xref: /qemu/target/arm/helper.c (revision 6e76d35f2375c3ef58aaaccbe5cee54b20a1f74a)
1 /*
2  * ARM generic helpers.
3  *
4  * This code is licensed under the GNU GPL v2 or later.
5  *
6  * SPDX-License-Identifier: GPL-2.0-or-later
7  */
8 
9 #include "qemu/osdep.h"
10 #include "qemu/units.h"
11 #include "qemu/log.h"
12 #include "target/arm/idau.h"
13 #include "trace.h"
14 #include "cpu.h"
15 #include "internals.h"
16 #include "exec/helper-proto.h"
17 #include "qemu/host-utils.h"
18 #include "qemu/main-loop.h"
19 #include "qemu/timer.h"
20 #include "qemu/bitops.h"
21 #include "qemu/crc32c.h"
22 #include "qemu/qemu-print.h"
23 #include "exec/exec-all.h"
24 #include <zlib.h> /* For crc32 */
25 #include "hw/irq.h"
26 #include "semihosting/semihost.h"
27 #include "sysemu/cpus.h"
28 #include "sysemu/cpu-timers.h"
29 #include "sysemu/kvm.h"
30 #include "qemu/range.h"
31 #include "qapi/qapi-commands-machine-target.h"
32 #include "qapi/error.h"
33 #include "qemu/guest-random.h"
34 #ifdef CONFIG_TCG
35 #include "arm_ldst.h"
36 #include "exec/cpu_ldst.h"
37 #include "semihosting/common-semi.h"
38 #endif
39 #include "cpregs.h"
40 
41 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
42 #define PMCR_NUM_COUNTERS 4 /* QEMU IMPDEF choice */
43 
44 #ifndef CONFIG_USER_ONLY
45 
46 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
47                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
48                                bool s1_is_el0,
49                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
50                                target_ulong *page_size_ptr,
51                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
52     __attribute__((nonnull));
53 #endif
54 
55 static void switch_mode(CPUARMState *env, int mode);
56 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx);
57 
58 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
59 {
60     assert(ri->fieldoffset);
61     if (cpreg_field_is_64bit(ri)) {
62         return CPREG_FIELD64(env, ri);
63     } else {
64         return CPREG_FIELD32(env, ri);
65     }
66 }
67 
68 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
69                       uint64_t value)
70 {
71     assert(ri->fieldoffset);
72     if (cpreg_field_is_64bit(ri)) {
73         CPREG_FIELD64(env, ri) = value;
74     } else {
75         CPREG_FIELD32(env, ri) = value;
76     }
77 }
78 
79 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
80 {
81     return (char *)env + ri->fieldoffset;
82 }
83 
84 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
85 {
86     /* Raw read of a coprocessor register (as needed for migration, etc). */
87     if (ri->type & ARM_CP_CONST) {
88         return ri->resetvalue;
89     } else if (ri->raw_readfn) {
90         return ri->raw_readfn(env, ri);
91     } else if (ri->readfn) {
92         return ri->readfn(env, ri);
93     } else {
94         return raw_read(env, ri);
95     }
96 }
97 
98 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
99                              uint64_t v)
100 {
101     /* Raw write of a coprocessor register (as needed for migration, etc).
102      * Note that constant registers are treated as write-ignored; the
103      * caller should check for success by whether a readback gives the
104      * value written.
105      */
106     if (ri->type & ARM_CP_CONST) {
107         return;
108     } else if (ri->raw_writefn) {
109         ri->raw_writefn(env, ri, v);
110     } else if (ri->writefn) {
111         ri->writefn(env, ri, v);
112     } else {
113         raw_write(env, ri, v);
114     }
115 }
116 
117 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
118 {
119    /* Return true if the regdef would cause an assertion if you called
120     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
121     * program bug for it not to have the NO_RAW flag).
122     * NB that returning false here doesn't necessarily mean that calling
123     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
124     * read/write access functions which are safe for raw use" from "has
125     * read/write access functions which have side effects but has forgotten
126     * to provide raw access functions".
127     * The tests here line up with the conditions in read/write_raw_cp_reg()
128     * and assertions in raw_read()/raw_write().
129     */
130     if ((ri->type & ARM_CP_CONST) ||
131         ri->fieldoffset ||
132         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
133         return false;
134     }
135     return true;
136 }
137 
138 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
139 {
140     /* Write the coprocessor state from cpu->env to the (index,value) list. */
141     int i;
142     bool ok = true;
143 
144     for (i = 0; i < cpu->cpreg_array_len; i++) {
145         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
146         const ARMCPRegInfo *ri;
147         uint64_t newval;
148 
149         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
150         if (!ri) {
151             ok = false;
152             continue;
153         }
154         if (ri->type & ARM_CP_NO_RAW) {
155             continue;
156         }
157 
158         newval = read_raw_cp_reg(&cpu->env, ri);
159         if (kvm_sync) {
160             /*
161              * Only sync if the previous list->cpustate sync succeeded.
162              * Rather than tracking the success/failure state for every
163              * item in the list, we just recheck "does the raw write we must
164              * have made in write_list_to_cpustate() read back OK" here.
165              */
166             uint64_t oldval = cpu->cpreg_values[i];
167 
168             if (oldval == newval) {
169                 continue;
170             }
171 
172             write_raw_cp_reg(&cpu->env, ri, oldval);
173             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
174                 continue;
175             }
176 
177             write_raw_cp_reg(&cpu->env, ri, newval);
178         }
179         cpu->cpreg_values[i] = newval;
180     }
181     return ok;
182 }
183 
184 bool write_list_to_cpustate(ARMCPU *cpu)
185 {
186     int i;
187     bool ok = true;
188 
189     for (i = 0; i < cpu->cpreg_array_len; i++) {
190         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
191         uint64_t v = cpu->cpreg_values[i];
192         const ARMCPRegInfo *ri;
193 
194         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
195         if (!ri) {
196             ok = false;
197             continue;
198         }
199         if (ri->type & ARM_CP_NO_RAW) {
200             continue;
201         }
202         /* Write value and confirm it reads back as written
203          * (to catch read-only registers and partially read-only
204          * registers where the incoming migration value doesn't match)
205          */
206         write_raw_cp_reg(&cpu->env, ri, v);
207         if (read_raw_cp_reg(&cpu->env, ri) != v) {
208             ok = false;
209         }
210     }
211     return ok;
212 }
213 
214 static void add_cpreg_to_list(gpointer key, gpointer opaque)
215 {
216     ARMCPU *cpu = opaque;
217     uint32_t regidx = (uintptr_t)key;
218     const ARMCPRegInfo *ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
219 
220     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
221         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
222         /* The value array need not be initialized at this point */
223         cpu->cpreg_array_len++;
224     }
225 }
226 
227 static void count_cpreg(gpointer key, gpointer opaque)
228 {
229     ARMCPU *cpu = opaque;
230     const ARMCPRegInfo *ri;
231 
232     ri = g_hash_table_lookup(cpu->cp_regs, key);
233 
234     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
235         cpu->cpreg_array_len++;
236     }
237 }
238 
239 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
240 {
241     uint64_t aidx = cpreg_to_kvm_id((uintptr_t)a);
242     uint64_t bidx = cpreg_to_kvm_id((uintptr_t)b);
243 
244     if (aidx > bidx) {
245         return 1;
246     }
247     if (aidx < bidx) {
248         return -1;
249     }
250     return 0;
251 }
252 
253 void init_cpreg_list(ARMCPU *cpu)
254 {
255     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
256      * Note that we require cpreg_tuples[] to be sorted by key ID.
257      */
258     GList *keys;
259     int arraylen;
260 
261     keys = g_hash_table_get_keys(cpu->cp_regs);
262     keys = g_list_sort(keys, cpreg_key_compare);
263 
264     cpu->cpreg_array_len = 0;
265 
266     g_list_foreach(keys, count_cpreg, cpu);
267 
268     arraylen = cpu->cpreg_array_len;
269     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
270     cpu->cpreg_values = g_new(uint64_t, arraylen);
271     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
272     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
273     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
274     cpu->cpreg_array_len = 0;
275 
276     g_list_foreach(keys, add_cpreg_to_list, cpu);
277 
278     assert(cpu->cpreg_array_len == arraylen);
279 
280     g_list_free(keys);
281 }
282 
283 /*
284  * Some registers are not accessible from AArch32 EL3 if SCR.NS == 0.
285  */
286 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
287                                         const ARMCPRegInfo *ri,
288                                         bool isread)
289 {
290     if (!is_a64(env) && arm_current_el(env) == 3 &&
291         arm_is_secure_below_el3(env)) {
292         return CP_ACCESS_TRAP_UNCATEGORIZED;
293     }
294     return CP_ACCESS_OK;
295 }
296 
297 /* Some secure-only AArch32 registers trap to EL3 if used from
298  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
299  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
300  * We assume that the .access field is set to PL1_RW.
301  */
302 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
303                                             const ARMCPRegInfo *ri,
304                                             bool isread)
305 {
306     if (arm_current_el(env) == 3) {
307         return CP_ACCESS_OK;
308     }
309     if (arm_is_secure_below_el3(env)) {
310         if (env->cp15.scr_el3 & SCR_EEL2) {
311             return CP_ACCESS_TRAP_EL2;
312         }
313         return CP_ACCESS_TRAP_EL3;
314     }
315     /* This will be EL1 NS and EL2 NS, which just UNDEF */
316     return CP_ACCESS_TRAP_UNCATEGORIZED;
317 }
318 
319 static uint64_t arm_mdcr_el2_eff(CPUARMState *env)
320 {
321     return arm_is_el2_enabled(env) ? env->cp15.mdcr_el2 : 0;
322 }
323 
324 /* Check for traps to "powerdown debug" registers, which are controlled
325  * by MDCR.TDOSA
326  */
327 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
328                                    bool isread)
329 {
330     int el = arm_current_el(env);
331     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
332     bool mdcr_el2_tdosa = (mdcr_el2 & MDCR_TDOSA) || (mdcr_el2 & MDCR_TDE) ||
333         (arm_hcr_el2_eff(env) & HCR_TGE);
334 
335     if (el < 2 && mdcr_el2_tdosa) {
336         return CP_ACCESS_TRAP_EL2;
337     }
338     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
339         return CP_ACCESS_TRAP_EL3;
340     }
341     return CP_ACCESS_OK;
342 }
343 
344 /* Check for traps to "debug ROM" registers, which are controlled
345  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
346  */
347 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
348                                   bool isread)
349 {
350     int el = arm_current_el(env);
351     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
352     bool mdcr_el2_tdra = (mdcr_el2 & MDCR_TDRA) || (mdcr_el2 & MDCR_TDE) ||
353         (arm_hcr_el2_eff(env) & HCR_TGE);
354 
355     if (el < 2 && mdcr_el2_tdra) {
356         return CP_ACCESS_TRAP_EL2;
357     }
358     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
359         return CP_ACCESS_TRAP_EL3;
360     }
361     return CP_ACCESS_OK;
362 }
363 
364 /* Check for traps to general debug registers, which are controlled
365  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
366  */
367 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
368                                   bool isread)
369 {
370     int el = arm_current_el(env);
371     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
372     bool mdcr_el2_tda = (mdcr_el2 & MDCR_TDA) || (mdcr_el2 & MDCR_TDE) ||
373         (arm_hcr_el2_eff(env) & HCR_TGE);
374 
375     if (el < 2 && mdcr_el2_tda) {
376         return CP_ACCESS_TRAP_EL2;
377     }
378     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
379         return CP_ACCESS_TRAP_EL3;
380     }
381     return CP_ACCESS_OK;
382 }
383 
384 /* Check for traps to performance monitor registers, which are controlled
385  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
386  */
387 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
388                                  bool isread)
389 {
390     int el = arm_current_el(env);
391     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
392 
393     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
394         return CP_ACCESS_TRAP_EL2;
395     }
396     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
397         return CP_ACCESS_TRAP_EL3;
398     }
399     return CP_ACCESS_OK;
400 }
401 
402 /* Check for traps from EL1 due to HCR_EL2.TVM and HCR_EL2.TRVM.  */
403 static CPAccessResult access_tvm_trvm(CPUARMState *env, const ARMCPRegInfo *ri,
404                                       bool isread)
405 {
406     if (arm_current_el(env) == 1) {
407         uint64_t trap = isread ? HCR_TRVM : HCR_TVM;
408         if (arm_hcr_el2_eff(env) & trap) {
409             return CP_ACCESS_TRAP_EL2;
410         }
411     }
412     return CP_ACCESS_OK;
413 }
414 
415 /* Check for traps from EL1 due to HCR_EL2.TSW.  */
416 static CPAccessResult access_tsw(CPUARMState *env, const ARMCPRegInfo *ri,
417                                  bool isread)
418 {
419     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TSW)) {
420         return CP_ACCESS_TRAP_EL2;
421     }
422     return CP_ACCESS_OK;
423 }
424 
425 /* Check for traps from EL1 due to HCR_EL2.TACR.  */
426 static CPAccessResult access_tacr(CPUARMState *env, const ARMCPRegInfo *ri,
427                                   bool isread)
428 {
429     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TACR)) {
430         return CP_ACCESS_TRAP_EL2;
431     }
432     return CP_ACCESS_OK;
433 }
434 
435 /* Check for traps from EL1 due to HCR_EL2.TTLB. */
436 static CPAccessResult access_ttlb(CPUARMState *env, const ARMCPRegInfo *ri,
437                                   bool isread)
438 {
439     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TTLB)) {
440         return CP_ACCESS_TRAP_EL2;
441     }
442     return CP_ACCESS_OK;
443 }
444 
445 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
446 {
447     ARMCPU *cpu = env_archcpu(env);
448 
449     raw_write(env, ri, value);
450     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
451 }
452 
453 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
454 {
455     ARMCPU *cpu = env_archcpu(env);
456 
457     if (raw_read(env, ri) != value) {
458         /* Unlike real hardware the qemu TLB uses virtual addresses,
459          * not modified virtual addresses, so this causes a TLB flush.
460          */
461         tlb_flush(CPU(cpu));
462         raw_write(env, ri, value);
463     }
464 }
465 
466 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
467                              uint64_t value)
468 {
469     ARMCPU *cpu = env_archcpu(env);
470 
471     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
472         && !extended_addresses_enabled(env)) {
473         /* For VMSA (when not using the LPAE long descriptor page table
474          * format) this register includes the ASID, so do a TLB flush.
475          * For PMSA it is purely a process ID and no action is needed.
476          */
477         tlb_flush(CPU(cpu));
478     }
479     raw_write(env, ri, value);
480 }
481 
482 /* IS variants of TLB operations must affect all cores */
483 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
484                              uint64_t value)
485 {
486     CPUState *cs = env_cpu(env);
487 
488     tlb_flush_all_cpus_synced(cs);
489 }
490 
491 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
492                              uint64_t value)
493 {
494     CPUState *cs = env_cpu(env);
495 
496     tlb_flush_all_cpus_synced(cs);
497 }
498 
499 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
500                              uint64_t value)
501 {
502     CPUState *cs = env_cpu(env);
503 
504     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
505 }
506 
507 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
508                              uint64_t value)
509 {
510     CPUState *cs = env_cpu(env);
511 
512     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
513 }
514 
515 /*
516  * Non-IS variants of TLB operations are upgraded to
517  * IS versions if we are at EL1 and HCR_EL2.FB is effectively set to
518  * force broadcast of these operations.
519  */
520 static bool tlb_force_broadcast(CPUARMState *env)
521 {
522     return arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_FB);
523 }
524 
525 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
526                           uint64_t value)
527 {
528     /* Invalidate all (TLBIALL) */
529     CPUState *cs = env_cpu(env);
530 
531     if (tlb_force_broadcast(env)) {
532         tlb_flush_all_cpus_synced(cs);
533     } else {
534         tlb_flush(cs);
535     }
536 }
537 
538 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
539                           uint64_t value)
540 {
541     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
542     CPUState *cs = env_cpu(env);
543 
544     value &= TARGET_PAGE_MASK;
545     if (tlb_force_broadcast(env)) {
546         tlb_flush_page_all_cpus_synced(cs, value);
547     } else {
548         tlb_flush_page(cs, value);
549     }
550 }
551 
552 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
553                            uint64_t value)
554 {
555     /* Invalidate by ASID (TLBIASID) */
556     CPUState *cs = env_cpu(env);
557 
558     if (tlb_force_broadcast(env)) {
559         tlb_flush_all_cpus_synced(cs);
560     } else {
561         tlb_flush(cs);
562     }
563 }
564 
565 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
566                            uint64_t value)
567 {
568     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
569     CPUState *cs = env_cpu(env);
570 
571     value &= TARGET_PAGE_MASK;
572     if (tlb_force_broadcast(env)) {
573         tlb_flush_page_all_cpus_synced(cs, value);
574     } else {
575         tlb_flush_page(cs, value);
576     }
577 }
578 
579 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
580                                uint64_t value)
581 {
582     CPUState *cs = env_cpu(env);
583 
584     tlb_flush_by_mmuidx(cs,
585                         ARMMMUIdxBit_E10_1 |
586                         ARMMMUIdxBit_E10_1_PAN |
587                         ARMMMUIdxBit_E10_0);
588 }
589 
590 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
591                                   uint64_t value)
592 {
593     CPUState *cs = env_cpu(env);
594 
595     tlb_flush_by_mmuidx_all_cpus_synced(cs,
596                                         ARMMMUIdxBit_E10_1 |
597                                         ARMMMUIdxBit_E10_1_PAN |
598                                         ARMMMUIdxBit_E10_0);
599 }
600 
601 
602 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
603                               uint64_t value)
604 {
605     CPUState *cs = env_cpu(env);
606 
607     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_E2);
608 }
609 
610 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
611                                  uint64_t value)
612 {
613     CPUState *cs = env_cpu(env);
614 
615     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_E2);
616 }
617 
618 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
619                               uint64_t value)
620 {
621     CPUState *cs = env_cpu(env);
622     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
623 
624     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_E2);
625 }
626 
627 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
628                                  uint64_t value)
629 {
630     CPUState *cs = env_cpu(env);
631     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
632 
633     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
634                                              ARMMMUIdxBit_E2);
635 }
636 
637 static const ARMCPRegInfo cp_reginfo[] = {
638     /* Define the secure and non-secure FCSE identifier CP registers
639      * separately because there is no secure bank in V8 (no _EL3).  This allows
640      * the secure register to be properly reset and migrated. There is also no
641      * v8 EL1 version of the register so the non-secure instance stands alone.
642      */
643     { .name = "FCSEIDR",
644       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
645       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
646       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
647       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
648     { .name = "FCSEIDR_S",
649       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
650       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
651       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
652       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
653     /* Define the secure and non-secure context identifier CP registers
654      * separately because there is no secure bank in V8 (no _EL3).  This allows
655      * the secure register to be properly reset and migrated.  In the
656      * non-secure case, the 32-bit register will have reset and migration
657      * disabled during registration as it is handled by the 64-bit instance.
658      */
659     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
660       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
661       .access = PL1_RW, .accessfn = access_tvm_trvm,
662       .secure = ARM_CP_SECSTATE_NS,
663       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
664       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
665     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
666       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
667       .access = PL1_RW, .accessfn = access_tvm_trvm,
668       .secure = ARM_CP_SECSTATE_S,
669       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
670       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
671 };
672 
673 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
674     /* NB: Some of these registers exist in v8 but with more precise
675      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
676      */
677     /* MMU Domain access control / MPU write buffer control */
678     { .name = "DACR",
679       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
680       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
681       .writefn = dacr_write, .raw_writefn = raw_write,
682       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
683                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
684     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
685      * For v6 and v5, these mappings are overly broad.
686      */
687     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
688       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
689     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
690       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
691     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
692       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
693     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
694       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
695     /* Cache maintenance ops; some of this space may be overridden later. */
696     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
697       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
698       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
699 };
700 
701 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
702     /* Not all pre-v6 cores implemented this WFI, so this is slightly
703      * over-broad.
704      */
705     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
706       .access = PL1_W, .type = ARM_CP_WFI },
707 };
708 
709 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
710     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
711      * is UNPREDICTABLE; we choose to NOP as most implementations do).
712      */
713     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
714       .access = PL1_W, .type = ARM_CP_WFI },
715     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
716      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
717      * OMAPCP will override this space.
718      */
719     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
720       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
721       .resetvalue = 0 },
722     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
723       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
724       .resetvalue = 0 },
725     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
726     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
727       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
728       .resetvalue = 0 },
729     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
730      * implementing it as RAZ means the "debug architecture version" bits
731      * will read as a reserved value, which should cause Linux to not try
732      * to use the debug hardware.
733      */
734     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
735       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
736     /* MMU TLB control. Note that the wildcarding means we cover not just
737      * the unified TLB ops but also the dside/iside/inner-shareable variants.
738      */
739     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
740       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
741       .type = ARM_CP_NO_RAW },
742     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
743       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
744       .type = ARM_CP_NO_RAW },
745     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
746       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
747       .type = ARM_CP_NO_RAW },
748     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
749       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
750       .type = ARM_CP_NO_RAW },
751     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
752       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
753     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
754       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
755 };
756 
757 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
758                         uint64_t value)
759 {
760     uint32_t mask = 0;
761 
762     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
763     if (!arm_feature(env, ARM_FEATURE_V8)) {
764         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
765          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
766          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
767          */
768         if (cpu_isar_feature(aa32_vfp_simd, env_archcpu(env))) {
769             /* VFP coprocessor: cp10 & cp11 [23:20] */
770             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
771 
772             if (!arm_feature(env, ARM_FEATURE_NEON)) {
773                 /* ASEDIS [31] bit is RAO/WI */
774                 value |= (1 << 31);
775             }
776 
777             /* VFPv3 and upwards with NEON implement 32 double precision
778              * registers (D0-D31).
779              */
780             if (!cpu_isar_feature(aa32_simd_r32, env_archcpu(env))) {
781                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
782                 value |= (1 << 30);
783             }
784         }
785         value &= mask;
786     }
787 
788     /*
789      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
790      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
791      */
792     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
793         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
794         value &= ~(0xf << 20);
795         value |= env->cp15.cpacr_el1 & (0xf << 20);
796     }
797 
798     env->cp15.cpacr_el1 = value;
799 }
800 
801 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
802 {
803     /*
804      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
805      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
806      */
807     uint64_t value = env->cp15.cpacr_el1;
808 
809     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
810         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
811         value &= ~(0xf << 20);
812     }
813     return value;
814 }
815 
816 
817 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
818 {
819     /* Call cpacr_write() so that we reset with the correct RAO bits set
820      * for our CPU features.
821      */
822     cpacr_write(env, ri, 0);
823 }
824 
825 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
826                                    bool isread)
827 {
828     if (arm_feature(env, ARM_FEATURE_V8)) {
829         /* Check if CPACR accesses are to be trapped to EL2 */
830         if (arm_current_el(env) == 1 && arm_is_el2_enabled(env) &&
831             (env->cp15.cptr_el[2] & CPTR_TCPAC)) {
832             return CP_ACCESS_TRAP_EL2;
833         /* Check if CPACR accesses are to be trapped to EL3 */
834         } else if (arm_current_el(env) < 3 &&
835                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
836             return CP_ACCESS_TRAP_EL3;
837         }
838     }
839 
840     return CP_ACCESS_OK;
841 }
842 
843 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
844                                   bool isread)
845 {
846     /* Check if CPTR accesses are set to trap to EL3 */
847     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
848         return CP_ACCESS_TRAP_EL3;
849     }
850 
851     return CP_ACCESS_OK;
852 }
853 
854 static const ARMCPRegInfo v6_cp_reginfo[] = {
855     /* prefetch by MVA in v6, NOP in v7 */
856     { .name = "MVA_prefetch",
857       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
858       .access = PL1_W, .type = ARM_CP_NOP },
859     /* We need to break the TB after ISB to execute self-modifying code
860      * correctly and also to take any pending interrupts immediately.
861      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
862      */
863     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
864       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
865     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
866       .access = PL0_W, .type = ARM_CP_NOP },
867     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
868       .access = PL0_W, .type = ARM_CP_NOP },
869     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
870       .access = PL1_RW, .accessfn = access_tvm_trvm,
871       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
872                              offsetof(CPUARMState, cp15.ifar_ns) },
873       .resetvalue = 0, },
874     /* Watchpoint Fault Address Register : should actually only be present
875      * for 1136, 1176, 11MPCore.
876      */
877     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
878       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
879     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
880       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
881       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
882       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
883 };
884 
885 typedef struct pm_event {
886     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
887     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
888     bool (*supported)(CPUARMState *);
889     /*
890      * Retrieve the current count of the underlying event. The programmed
891      * counters hold a difference from the return value from this function
892      */
893     uint64_t (*get_count)(CPUARMState *);
894     /*
895      * Return how many nanoseconds it will take (at a minimum) for count events
896      * to occur. A negative value indicates the counter will never overflow, or
897      * that the counter has otherwise arranged for the overflow bit to be set
898      * and the PMU interrupt to be raised on overflow.
899      */
900     int64_t (*ns_per_count)(uint64_t);
901 } pm_event;
902 
903 static bool event_always_supported(CPUARMState *env)
904 {
905     return true;
906 }
907 
908 static uint64_t swinc_get_count(CPUARMState *env)
909 {
910     /*
911      * SW_INCR events are written directly to the pmevcntr's by writes to
912      * PMSWINC, so there is no underlying count maintained by the PMU itself
913      */
914     return 0;
915 }
916 
917 static int64_t swinc_ns_per(uint64_t ignored)
918 {
919     return -1;
920 }
921 
922 /*
923  * Return the underlying cycle count for the PMU cycle counters. If we're in
924  * usermode, simply return 0.
925  */
926 static uint64_t cycles_get_count(CPUARMState *env)
927 {
928 #ifndef CONFIG_USER_ONLY
929     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
930                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
931 #else
932     return cpu_get_host_ticks();
933 #endif
934 }
935 
936 #ifndef CONFIG_USER_ONLY
937 static int64_t cycles_ns_per(uint64_t cycles)
938 {
939     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
940 }
941 
942 static bool instructions_supported(CPUARMState *env)
943 {
944     return icount_enabled() == 1; /* Precise instruction counting */
945 }
946 
947 static uint64_t instructions_get_count(CPUARMState *env)
948 {
949     return (uint64_t)icount_get_raw();
950 }
951 
952 static int64_t instructions_ns_per(uint64_t icount)
953 {
954     return icount_to_ns((int64_t)icount);
955 }
956 #endif
957 
958 static bool pmu_8_1_events_supported(CPUARMState *env)
959 {
960     /* For events which are supported in any v8.1 PMU */
961     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
962 }
963 
964 static bool pmu_8_4_events_supported(CPUARMState *env)
965 {
966     /* For events which are supported in any v8.1 PMU */
967     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
968 }
969 
970 static uint64_t zero_event_get_count(CPUARMState *env)
971 {
972     /* For events which on QEMU never fire, so their count is always zero */
973     return 0;
974 }
975 
976 static int64_t zero_event_ns_per(uint64_t cycles)
977 {
978     /* An event which never fires can never overflow */
979     return -1;
980 }
981 
982 static const pm_event pm_events[] = {
983     { .number = 0x000, /* SW_INCR */
984       .supported = event_always_supported,
985       .get_count = swinc_get_count,
986       .ns_per_count = swinc_ns_per,
987     },
988 #ifndef CONFIG_USER_ONLY
989     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
990       .supported = instructions_supported,
991       .get_count = instructions_get_count,
992       .ns_per_count = instructions_ns_per,
993     },
994     { .number = 0x011, /* CPU_CYCLES, Cycle */
995       .supported = event_always_supported,
996       .get_count = cycles_get_count,
997       .ns_per_count = cycles_ns_per,
998     },
999 #endif
1000     { .number = 0x023, /* STALL_FRONTEND */
1001       .supported = pmu_8_1_events_supported,
1002       .get_count = zero_event_get_count,
1003       .ns_per_count = zero_event_ns_per,
1004     },
1005     { .number = 0x024, /* STALL_BACKEND */
1006       .supported = pmu_8_1_events_supported,
1007       .get_count = zero_event_get_count,
1008       .ns_per_count = zero_event_ns_per,
1009     },
1010     { .number = 0x03c, /* STALL */
1011       .supported = pmu_8_4_events_supported,
1012       .get_count = zero_event_get_count,
1013       .ns_per_count = zero_event_ns_per,
1014     },
1015 };
1016 
1017 /*
1018  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1019  * events (i.e. the statistical profiling extension), this implementation
1020  * should first be updated to something sparse instead of the current
1021  * supported_event_map[] array.
1022  */
1023 #define MAX_EVENT_ID 0x3c
1024 #define UNSUPPORTED_EVENT UINT16_MAX
1025 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1026 
1027 /*
1028  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1029  * of ARM event numbers to indices in our pm_events array.
1030  *
1031  * Note: Events in the 0x40XX range are not currently supported.
1032  */
1033 void pmu_init(ARMCPU *cpu)
1034 {
1035     unsigned int i;
1036 
1037     /*
1038      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1039      * events to them
1040      */
1041     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1042         supported_event_map[i] = UNSUPPORTED_EVENT;
1043     }
1044     cpu->pmceid0 = 0;
1045     cpu->pmceid1 = 0;
1046 
1047     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1048         const pm_event *cnt = &pm_events[i];
1049         assert(cnt->number <= MAX_EVENT_ID);
1050         /* We do not currently support events in the 0x40xx range */
1051         assert(cnt->number <= 0x3f);
1052 
1053         if (cnt->supported(&cpu->env)) {
1054             supported_event_map[cnt->number] = i;
1055             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1056             if (cnt->number & 0x20) {
1057                 cpu->pmceid1 |= event_mask;
1058             } else {
1059                 cpu->pmceid0 |= event_mask;
1060             }
1061         }
1062     }
1063 }
1064 
1065 /*
1066  * Check at runtime whether a PMU event is supported for the current machine
1067  */
1068 static bool event_supported(uint16_t number)
1069 {
1070     if (number > MAX_EVENT_ID) {
1071         return false;
1072     }
1073     return supported_event_map[number] != UNSUPPORTED_EVENT;
1074 }
1075 
1076 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1077                                    bool isread)
1078 {
1079     /* Performance monitor registers user accessibility is controlled
1080      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1081      * trapping to EL2 or EL3 for other accesses.
1082      */
1083     int el = arm_current_el(env);
1084     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1085 
1086     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1087         return CP_ACCESS_TRAP;
1088     }
1089     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
1090         return CP_ACCESS_TRAP_EL2;
1091     }
1092     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1093         return CP_ACCESS_TRAP_EL3;
1094     }
1095 
1096     return CP_ACCESS_OK;
1097 }
1098 
1099 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1100                                            const ARMCPRegInfo *ri,
1101                                            bool isread)
1102 {
1103     /* ER: event counter read trap control */
1104     if (arm_feature(env, ARM_FEATURE_V8)
1105         && arm_current_el(env) == 0
1106         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1107         && isread) {
1108         return CP_ACCESS_OK;
1109     }
1110 
1111     return pmreg_access(env, ri, isread);
1112 }
1113 
1114 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1115                                          const ARMCPRegInfo *ri,
1116                                          bool isread)
1117 {
1118     /* SW: software increment write trap control */
1119     if (arm_feature(env, ARM_FEATURE_V8)
1120         && arm_current_el(env) == 0
1121         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1122         && !isread) {
1123         return CP_ACCESS_OK;
1124     }
1125 
1126     return pmreg_access(env, ri, isread);
1127 }
1128 
1129 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1130                                         const ARMCPRegInfo *ri,
1131                                         bool isread)
1132 {
1133     /* ER: event counter read trap control */
1134     if (arm_feature(env, ARM_FEATURE_V8)
1135         && arm_current_el(env) == 0
1136         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1137         return CP_ACCESS_OK;
1138     }
1139 
1140     return pmreg_access(env, ri, isread);
1141 }
1142 
1143 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1144                                          const ARMCPRegInfo *ri,
1145                                          bool isread)
1146 {
1147     /* CR: cycle counter read trap control */
1148     if (arm_feature(env, ARM_FEATURE_V8)
1149         && arm_current_el(env) == 0
1150         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1151         && isread) {
1152         return CP_ACCESS_OK;
1153     }
1154 
1155     return pmreg_access(env, ri, isread);
1156 }
1157 
1158 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1159  * the current EL, security state, and register configuration.
1160  */
1161 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1162 {
1163     uint64_t filter;
1164     bool e, p, u, nsk, nsu, nsh, m;
1165     bool enabled, prohibited, filtered;
1166     bool secure = arm_is_secure(env);
1167     int el = arm_current_el(env);
1168     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1169     uint8_t hpmn = mdcr_el2 & MDCR_HPMN;
1170 
1171     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1172         return false;
1173     }
1174 
1175     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1176             (counter < hpmn || counter == 31)) {
1177         e = env->cp15.c9_pmcr & PMCRE;
1178     } else {
1179         e = mdcr_el2 & MDCR_HPME;
1180     }
1181     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1182 
1183     if (!secure) {
1184         if (el == 2 && (counter < hpmn || counter == 31)) {
1185             prohibited = mdcr_el2 & MDCR_HPMD;
1186         } else {
1187             prohibited = false;
1188         }
1189     } else {
1190         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1191            !(env->cp15.mdcr_el3 & MDCR_SPME);
1192     }
1193 
1194     if (prohibited && counter == 31) {
1195         prohibited = env->cp15.c9_pmcr & PMCRDP;
1196     }
1197 
1198     if (counter == 31) {
1199         filter = env->cp15.pmccfiltr_el0;
1200     } else {
1201         filter = env->cp15.c14_pmevtyper[counter];
1202     }
1203 
1204     p   = filter & PMXEVTYPER_P;
1205     u   = filter & PMXEVTYPER_U;
1206     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1207     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1208     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1209     m   = arm_el_is_aa64(env, 1) &&
1210               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1211 
1212     if (el == 0) {
1213         filtered = secure ? u : u != nsu;
1214     } else if (el == 1) {
1215         filtered = secure ? p : p != nsk;
1216     } else if (el == 2) {
1217         filtered = !nsh;
1218     } else { /* EL3 */
1219         filtered = m != p;
1220     }
1221 
1222     if (counter != 31) {
1223         /*
1224          * If not checking PMCCNTR, ensure the counter is setup to an event we
1225          * support
1226          */
1227         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1228         if (!event_supported(event)) {
1229             return false;
1230         }
1231     }
1232 
1233     return enabled && !prohibited && !filtered;
1234 }
1235 
1236 static void pmu_update_irq(CPUARMState *env)
1237 {
1238     ARMCPU *cpu = env_archcpu(env);
1239     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1240             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1241 }
1242 
1243 /*
1244  * Ensure c15_ccnt is the guest-visible count so that operations such as
1245  * enabling/disabling the counter or filtering, modifying the count itself,
1246  * etc. can be done logically. This is essentially a no-op if the counter is
1247  * not enabled at the time of the call.
1248  */
1249 static void pmccntr_op_start(CPUARMState *env)
1250 {
1251     uint64_t cycles = cycles_get_count(env);
1252 
1253     if (pmu_counter_enabled(env, 31)) {
1254         uint64_t eff_cycles = cycles;
1255         if (env->cp15.c9_pmcr & PMCRD) {
1256             /* Increment once every 64 processor clock cycles */
1257             eff_cycles /= 64;
1258         }
1259 
1260         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1261 
1262         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1263                                  1ull << 63 : 1ull << 31;
1264         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1265             env->cp15.c9_pmovsr |= (1 << 31);
1266             pmu_update_irq(env);
1267         }
1268 
1269         env->cp15.c15_ccnt = new_pmccntr;
1270     }
1271     env->cp15.c15_ccnt_delta = cycles;
1272 }
1273 
1274 /*
1275  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1276  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1277  * pmccntr_op_start.
1278  */
1279 static void pmccntr_op_finish(CPUARMState *env)
1280 {
1281     if (pmu_counter_enabled(env, 31)) {
1282 #ifndef CONFIG_USER_ONLY
1283         /* Calculate when the counter will next overflow */
1284         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1285         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1286             remaining_cycles = (uint32_t)remaining_cycles;
1287         }
1288         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1289 
1290         if (overflow_in > 0) {
1291             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1292                 overflow_in;
1293             ARMCPU *cpu = env_archcpu(env);
1294             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1295         }
1296 #endif
1297 
1298         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1299         if (env->cp15.c9_pmcr & PMCRD) {
1300             /* Increment once every 64 processor clock cycles */
1301             prev_cycles /= 64;
1302         }
1303         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1304     }
1305 }
1306 
1307 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1308 {
1309 
1310     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1311     uint64_t count = 0;
1312     if (event_supported(event)) {
1313         uint16_t event_idx = supported_event_map[event];
1314         count = pm_events[event_idx].get_count(env);
1315     }
1316 
1317     if (pmu_counter_enabled(env, counter)) {
1318         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1319 
1320         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1321             env->cp15.c9_pmovsr |= (1 << counter);
1322             pmu_update_irq(env);
1323         }
1324         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1325     }
1326     env->cp15.c14_pmevcntr_delta[counter] = count;
1327 }
1328 
1329 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1330 {
1331     if (pmu_counter_enabled(env, counter)) {
1332 #ifndef CONFIG_USER_ONLY
1333         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1334         uint16_t event_idx = supported_event_map[event];
1335         uint64_t delta = UINT32_MAX -
1336             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1337         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1338 
1339         if (overflow_in > 0) {
1340             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1341                 overflow_in;
1342             ARMCPU *cpu = env_archcpu(env);
1343             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1344         }
1345 #endif
1346 
1347         env->cp15.c14_pmevcntr_delta[counter] -=
1348             env->cp15.c14_pmevcntr[counter];
1349     }
1350 }
1351 
1352 void pmu_op_start(CPUARMState *env)
1353 {
1354     unsigned int i;
1355     pmccntr_op_start(env);
1356     for (i = 0; i < pmu_num_counters(env); i++) {
1357         pmevcntr_op_start(env, i);
1358     }
1359 }
1360 
1361 void pmu_op_finish(CPUARMState *env)
1362 {
1363     unsigned int i;
1364     pmccntr_op_finish(env);
1365     for (i = 0; i < pmu_num_counters(env); i++) {
1366         pmevcntr_op_finish(env, i);
1367     }
1368 }
1369 
1370 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1371 {
1372     pmu_op_start(&cpu->env);
1373 }
1374 
1375 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1376 {
1377     pmu_op_finish(&cpu->env);
1378 }
1379 
1380 void arm_pmu_timer_cb(void *opaque)
1381 {
1382     ARMCPU *cpu = opaque;
1383 
1384     /*
1385      * Update all the counter values based on the current underlying counts,
1386      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1387      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1388      * counter may expire.
1389      */
1390     pmu_op_start(&cpu->env);
1391     pmu_op_finish(&cpu->env);
1392 }
1393 
1394 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1395                        uint64_t value)
1396 {
1397     pmu_op_start(env);
1398 
1399     if (value & PMCRC) {
1400         /* The counter has been reset */
1401         env->cp15.c15_ccnt = 0;
1402     }
1403 
1404     if (value & PMCRP) {
1405         unsigned int i;
1406         for (i = 0; i < pmu_num_counters(env); i++) {
1407             env->cp15.c14_pmevcntr[i] = 0;
1408         }
1409     }
1410 
1411     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1412     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1413 
1414     pmu_op_finish(env);
1415 }
1416 
1417 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1418                           uint64_t value)
1419 {
1420     unsigned int i;
1421     for (i = 0; i < pmu_num_counters(env); i++) {
1422         /* Increment a counter's count iff: */
1423         if ((value & (1 << i)) && /* counter's bit is set */
1424                 /* counter is enabled and not filtered */
1425                 pmu_counter_enabled(env, i) &&
1426                 /* counter is SW_INCR */
1427                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1428             pmevcntr_op_start(env, i);
1429 
1430             /*
1431              * Detect if this write causes an overflow since we can't predict
1432              * PMSWINC overflows like we can for other events
1433              */
1434             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1435 
1436             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1437                 env->cp15.c9_pmovsr |= (1 << i);
1438                 pmu_update_irq(env);
1439             }
1440 
1441             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1442 
1443             pmevcntr_op_finish(env, i);
1444         }
1445     }
1446 }
1447 
1448 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1449 {
1450     uint64_t ret;
1451     pmccntr_op_start(env);
1452     ret = env->cp15.c15_ccnt;
1453     pmccntr_op_finish(env);
1454     return ret;
1455 }
1456 
1457 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1458                          uint64_t value)
1459 {
1460     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1461      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1462      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1463      * accessed.
1464      */
1465     env->cp15.c9_pmselr = value & 0x1f;
1466 }
1467 
1468 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1469                         uint64_t value)
1470 {
1471     pmccntr_op_start(env);
1472     env->cp15.c15_ccnt = value;
1473     pmccntr_op_finish(env);
1474 }
1475 
1476 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1477                             uint64_t value)
1478 {
1479     uint64_t cur_val = pmccntr_read(env, NULL);
1480 
1481     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1482 }
1483 
1484 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1485                             uint64_t value)
1486 {
1487     pmccntr_op_start(env);
1488     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1489     pmccntr_op_finish(env);
1490 }
1491 
1492 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1493                             uint64_t value)
1494 {
1495     pmccntr_op_start(env);
1496     /* M is not accessible from AArch32 */
1497     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1498         (value & PMCCFILTR);
1499     pmccntr_op_finish(env);
1500 }
1501 
1502 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1503 {
1504     /* M is not visible in AArch32 */
1505     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1506 }
1507 
1508 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1509                             uint64_t value)
1510 {
1511     value &= pmu_counter_mask(env);
1512     env->cp15.c9_pmcnten |= value;
1513 }
1514 
1515 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1516                              uint64_t value)
1517 {
1518     value &= pmu_counter_mask(env);
1519     env->cp15.c9_pmcnten &= ~value;
1520 }
1521 
1522 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1523                          uint64_t value)
1524 {
1525     value &= pmu_counter_mask(env);
1526     env->cp15.c9_pmovsr &= ~value;
1527     pmu_update_irq(env);
1528 }
1529 
1530 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1531                          uint64_t value)
1532 {
1533     value &= pmu_counter_mask(env);
1534     env->cp15.c9_pmovsr |= value;
1535     pmu_update_irq(env);
1536 }
1537 
1538 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1539                              uint64_t value, const uint8_t counter)
1540 {
1541     if (counter == 31) {
1542         pmccfiltr_write(env, ri, value);
1543     } else if (counter < pmu_num_counters(env)) {
1544         pmevcntr_op_start(env, counter);
1545 
1546         /*
1547          * If this counter's event type is changing, store the current
1548          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1549          * pmevcntr_op_finish has the correct baseline when it converts back to
1550          * a delta.
1551          */
1552         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1553             PMXEVTYPER_EVTCOUNT;
1554         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1555         if (old_event != new_event) {
1556             uint64_t count = 0;
1557             if (event_supported(new_event)) {
1558                 uint16_t event_idx = supported_event_map[new_event];
1559                 count = pm_events[event_idx].get_count(env);
1560             }
1561             env->cp15.c14_pmevcntr_delta[counter] = count;
1562         }
1563 
1564         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1565         pmevcntr_op_finish(env, counter);
1566     }
1567     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1568      * PMSELR value is equal to or greater than the number of implemented
1569      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1570      */
1571 }
1572 
1573 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1574                                const uint8_t counter)
1575 {
1576     if (counter == 31) {
1577         return env->cp15.pmccfiltr_el0;
1578     } else if (counter < pmu_num_counters(env)) {
1579         return env->cp15.c14_pmevtyper[counter];
1580     } else {
1581       /*
1582        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1583        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1584        */
1585         return 0;
1586     }
1587 }
1588 
1589 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1590                               uint64_t value)
1591 {
1592     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1593     pmevtyper_write(env, ri, value, counter);
1594 }
1595 
1596 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1597                                uint64_t value)
1598 {
1599     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1600     env->cp15.c14_pmevtyper[counter] = value;
1601 
1602     /*
1603      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1604      * pmu_op_finish calls when loading saved state for a migration. Because
1605      * we're potentially updating the type of event here, the value written to
1606      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1607      * different counter type. Therefore, we need to set this value to the
1608      * current count for the counter type we're writing so that pmu_op_finish
1609      * has the correct count for its calculation.
1610      */
1611     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1612     if (event_supported(event)) {
1613         uint16_t event_idx = supported_event_map[event];
1614         env->cp15.c14_pmevcntr_delta[counter] =
1615             pm_events[event_idx].get_count(env);
1616     }
1617 }
1618 
1619 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1620 {
1621     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1622     return pmevtyper_read(env, ri, counter);
1623 }
1624 
1625 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1626                              uint64_t value)
1627 {
1628     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1629 }
1630 
1631 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1632 {
1633     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1634 }
1635 
1636 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1637                              uint64_t value, uint8_t counter)
1638 {
1639     if (counter < pmu_num_counters(env)) {
1640         pmevcntr_op_start(env, counter);
1641         env->cp15.c14_pmevcntr[counter] = value;
1642         pmevcntr_op_finish(env, counter);
1643     }
1644     /*
1645      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1646      * are CONSTRAINED UNPREDICTABLE.
1647      */
1648 }
1649 
1650 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1651                               uint8_t counter)
1652 {
1653     if (counter < pmu_num_counters(env)) {
1654         uint64_t ret;
1655         pmevcntr_op_start(env, counter);
1656         ret = env->cp15.c14_pmevcntr[counter];
1657         pmevcntr_op_finish(env, counter);
1658         return ret;
1659     } else {
1660       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1661        * are CONSTRAINED UNPREDICTABLE. */
1662         return 0;
1663     }
1664 }
1665 
1666 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1667                              uint64_t value)
1668 {
1669     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1670     pmevcntr_write(env, ri, value, counter);
1671 }
1672 
1673 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1674 {
1675     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1676     return pmevcntr_read(env, ri, counter);
1677 }
1678 
1679 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1680                              uint64_t value)
1681 {
1682     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1683     assert(counter < pmu_num_counters(env));
1684     env->cp15.c14_pmevcntr[counter] = value;
1685     pmevcntr_write(env, ri, value, counter);
1686 }
1687 
1688 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1689 {
1690     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1691     assert(counter < pmu_num_counters(env));
1692     return env->cp15.c14_pmevcntr[counter];
1693 }
1694 
1695 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1696                              uint64_t value)
1697 {
1698     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1699 }
1700 
1701 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1702 {
1703     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1704 }
1705 
1706 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1707                             uint64_t value)
1708 {
1709     if (arm_feature(env, ARM_FEATURE_V8)) {
1710         env->cp15.c9_pmuserenr = value & 0xf;
1711     } else {
1712         env->cp15.c9_pmuserenr = value & 1;
1713     }
1714 }
1715 
1716 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1717                              uint64_t value)
1718 {
1719     /* We have no event counters so only the C bit can be changed */
1720     value &= pmu_counter_mask(env);
1721     env->cp15.c9_pminten |= value;
1722     pmu_update_irq(env);
1723 }
1724 
1725 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1726                              uint64_t value)
1727 {
1728     value &= pmu_counter_mask(env);
1729     env->cp15.c9_pminten &= ~value;
1730     pmu_update_irq(env);
1731 }
1732 
1733 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1734                        uint64_t value)
1735 {
1736     /* Note that even though the AArch64 view of this register has bits
1737      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1738      * architectural requirements for bits which are RES0 only in some
1739      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1740      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1741      */
1742     raw_write(env, ri, value & ~0x1FULL);
1743 }
1744 
1745 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1746 {
1747     /* Begin with base v8.0 state.  */
1748     uint32_t valid_mask = 0x3fff;
1749     ARMCPU *cpu = env_archcpu(env);
1750 
1751     if (ri->state == ARM_CP_STATE_AA64) {
1752         if (arm_feature(env, ARM_FEATURE_AARCH64) &&
1753             !cpu_isar_feature(aa64_aa32_el1, cpu)) {
1754                 value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1755         }
1756         valid_mask &= ~SCR_NET;
1757 
1758         if (cpu_isar_feature(aa64_ras, cpu)) {
1759             valid_mask |= SCR_TERR;
1760         }
1761         if (cpu_isar_feature(aa64_lor, cpu)) {
1762             valid_mask |= SCR_TLOR;
1763         }
1764         if (cpu_isar_feature(aa64_pauth, cpu)) {
1765             valid_mask |= SCR_API | SCR_APK;
1766         }
1767         if (cpu_isar_feature(aa64_sel2, cpu)) {
1768             valid_mask |= SCR_EEL2;
1769         }
1770         if (cpu_isar_feature(aa64_mte, cpu)) {
1771             valid_mask |= SCR_ATA;
1772         }
1773         if (cpu_isar_feature(aa64_scxtnum, cpu)) {
1774             valid_mask |= SCR_ENSCXT;
1775         }
1776     } else {
1777         valid_mask &= ~(SCR_RW | SCR_ST);
1778         if (cpu_isar_feature(aa32_ras, cpu)) {
1779             valid_mask |= SCR_TERR;
1780         }
1781     }
1782 
1783     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1784         valid_mask &= ~SCR_HCE;
1785 
1786         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1787          * supported if EL2 exists. The bit is UNK/SBZP when
1788          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1789          * when EL2 is unavailable.
1790          * On ARMv8, this bit is always available.
1791          */
1792         if (arm_feature(env, ARM_FEATURE_V7) &&
1793             !arm_feature(env, ARM_FEATURE_V8)) {
1794             valid_mask &= ~SCR_SMD;
1795         }
1796     }
1797 
1798     /* Clear all-context RES0 bits.  */
1799     value &= valid_mask;
1800     raw_write(env, ri, value);
1801 }
1802 
1803 static void scr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1804 {
1805     /*
1806      * scr_write will set the RES1 bits on an AArch64-only CPU.
1807      * The reset value will be 0x30 on an AArch64-only CPU and 0 otherwise.
1808      */
1809     scr_write(env, ri, 0);
1810 }
1811 
1812 static CPAccessResult access_aa64_tid2(CPUARMState *env,
1813                                        const ARMCPRegInfo *ri,
1814                                        bool isread)
1815 {
1816     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
1817         return CP_ACCESS_TRAP_EL2;
1818     }
1819 
1820     return CP_ACCESS_OK;
1821 }
1822 
1823 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1824 {
1825     ARMCPU *cpu = env_archcpu(env);
1826 
1827     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1828      * bank
1829      */
1830     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1831                                         ri->secure & ARM_CP_SECSTATE_S);
1832 
1833     return cpu->ccsidr[index];
1834 }
1835 
1836 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1837                          uint64_t value)
1838 {
1839     raw_write(env, ri, value & 0xf);
1840 }
1841 
1842 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1843 {
1844     CPUState *cs = env_cpu(env);
1845     bool el1 = arm_current_el(env) == 1;
1846     uint64_t hcr_el2 = el1 ? arm_hcr_el2_eff(env) : 0;
1847     uint64_t ret = 0;
1848 
1849     if (hcr_el2 & HCR_IMO) {
1850         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1851             ret |= CPSR_I;
1852         }
1853     } else {
1854         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1855             ret |= CPSR_I;
1856         }
1857     }
1858 
1859     if (hcr_el2 & HCR_FMO) {
1860         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1861             ret |= CPSR_F;
1862         }
1863     } else {
1864         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1865             ret |= CPSR_F;
1866         }
1867     }
1868 
1869     if (hcr_el2 & HCR_AMO) {
1870         if (cs->interrupt_request & CPU_INTERRUPT_VSERR) {
1871             ret |= CPSR_A;
1872         }
1873     }
1874 
1875     return ret;
1876 }
1877 
1878 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1879                                        bool isread)
1880 {
1881     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
1882         return CP_ACCESS_TRAP_EL2;
1883     }
1884 
1885     return CP_ACCESS_OK;
1886 }
1887 
1888 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1889                                        bool isread)
1890 {
1891     if (arm_feature(env, ARM_FEATURE_V8)) {
1892         return access_aa64_tid1(env, ri, isread);
1893     }
1894 
1895     return CP_ACCESS_OK;
1896 }
1897 
1898 static const ARMCPRegInfo v7_cp_reginfo[] = {
1899     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1900     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1901       .access = PL1_W, .type = ARM_CP_NOP },
1902     /* Performance monitors are implementation defined in v7,
1903      * but with an ARM recommended set of registers, which we
1904      * follow.
1905      *
1906      * Performance registers fall into three categories:
1907      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1908      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1909      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1910      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1911      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1912      */
1913     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1914       .access = PL0_RW, .type = ARM_CP_ALIAS,
1915       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1916       .writefn = pmcntenset_write,
1917       .accessfn = pmreg_access,
1918       .raw_writefn = raw_write },
1919     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1920       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1921       .access = PL0_RW, .accessfn = pmreg_access,
1922       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1923       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1924     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1925       .access = PL0_RW,
1926       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1927       .accessfn = pmreg_access,
1928       .writefn = pmcntenclr_write,
1929       .type = ARM_CP_ALIAS },
1930     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1931       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1932       .access = PL0_RW, .accessfn = pmreg_access,
1933       .type = ARM_CP_ALIAS,
1934       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1935       .writefn = pmcntenclr_write },
1936     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1937       .access = PL0_RW, .type = ARM_CP_IO,
1938       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
1939       .accessfn = pmreg_access,
1940       .writefn = pmovsr_write,
1941       .raw_writefn = raw_write },
1942     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1943       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1944       .access = PL0_RW, .accessfn = pmreg_access,
1945       .type = ARM_CP_ALIAS | ARM_CP_IO,
1946       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1947       .writefn = pmovsr_write,
1948       .raw_writefn = raw_write },
1949     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1950       .access = PL0_W, .accessfn = pmreg_access_swinc,
1951       .type = ARM_CP_NO_RAW | ARM_CP_IO,
1952       .writefn = pmswinc_write },
1953     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
1954       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
1955       .access = PL0_W, .accessfn = pmreg_access_swinc,
1956       .type = ARM_CP_NO_RAW | ARM_CP_IO,
1957       .writefn = pmswinc_write },
1958     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1959       .access = PL0_RW, .type = ARM_CP_ALIAS,
1960       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1961       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1962       .raw_writefn = raw_write},
1963     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1964       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1965       .access = PL0_RW, .accessfn = pmreg_access_selr,
1966       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1967       .writefn = pmselr_write, .raw_writefn = raw_write, },
1968     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1969       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
1970       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1971       .accessfn = pmreg_access_ccntr },
1972     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1973       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1974       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1975       .type = ARM_CP_IO,
1976       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
1977       .readfn = pmccntr_read, .writefn = pmccntr_write,
1978       .raw_readfn = raw_read, .raw_writefn = raw_write, },
1979     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
1980       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
1981       .access = PL0_RW, .accessfn = pmreg_access,
1982       .type = ARM_CP_ALIAS | ARM_CP_IO,
1983       .resetvalue = 0, },
1984     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1985       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1986       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
1987       .access = PL0_RW, .accessfn = pmreg_access,
1988       .type = ARM_CP_IO,
1989       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1990       .resetvalue = 0, },
1991     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1992       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1993       .accessfn = pmreg_access,
1994       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1995     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1996       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1997       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1998       .accessfn = pmreg_access,
1999       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2000     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2001       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2002       .accessfn = pmreg_access_xevcntr,
2003       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2004     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2005       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2006       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2007       .accessfn = pmreg_access_xevcntr,
2008       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2009     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2010       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2011       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2012       .resetvalue = 0,
2013       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2014     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2015       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2016       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2017       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2018       .resetvalue = 0,
2019       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2020     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2021       .access = PL1_RW, .accessfn = access_tpm,
2022       .type = ARM_CP_ALIAS | ARM_CP_IO,
2023       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2024       .resetvalue = 0,
2025       .writefn = pmintenset_write, .raw_writefn = raw_write },
2026     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2027       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2028       .access = PL1_RW, .accessfn = access_tpm,
2029       .type = ARM_CP_IO,
2030       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2031       .writefn = pmintenset_write, .raw_writefn = raw_write,
2032       .resetvalue = 0x0 },
2033     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2034       .access = PL1_RW, .accessfn = access_tpm,
2035       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2036       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2037       .writefn = pmintenclr_write, },
2038     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2039       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2040       .access = PL1_RW, .accessfn = access_tpm,
2041       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2042       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2043       .writefn = pmintenclr_write },
2044     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2045       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2046       .access = PL1_R,
2047       .accessfn = access_aa64_tid2,
2048       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2049     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2050       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2051       .access = PL1_RW,
2052       .accessfn = access_aa64_tid2,
2053       .writefn = csselr_write, .resetvalue = 0,
2054       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2055                              offsetof(CPUARMState, cp15.csselr_ns) } },
2056     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2057      * just RAZ for all cores:
2058      */
2059     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2060       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2061       .access = PL1_R, .type = ARM_CP_CONST,
2062       .accessfn = access_aa64_tid1,
2063       .resetvalue = 0 },
2064     /* Auxiliary fault status registers: these also are IMPDEF, and we
2065      * choose to RAZ/WI for all cores.
2066      */
2067     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2068       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2069       .access = PL1_RW, .accessfn = access_tvm_trvm,
2070       .type = ARM_CP_CONST, .resetvalue = 0 },
2071     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2072       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2073       .access = PL1_RW, .accessfn = access_tvm_trvm,
2074       .type = ARM_CP_CONST, .resetvalue = 0 },
2075     /* MAIR can just read-as-written because we don't implement caches
2076      * and so don't need to care about memory attributes.
2077      */
2078     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2079       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2080       .access = PL1_RW, .accessfn = access_tvm_trvm,
2081       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2082       .resetvalue = 0 },
2083     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2084       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2085       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2086       .resetvalue = 0 },
2087     /* For non-long-descriptor page tables these are PRRR and NMRR;
2088      * regardless they still act as reads-as-written for QEMU.
2089      */
2090      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2091       * allows them to assign the correct fieldoffset based on the endianness
2092       * handled in the field definitions.
2093       */
2094     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2095       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2096       .access = PL1_RW, .accessfn = access_tvm_trvm,
2097       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2098                              offsetof(CPUARMState, cp15.mair0_ns) },
2099       .resetfn = arm_cp_reset_ignore },
2100     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2101       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2102       .access = PL1_RW, .accessfn = access_tvm_trvm,
2103       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2104                              offsetof(CPUARMState, cp15.mair1_ns) },
2105       .resetfn = arm_cp_reset_ignore },
2106     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2107       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2108       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2109     /* 32 bit ITLB invalidates */
2110     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2111       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2112       .writefn = tlbiall_write },
2113     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2114       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2115       .writefn = tlbimva_write },
2116     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2117       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2118       .writefn = tlbiasid_write },
2119     /* 32 bit DTLB invalidates */
2120     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2121       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2122       .writefn = tlbiall_write },
2123     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2124       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2125       .writefn = tlbimva_write },
2126     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2127       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2128       .writefn = tlbiasid_write },
2129     /* 32 bit TLB invalidates */
2130     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2131       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2132       .writefn = tlbiall_write },
2133     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2134       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2135       .writefn = tlbimva_write },
2136     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2137       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2138       .writefn = tlbiasid_write },
2139     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2140       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2141       .writefn = tlbimvaa_write },
2142 };
2143 
2144 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2145     /* 32 bit TLB invalidates, Inner Shareable */
2146     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2147       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2148       .writefn = tlbiall_is_write },
2149     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2150       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2151       .writefn = tlbimva_is_write },
2152     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2153       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2154       .writefn = tlbiasid_is_write },
2155     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2156       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2157       .writefn = tlbimvaa_is_write },
2158 };
2159 
2160 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2161     /* PMOVSSET is not implemented in v7 before v7ve */
2162     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2163       .access = PL0_RW, .accessfn = pmreg_access,
2164       .type = ARM_CP_ALIAS | ARM_CP_IO,
2165       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2166       .writefn = pmovsset_write,
2167       .raw_writefn = raw_write },
2168     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2169       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2170       .access = PL0_RW, .accessfn = pmreg_access,
2171       .type = ARM_CP_ALIAS | ARM_CP_IO,
2172       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2173       .writefn = pmovsset_write,
2174       .raw_writefn = raw_write },
2175 };
2176 
2177 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2178                         uint64_t value)
2179 {
2180     value &= 1;
2181     env->teecr = value;
2182 }
2183 
2184 static CPAccessResult teecr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2185                                    bool isread)
2186 {
2187     /*
2188      * HSTR.TTEE only exists in v7A, not v8A, but v8A doesn't have T2EE
2189      * at all, so we don't need to check whether we're v8A.
2190      */
2191     if (arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
2192         (env->cp15.hstr_el2 & HSTR_TTEE)) {
2193         return CP_ACCESS_TRAP_EL2;
2194     }
2195     return CP_ACCESS_OK;
2196 }
2197 
2198 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2199                                     bool isread)
2200 {
2201     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2202         return CP_ACCESS_TRAP;
2203     }
2204     return teecr_access(env, ri, isread);
2205 }
2206 
2207 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2208     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2209       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2210       .resetvalue = 0,
2211       .writefn = teecr_write, .accessfn = teecr_access },
2212     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2213       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2214       .accessfn = teehbr_access, .resetvalue = 0 },
2215 };
2216 
2217 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2218     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2219       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2220       .access = PL0_RW,
2221       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2222     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2223       .access = PL0_RW,
2224       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2225                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2226       .resetfn = arm_cp_reset_ignore },
2227     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2228       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2229       .access = PL0_R|PL1_W,
2230       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2231       .resetvalue = 0},
2232     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2233       .access = PL0_R|PL1_W,
2234       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2235                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2236       .resetfn = arm_cp_reset_ignore },
2237     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2238       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2239       .access = PL1_RW,
2240       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2241     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2242       .access = PL1_RW,
2243       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2244                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2245       .resetvalue = 0 },
2246 };
2247 
2248 #ifndef CONFIG_USER_ONLY
2249 
2250 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2251                                        bool isread)
2252 {
2253     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2254      * Writable only at the highest implemented exception level.
2255      */
2256     int el = arm_current_el(env);
2257     uint64_t hcr;
2258     uint32_t cntkctl;
2259 
2260     switch (el) {
2261     case 0:
2262         hcr = arm_hcr_el2_eff(env);
2263         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2264             cntkctl = env->cp15.cnthctl_el2;
2265         } else {
2266             cntkctl = env->cp15.c14_cntkctl;
2267         }
2268         if (!extract32(cntkctl, 0, 2)) {
2269             return CP_ACCESS_TRAP;
2270         }
2271         break;
2272     case 1:
2273         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2274             arm_is_secure_below_el3(env)) {
2275             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2276             return CP_ACCESS_TRAP_UNCATEGORIZED;
2277         }
2278         break;
2279     case 2:
2280     case 3:
2281         break;
2282     }
2283 
2284     if (!isread && el < arm_highest_el(env)) {
2285         return CP_ACCESS_TRAP_UNCATEGORIZED;
2286     }
2287 
2288     return CP_ACCESS_OK;
2289 }
2290 
2291 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2292                                         bool isread)
2293 {
2294     unsigned int cur_el = arm_current_el(env);
2295     bool has_el2 = arm_is_el2_enabled(env);
2296     uint64_t hcr = arm_hcr_el2_eff(env);
2297 
2298     switch (cur_el) {
2299     case 0:
2300         /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2301         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2302             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2303                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2304         }
2305 
2306         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2307         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2308             return CP_ACCESS_TRAP;
2309         }
2310 
2311         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2312         if (hcr & HCR_E2H) {
2313             if (timeridx == GTIMER_PHYS &&
2314                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2315                 return CP_ACCESS_TRAP_EL2;
2316             }
2317         } else {
2318             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2319             if (has_el2 && timeridx == GTIMER_PHYS &&
2320                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2321                 return CP_ACCESS_TRAP_EL2;
2322             }
2323         }
2324         break;
2325 
2326     case 1:
2327         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2328         if (has_el2 && timeridx == GTIMER_PHYS &&
2329             (hcr & HCR_E2H
2330              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2331              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2332             return CP_ACCESS_TRAP_EL2;
2333         }
2334         break;
2335     }
2336     return CP_ACCESS_OK;
2337 }
2338 
2339 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2340                                       bool isread)
2341 {
2342     unsigned int cur_el = arm_current_el(env);
2343     bool has_el2 = arm_is_el2_enabled(env);
2344     uint64_t hcr = arm_hcr_el2_eff(env);
2345 
2346     switch (cur_el) {
2347     case 0:
2348         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2349             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2350             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2351                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2352         }
2353 
2354         /*
2355          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2356          * EL0 if EL0[PV]TEN is zero.
2357          */
2358         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2359             return CP_ACCESS_TRAP;
2360         }
2361         /* fall through */
2362 
2363     case 1:
2364         if (has_el2 && timeridx == GTIMER_PHYS) {
2365             if (hcr & HCR_E2H) {
2366                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2367                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2368                     return CP_ACCESS_TRAP_EL2;
2369                 }
2370             } else {
2371                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2372                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2373                     return CP_ACCESS_TRAP_EL2;
2374                 }
2375             }
2376         }
2377         break;
2378     }
2379     return CP_ACCESS_OK;
2380 }
2381 
2382 static CPAccessResult gt_pct_access(CPUARMState *env,
2383                                     const ARMCPRegInfo *ri,
2384                                     bool isread)
2385 {
2386     return gt_counter_access(env, GTIMER_PHYS, isread);
2387 }
2388 
2389 static CPAccessResult gt_vct_access(CPUARMState *env,
2390                                     const ARMCPRegInfo *ri,
2391                                     bool isread)
2392 {
2393     return gt_counter_access(env, GTIMER_VIRT, isread);
2394 }
2395 
2396 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2397                                        bool isread)
2398 {
2399     return gt_timer_access(env, GTIMER_PHYS, isread);
2400 }
2401 
2402 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2403                                        bool isread)
2404 {
2405     return gt_timer_access(env, GTIMER_VIRT, isread);
2406 }
2407 
2408 static CPAccessResult gt_stimer_access(CPUARMState *env,
2409                                        const ARMCPRegInfo *ri,
2410                                        bool isread)
2411 {
2412     /* The AArch64 register view of the secure physical timer is
2413      * always accessible from EL3, and configurably accessible from
2414      * Secure EL1.
2415      */
2416     switch (arm_current_el(env)) {
2417     case 1:
2418         if (!arm_is_secure(env)) {
2419             return CP_ACCESS_TRAP;
2420         }
2421         if (!(env->cp15.scr_el3 & SCR_ST)) {
2422             return CP_ACCESS_TRAP_EL3;
2423         }
2424         return CP_ACCESS_OK;
2425     case 0:
2426     case 2:
2427         return CP_ACCESS_TRAP;
2428     case 3:
2429         return CP_ACCESS_OK;
2430     default:
2431         g_assert_not_reached();
2432     }
2433 }
2434 
2435 static uint64_t gt_get_countervalue(CPUARMState *env)
2436 {
2437     ARMCPU *cpu = env_archcpu(env);
2438 
2439     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2440 }
2441 
2442 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2443 {
2444     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2445 
2446     if (gt->ctl & 1) {
2447         /* Timer enabled: calculate and set current ISTATUS, irq, and
2448          * reset timer to when ISTATUS next has to change
2449          */
2450         uint64_t offset = timeridx == GTIMER_VIRT ?
2451                                       cpu->env.cp15.cntvoff_el2 : 0;
2452         uint64_t count = gt_get_countervalue(&cpu->env);
2453         /* Note that this must be unsigned 64 bit arithmetic: */
2454         int istatus = count - offset >= gt->cval;
2455         uint64_t nexttick;
2456         int irqstate;
2457 
2458         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2459 
2460         irqstate = (istatus && !(gt->ctl & 2));
2461         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2462 
2463         if (istatus) {
2464             /* Next transition is when count rolls back over to zero */
2465             nexttick = UINT64_MAX;
2466         } else {
2467             /* Next transition is when we hit cval */
2468             nexttick = gt->cval + offset;
2469         }
2470         /* Note that the desired next expiry time might be beyond the
2471          * signed-64-bit range of a QEMUTimer -- in this case we just
2472          * set the timer for as far in the future as possible. When the
2473          * timer expires we will reset the timer for any remaining period.
2474          */
2475         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2476             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2477         } else {
2478             timer_mod(cpu->gt_timer[timeridx], nexttick);
2479         }
2480         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2481     } else {
2482         /* Timer disabled: ISTATUS and timer output always clear */
2483         gt->ctl &= ~4;
2484         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2485         timer_del(cpu->gt_timer[timeridx]);
2486         trace_arm_gt_recalc_disabled(timeridx);
2487     }
2488 }
2489 
2490 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2491                            int timeridx)
2492 {
2493     ARMCPU *cpu = env_archcpu(env);
2494 
2495     timer_del(cpu->gt_timer[timeridx]);
2496 }
2497 
2498 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2499 {
2500     return gt_get_countervalue(env);
2501 }
2502 
2503 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2504 {
2505     uint64_t hcr;
2506 
2507     switch (arm_current_el(env)) {
2508     case 2:
2509         hcr = arm_hcr_el2_eff(env);
2510         if (hcr & HCR_E2H) {
2511             return 0;
2512         }
2513         break;
2514     case 0:
2515         hcr = arm_hcr_el2_eff(env);
2516         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2517             return 0;
2518         }
2519         break;
2520     }
2521 
2522     return env->cp15.cntvoff_el2;
2523 }
2524 
2525 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2526 {
2527     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2528 }
2529 
2530 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2531                           int timeridx,
2532                           uint64_t value)
2533 {
2534     trace_arm_gt_cval_write(timeridx, value);
2535     env->cp15.c14_timer[timeridx].cval = value;
2536     gt_recalc_timer(env_archcpu(env), timeridx);
2537 }
2538 
2539 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2540                              int timeridx)
2541 {
2542     uint64_t offset = 0;
2543 
2544     switch (timeridx) {
2545     case GTIMER_VIRT:
2546     case GTIMER_HYPVIRT:
2547         offset = gt_virt_cnt_offset(env);
2548         break;
2549     }
2550 
2551     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2552                       (gt_get_countervalue(env) - offset));
2553 }
2554 
2555 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2556                           int timeridx,
2557                           uint64_t value)
2558 {
2559     uint64_t offset = 0;
2560 
2561     switch (timeridx) {
2562     case GTIMER_VIRT:
2563     case GTIMER_HYPVIRT:
2564         offset = gt_virt_cnt_offset(env);
2565         break;
2566     }
2567 
2568     trace_arm_gt_tval_write(timeridx, value);
2569     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2570                                          sextract64(value, 0, 32);
2571     gt_recalc_timer(env_archcpu(env), timeridx);
2572 }
2573 
2574 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2575                          int timeridx,
2576                          uint64_t value)
2577 {
2578     ARMCPU *cpu = env_archcpu(env);
2579     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2580 
2581     trace_arm_gt_ctl_write(timeridx, value);
2582     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2583     if ((oldval ^ value) & 1) {
2584         /* Enable toggled */
2585         gt_recalc_timer(cpu, timeridx);
2586     } else if ((oldval ^ value) & 2) {
2587         /* IMASK toggled: don't need to recalculate,
2588          * just set the interrupt line based on ISTATUS
2589          */
2590         int irqstate = (oldval & 4) && !(value & 2);
2591 
2592         trace_arm_gt_imask_toggle(timeridx, irqstate);
2593         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2594     }
2595 }
2596 
2597 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2598 {
2599     gt_timer_reset(env, ri, GTIMER_PHYS);
2600 }
2601 
2602 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2603                                uint64_t value)
2604 {
2605     gt_cval_write(env, ri, GTIMER_PHYS, value);
2606 }
2607 
2608 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2609 {
2610     return gt_tval_read(env, ri, GTIMER_PHYS);
2611 }
2612 
2613 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2614                                uint64_t value)
2615 {
2616     gt_tval_write(env, ri, GTIMER_PHYS, value);
2617 }
2618 
2619 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2620                               uint64_t value)
2621 {
2622     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2623 }
2624 
2625 static int gt_phys_redir_timeridx(CPUARMState *env)
2626 {
2627     switch (arm_mmu_idx(env)) {
2628     case ARMMMUIdx_E20_0:
2629     case ARMMMUIdx_E20_2:
2630     case ARMMMUIdx_E20_2_PAN:
2631     case ARMMMUIdx_SE20_0:
2632     case ARMMMUIdx_SE20_2:
2633     case ARMMMUIdx_SE20_2_PAN:
2634         return GTIMER_HYP;
2635     default:
2636         return GTIMER_PHYS;
2637     }
2638 }
2639 
2640 static int gt_virt_redir_timeridx(CPUARMState *env)
2641 {
2642     switch (arm_mmu_idx(env)) {
2643     case ARMMMUIdx_E20_0:
2644     case ARMMMUIdx_E20_2:
2645     case ARMMMUIdx_E20_2_PAN:
2646     case ARMMMUIdx_SE20_0:
2647     case ARMMMUIdx_SE20_2:
2648     case ARMMMUIdx_SE20_2_PAN:
2649         return GTIMER_HYPVIRT;
2650     default:
2651         return GTIMER_VIRT;
2652     }
2653 }
2654 
2655 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2656                                         const ARMCPRegInfo *ri)
2657 {
2658     int timeridx = gt_phys_redir_timeridx(env);
2659     return env->cp15.c14_timer[timeridx].cval;
2660 }
2661 
2662 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2663                                      uint64_t value)
2664 {
2665     int timeridx = gt_phys_redir_timeridx(env);
2666     gt_cval_write(env, ri, timeridx, value);
2667 }
2668 
2669 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2670                                         const ARMCPRegInfo *ri)
2671 {
2672     int timeridx = gt_phys_redir_timeridx(env);
2673     return gt_tval_read(env, ri, timeridx);
2674 }
2675 
2676 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2677                                      uint64_t value)
2678 {
2679     int timeridx = gt_phys_redir_timeridx(env);
2680     gt_tval_write(env, ri, timeridx, value);
2681 }
2682 
2683 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2684                                        const ARMCPRegInfo *ri)
2685 {
2686     int timeridx = gt_phys_redir_timeridx(env);
2687     return env->cp15.c14_timer[timeridx].ctl;
2688 }
2689 
2690 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2691                                     uint64_t value)
2692 {
2693     int timeridx = gt_phys_redir_timeridx(env);
2694     gt_ctl_write(env, ri, timeridx, value);
2695 }
2696 
2697 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2698 {
2699     gt_timer_reset(env, ri, GTIMER_VIRT);
2700 }
2701 
2702 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2703                                uint64_t value)
2704 {
2705     gt_cval_write(env, ri, GTIMER_VIRT, value);
2706 }
2707 
2708 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2709 {
2710     return gt_tval_read(env, ri, GTIMER_VIRT);
2711 }
2712 
2713 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2714                                uint64_t value)
2715 {
2716     gt_tval_write(env, ri, GTIMER_VIRT, value);
2717 }
2718 
2719 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2720                               uint64_t value)
2721 {
2722     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2723 }
2724 
2725 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2726                               uint64_t value)
2727 {
2728     ARMCPU *cpu = env_archcpu(env);
2729 
2730     trace_arm_gt_cntvoff_write(value);
2731     raw_write(env, ri, value);
2732     gt_recalc_timer(cpu, GTIMER_VIRT);
2733 }
2734 
2735 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
2736                                         const ARMCPRegInfo *ri)
2737 {
2738     int timeridx = gt_virt_redir_timeridx(env);
2739     return env->cp15.c14_timer[timeridx].cval;
2740 }
2741 
2742 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2743                                      uint64_t value)
2744 {
2745     int timeridx = gt_virt_redir_timeridx(env);
2746     gt_cval_write(env, ri, timeridx, value);
2747 }
2748 
2749 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
2750                                         const ARMCPRegInfo *ri)
2751 {
2752     int timeridx = gt_virt_redir_timeridx(env);
2753     return gt_tval_read(env, ri, timeridx);
2754 }
2755 
2756 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2757                                      uint64_t value)
2758 {
2759     int timeridx = gt_virt_redir_timeridx(env);
2760     gt_tval_write(env, ri, timeridx, value);
2761 }
2762 
2763 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
2764                                        const ARMCPRegInfo *ri)
2765 {
2766     int timeridx = gt_virt_redir_timeridx(env);
2767     return env->cp15.c14_timer[timeridx].ctl;
2768 }
2769 
2770 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2771                                     uint64_t value)
2772 {
2773     int timeridx = gt_virt_redir_timeridx(env);
2774     gt_ctl_write(env, ri, timeridx, value);
2775 }
2776 
2777 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2778 {
2779     gt_timer_reset(env, ri, GTIMER_HYP);
2780 }
2781 
2782 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2783                               uint64_t value)
2784 {
2785     gt_cval_write(env, ri, GTIMER_HYP, value);
2786 }
2787 
2788 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2789 {
2790     return gt_tval_read(env, ri, GTIMER_HYP);
2791 }
2792 
2793 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2794                               uint64_t value)
2795 {
2796     gt_tval_write(env, ri, GTIMER_HYP, value);
2797 }
2798 
2799 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2800                               uint64_t value)
2801 {
2802     gt_ctl_write(env, ri, GTIMER_HYP, value);
2803 }
2804 
2805 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2806 {
2807     gt_timer_reset(env, ri, GTIMER_SEC);
2808 }
2809 
2810 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2811                               uint64_t value)
2812 {
2813     gt_cval_write(env, ri, GTIMER_SEC, value);
2814 }
2815 
2816 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2817 {
2818     return gt_tval_read(env, ri, GTIMER_SEC);
2819 }
2820 
2821 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2822                               uint64_t value)
2823 {
2824     gt_tval_write(env, ri, GTIMER_SEC, value);
2825 }
2826 
2827 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2828                               uint64_t value)
2829 {
2830     gt_ctl_write(env, ri, GTIMER_SEC, value);
2831 }
2832 
2833 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2834 {
2835     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
2836 }
2837 
2838 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2839                              uint64_t value)
2840 {
2841     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
2842 }
2843 
2844 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2845 {
2846     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
2847 }
2848 
2849 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2850                              uint64_t value)
2851 {
2852     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
2853 }
2854 
2855 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2856                             uint64_t value)
2857 {
2858     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
2859 }
2860 
2861 void arm_gt_ptimer_cb(void *opaque)
2862 {
2863     ARMCPU *cpu = opaque;
2864 
2865     gt_recalc_timer(cpu, GTIMER_PHYS);
2866 }
2867 
2868 void arm_gt_vtimer_cb(void *opaque)
2869 {
2870     ARMCPU *cpu = opaque;
2871 
2872     gt_recalc_timer(cpu, GTIMER_VIRT);
2873 }
2874 
2875 void arm_gt_htimer_cb(void *opaque)
2876 {
2877     ARMCPU *cpu = opaque;
2878 
2879     gt_recalc_timer(cpu, GTIMER_HYP);
2880 }
2881 
2882 void arm_gt_stimer_cb(void *opaque)
2883 {
2884     ARMCPU *cpu = opaque;
2885 
2886     gt_recalc_timer(cpu, GTIMER_SEC);
2887 }
2888 
2889 void arm_gt_hvtimer_cb(void *opaque)
2890 {
2891     ARMCPU *cpu = opaque;
2892 
2893     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
2894 }
2895 
2896 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
2897 {
2898     ARMCPU *cpu = env_archcpu(env);
2899 
2900     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
2901 }
2902 
2903 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2904     /* Note that CNTFRQ is purely reads-as-written for the benefit
2905      * of software; writing it doesn't actually change the timer frequency.
2906      * Our reset value matches the fixed frequency we implement the timer at.
2907      */
2908     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2909       .type = ARM_CP_ALIAS,
2910       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2911       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2912     },
2913     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2914       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2915       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2916       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2917       .resetfn = arm_gt_cntfrq_reset,
2918     },
2919     /* overall control: mostly access permissions */
2920     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2921       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2922       .access = PL1_RW,
2923       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2924       .resetvalue = 0,
2925     },
2926     /* per-timer control */
2927     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2928       .secure = ARM_CP_SECSTATE_NS,
2929       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2930       .accessfn = gt_ptimer_access,
2931       .fieldoffset = offsetoflow32(CPUARMState,
2932                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2933       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
2934       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
2935     },
2936     { .name = "CNTP_CTL_S",
2937       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2938       .secure = ARM_CP_SECSTATE_S,
2939       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2940       .accessfn = gt_ptimer_access,
2941       .fieldoffset = offsetoflow32(CPUARMState,
2942                                    cp15.c14_timer[GTIMER_SEC].ctl),
2943       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2944     },
2945     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2946       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2947       .type = ARM_CP_IO, .access = PL0_RW,
2948       .accessfn = gt_ptimer_access,
2949       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2950       .resetvalue = 0,
2951       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
2952       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
2953     },
2954     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2955       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2956       .accessfn = gt_vtimer_access,
2957       .fieldoffset = offsetoflow32(CPUARMState,
2958                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2959       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
2960       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
2961     },
2962     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2963       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2964       .type = ARM_CP_IO, .access = PL0_RW,
2965       .accessfn = gt_vtimer_access,
2966       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2967       .resetvalue = 0,
2968       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
2969       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
2970     },
2971     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2972     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2973       .secure = ARM_CP_SECSTATE_NS,
2974       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2975       .accessfn = gt_ptimer_access,
2976       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
2977     },
2978     { .name = "CNTP_TVAL_S",
2979       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2980       .secure = ARM_CP_SECSTATE_S,
2981       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2982       .accessfn = gt_ptimer_access,
2983       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2984     },
2985     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2986       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2987       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2988       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2989       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
2990     },
2991     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2992       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2993       .accessfn = gt_vtimer_access,
2994       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
2995     },
2996     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2997       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2998       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2999       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
3000       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3001     },
3002     /* The counter itself */
3003     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
3004       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3005       .accessfn = gt_pct_access,
3006       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
3007     },
3008     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
3009       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
3010       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3011       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
3012     },
3013     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3014       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3015       .accessfn = gt_vct_access,
3016       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3017     },
3018     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3019       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3020       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3021       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3022     },
3023     /* Comparison value, indicating when the timer goes off */
3024     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3025       .secure = ARM_CP_SECSTATE_NS,
3026       .access = PL0_RW,
3027       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3028       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3029       .accessfn = gt_ptimer_access,
3030       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3031       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3032     },
3033     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3034       .secure = ARM_CP_SECSTATE_S,
3035       .access = PL0_RW,
3036       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3037       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3038       .accessfn = gt_ptimer_access,
3039       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3040     },
3041     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3042       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3043       .access = PL0_RW,
3044       .type = ARM_CP_IO,
3045       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3046       .resetvalue = 0, .accessfn = gt_ptimer_access,
3047       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3048       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3049     },
3050     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3051       .access = PL0_RW,
3052       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3053       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3054       .accessfn = gt_vtimer_access,
3055       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3056       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3057     },
3058     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3059       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3060       .access = PL0_RW,
3061       .type = ARM_CP_IO,
3062       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3063       .resetvalue = 0, .accessfn = gt_vtimer_access,
3064       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3065       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3066     },
3067     /* Secure timer -- this is actually restricted to only EL3
3068      * and configurably Secure-EL1 via the accessfn.
3069      */
3070     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3071       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3072       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3073       .accessfn = gt_stimer_access,
3074       .readfn = gt_sec_tval_read,
3075       .writefn = gt_sec_tval_write,
3076       .resetfn = gt_sec_timer_reset,
3077     },
3078     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3079       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3080       .type = ARM_CP_IO, .access = PL1_RW,
3081       .accessfn = gt_stimer_access,
3082       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3083       .resetvalue = 0,
3084       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3085     },
3086     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3087       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3088       .type = ARM_CP_IO, .access = PL1_RW,
3089       .accessfn = gt_stimer_access,
3090       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3091       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3092     },
3093 };
3094 
3095 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3096                                  bool isread)
3097 {
3098     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3099         return CP_ACCESS_TRAP;
3100     }
3101     return CP_ACCESS_OK;
3102 }
3103 
3104 #else
3105 
3106 /* In user-mode most of the generic timer registers are inaccessible
3107  * however modern kernels (4.12+) allow access to cntvct_el0
3108  */
3109 
3110 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3111 {
3112     ARMCPU *cpu = env_archcpu(env);
3113 
3114     /* Currently we have no support for QEMUTimer in linux-user so we
3115      * can't call gt_get_countervalue(env), instead we directly
3116      * call the lower level functions.
3117      */
3118     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3119 }
3120 
3121 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3122     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3123       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3124       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3125       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3126       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3127     },
3128     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3129       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3130       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3131       .readfn = gt_virt_cnt_read,
3132     },
3133 };
3134 
3135 #endif
3136 
3137 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3138 {
3139     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3140         raw_write(env, ri, value);
3141     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3142         raw_write(env, ri, value & 0xfffff6ff);
3143     } else {
3144         raw_write(env, ri, value & 0xfffff1ff);
3145     }
3146 }
3147 
3148 #ifndef CONFIG_USER_ONLY
3149 /* get_phys_addr() isn't present for user-mode-only targets */
3150 
3151 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3152                                  bool isread)
3153 {
3154     if (ri->opc2 & 4) {
3155         /* The ATS12NSO* operations must trap to EL3 or EL2 if executed in
3156          * Secure EL1 (which can only happen if EL3 is AArch64).
3157          * They are simply UNDEF if executed from NS EL1.
3158          * They function normally from EL2 or EL3.
3159          */
3160         if (arm_current_el(env) == 1) {
3161             if (arm_is_secure_below_el3(env)) {
3162                 if (env->cp15.scr_el3 & SCR_EEL2) {
3163                     return CP_ACCESS_TRAP_UNCATEGORIZED_EL2;
3164                 }
3165                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3166             }
3167             return CP_ACCESS_TRAP_UNCATEGORIZED;
3168         }
3169     }
3170     return CP_ACCESS_OK;
3171 }
3172 
3173 #ifdef CONFIG_TCG
3174 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3175                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3176 {
3177     hwaddr phys_addr;
3178     target_ulong page_size;
3179     int prot;
3180     bool ret;
3181     uint64_t par64;
3182     bool format64 = false;
3183     MemTxAttrs attrs = {};
3184     ARMMMUFaultInfo fi = {};
3185     ARMCacheAttrs cacheattrs = {};
3186 
3187     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3188                         &prot, &page_size, &fi, &cacheattrs);
3189 
3190     /*
3191      * ATS operations only do S1 or S1+S2 translations, so we never
3192      * have to deal with the ARMCacheAttrs format for S2 only.
3193      */
3194     assert(!cacheattrs.is_s2_format);
3195 
3196     if (ret) {
3197         /*
3198          * Some kinds of translation fault must cause exceptions rather
3199          * than being reported in the PAR.
3200          */
3201         int current_el = arm_current_el(env);
3202         int target_el;
3203         uint32_t syn, fsr, fsc;
3204         bool take_exc = false;
3205 
3206         if (fi.s1ptw && current_el == 1
3207             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3208             /*
3209              * Synchronous stage 2 fault on an access made as part of the
3210              * translation table walk for AT S1E0* or AT S1E1* insn
3211              * executed from NS EL1. If this is a synchronous external abort
3212              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3213              * to EL3. Otherwise the fault is taken as an exception to EL2,
3214              * and HPFAR_EL2 holds the faulting IPA.
3215              */
3216             if (fi.type == ARMFault_SyncExternalOnWalk &&
3217                 (env->cp15.scr_el3 & SCR_EA)) {
3218                 target_el = 3;
3219             } else {
3220                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3221                 if (arm_is_secure_below_el3(env) && fi.s1ns) {
3222                     env->cp15.hpfar_el2 |= HPFAR_NS;
3223                 }
3224                 target_el = 2;
3225             }
3226             take_exc = true;
3227         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3228             /*
3229              * Synchronous external aborts during a translation table walk
3230              * are taken as Data Abort exceptions.
3231              */
3232             if (fi.stage2) {
3233                 if (current_el == 3) {
3234                     target_el = 3;
3235                 } else {
3236                     target_el = 2;
3237                 }
3238             } else {
3239                 target_el = exception_target_el(env);
3240             }
3241             take_exc = true;
3242         }
3243 
3244         if (take_exc) {
3245             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3246             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3247                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3248                 fsr = arm_fi_to_lfsc(&fi);
3249                 fsc = extract32(fsr, 0, 6);
3250             } else {
3251                 fsr = arm_fi_to_sfsc(&fi);
3252                 fsc = 0x3f;
3253             }
3254             /*
3255              * Report exception with ESR indicating a fault due to a
3256              * translation table walk for a cache maintenance instruction.
3257              */
3258             syn = syn_data_abort_no_iss(current_el == target_el, 0,
3259                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3260             env->exception.vaddress = value;
3261             env->exception.fsr = fsr;
3262             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3263         }
3264     }
3265 
3266     if (is_a64(env)) {
3267         format64 = true;
3268     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3269         /*
3270          * ATS1Cxx:
3271          * * TTBCR.EAE determines whether the result is returned using the
3272          *   32-bit or the 64-bit PAR format
3273          * * Instructions executed in Hyp mode always use the 64bit format
3274          *
3275          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3276          * * The Non-secure TTBCR.EAE bit is set to 1
3277          * * The implementation includes EL2, and the value of HCR.VM is 1
3278          *
3279          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3280          *
3281          * ATS1Hx always uses the 64bit format.
3282          */
3283         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3284 
3285         if (arm_feature(env, ARM_FEATURE_EL2)) {
3286             if (mmu_idx == ARMMMUIdx_E10_0 ||
3287                 mmu_idx == ARMMMUIdx_E10_1 ||
3288                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3289                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3290             } else {
3291                 format64 |= arm_current_el(env) == 2;
3292             }
3293         }
3294     }
3295 
3296     if (format64) {
3297         /* Create a 64-bit PAR */
3298         par64 = (1 << 11); /* LPAE bit always set */
3299         if (!ret) {
3300             par64 |= phys_addr & ~0xfffULL;
3301             if (!attrs.secure) {
3302                 par64 |= (1 << 9); /* NS */
3303             }
3304             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3305             par64 |= cacheattrs.shareability << 7; /* SH */
3306         } else {
3307             uint32_t fsr = arm_fi_to_lfsc(&fi);
3308 
3309             par64 |= 1; /* F */
3310             par64 |= (fsr & 0x3f) << 1; /* FS */
3311             if (fi.stage2) {
3312                 par64 |= (1 << 9); /* S */
3313             }
3314             if (fi.s1ptw) {
3315                 par64 |= (1 << 8); /* PTW */
3316             }
3317         }
3318     } else {
3319         /* fsr is a DFSR/IFSR value for the short descriptor
3320          * translation table format (with WnR always clear).
3321          * Convert it to a 32-bit PAR.
3322          */
3323         if (!ret) {
3324             /* We do not set any attribute bits in the PAR */
3325             if (page_size == (1 << 24)
3326                 && arm_feature(env, ARM_FEATURE_V7)) {
3327                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3328             } else {
3329                 par64 = phys_addr & 0xfffff000;
3330             }
3331             if (!attrs.secure) {
3332                 par64 |= (1 << 9); /* NS */
3333             }
3334         } else {
3335             uint32_t fsr = arm_fi_to_sfsc(&fi);
3336 
3337             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3338                     ((fsr & 0xf) << 1) | 1;
3339         }
3340     }
3341     return par64;
3342 }
3343 #endif /* CONFIG_TCG */
3344 
3345 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3346 {
3347 #ifdef CONFIG_TCG
3348     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3349     uint64_t par64;
3350     ARMMMUIdx mmu_idx;
3351     int el = arm_current_el(env);
3352     bool secure = arm_is_secure_below_el3(env);
3353 
3354     switch (ri->opc2 & 6) {
3355     case 0:
3356         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3357         switch (el) {
3358         case 3:
3359             mmu_idx = ARMMMUIdx_SE3;
3360             break;
3361         case 2:
3362             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3363             /* fall through */
3364         case 1:
3365             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3366                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3367                            : ARMMMUIdx_Stage1_E1_PAN);
3368             } else {
3369                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3370             }
3371             break;
3372         default:
3373             g_assert_not_reached();
3374         }
3375         break;
3376     case 2:
3377         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3378         switch (el) {
3379         case 3:
3380             mmu_idx = ARMMMUIdx_SE10_0;
3381             break;
3382         case 2:
3383             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3384             mmu_idx = ARMMMUIdx_Stage1_E0;
3385             break;
3386         case 1:
3387             mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3388             break;
3389         default:
3390             g_assert_not_reached();
3391         }
3392         break;
3393     case 4:
3394         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3395         mmu_idx = ARMMMUIdx_E10_1;
3396         break;
3397     case 6:
3398         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3399         mmu_idx = ARMMMUIdx_E10_0;
3400         break;
3401     default:
3402         g_assert_not_reached();
3403     }
3404 
3405     par64 = do_ats_write(env, value, access_type, mmu_idx);
3406 
3407     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3408 #else
3409     /* Handled by hardware accelerator. */
3410     g_assert_not_reached();
3411 #endif /* CONFIG_TCG */
3412 }
3413 
3414 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3415                         uint64_t value)
3416 {
3417 #ifdef CONFIG_TCG
3418     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3419     uint64_t par64;
3420 
3421     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3422 
3423     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3424 #else
3425     /* Handled by hardware accelerator. */
3426     g_assert_not_reached();
3427 #endif /* CONFIG_TCG */
3428 }
3429 
3430 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3431                                      bool isread)
3432 {
3433     if (arm_current_el(env) == 3 &&
3434         !(env->cp15.scr_el3 & (SCR_NS | SCR_EEL2))) {
3435         return CP_ACCESS_TRAP;
3436     }
3437     return CP_ACCESS_OK;
3438 }
3439 
3440 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3441                         uint64_t value)
3442 {
3443 #ifdef CONFIG_TCG
3444     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3445     ARMMMUIdx mmu_idx;
3446     int secure = arm_is_secure_below_el3(env);
3447 
3448     switch (ri->opc2 & 6) {
3449     case 0:
3450         switch (ri->opc1) {
3451         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3452             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3453                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3454                            : ARMMMUIdx_Stage1_E1_PAN);
3455             } else {
3456                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3457             }
3458             break;
3459         case 4: /* AT S1E2R, AT S1E2W */
3460             mmu_idx = secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2;
3461             break;
3462         case 6: /* AT S1E3R, AT S1E3W */
3463             mmu_idx = ARMMMUIdx_SE3;
3464             break;
3465         default:
3466             g_assert_not_reached();
3467         }
3468         break;
3469     case 2: /* AT S1E0R, AT S1E0W */
3470         mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3471         break;
3472     case 4: /* AT S12E1R, AT S12E1W */
3473         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3474         break;
3475     case 6: /* AT S12E0R, AT S12E0W */
3476         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3477         break;
3478     default:
3479         g_assert_not_reached();
3480     }
3481 
3482     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3483 #else
3484     /* Handled by hardware accelerator. */
3485     g_assert_not_reached();
3486 #endif /* CONFIG_TCG */
3487 }
3488 #endif
3489 
3490 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3491     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3492       .access = PL1_RW, .resetvalue = 0,
3493       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3494                              offsetoflow32(CPUARMState, cp15.par_ns) },
3495       .writefn = par_write },
3496 #ifndef CONFIG_USER_ONLY
3497     /* This underdecoding is safe because the reginfo is NO_RAW. */
3498     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3499       .access = PL1_W, .accessfn = ats_access,
3500       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3501 #endif
3502 };
3503 
3504 /* Return basic MPU access permission bits.  */
3505 static uint32_t simple_mpu_ap_bits(uint32_t val)
3506 {
3507     uint32_t ret;
3508     uint32_t mask;
3509     int i;
3510     ret = 0;
3511     mask = 3;
3512     for (i = 0; i < 16; i += 2) {
3513         ret |= (val >> i) & mask;
3514         mask <<= 2;
3515     }
3516     return ret;
3517 }
3518 
3519 /* Pad basic MPU access permission bits to extended format.  */
3520 static uint32_t extended_mpu_ap_bits(uint32_t val)
3521 {
3522     uint32_t ret;
3523     uint32_t mask;
3524     int i;
3525     ret = 0;
3526     mask = 3;
3527     for (i = 0; i < 16; i += 2) {
3528         ret |= (val & mask) << i;
3529         mask <<= 2;
3530     }
3531     return ret;
3532 }
3533 
3534 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3535                                  uint64_t value)
3536 {
3537     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3538 }
3539 
3540 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3541 {
3542     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3543 }
3544 
3545 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3546                                  uint64_t value)
3547 {
3548     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3549 }
3550 
3551 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3552 {
3553     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3554 }
3555 
3556 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3557 {
3558     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3559 
3560     if (!u32p) {
3561         return 0;
3562     }
3563 
3564     u32p += env->pmsav7.rnr[M_REG_NS];
3565     return *u32p;
3566 }
3567 
3568 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3569                          uint64_t value)
3570 {
3571     ARMCPU *cpu = env_archcpu(env);
3572     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3573 
3574     if (!u32p) {
3575         return;
3576     }
3577 
3578     u32p += env->pmsav7.rnr[M_REG_NS];
3579     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3580     *u32p = value;
3581 }
3582 
3583 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3584                               uint64_t value)
3585 {
3586     ARMCPU *cpu = env_archcpu(env);
3587     uint32_t nrgs = cpu->pmsav7_dregion;
3588 
3589     if (value >= nrgs) {
3590         qemu_log_mask(LOG_GUEST_ERROR,
3591                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3592                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3593         return;
3594     }
3595 
3596     raw_write(env, ri, value);
3597 }
3598 
3599 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3600     /* Reset for all these registers is handled in arm_cpu_reset(),
3601      * because the PMSAv7 is also used by M-profile CPUs, which do
3602      * not register cpregs but still need the state to be reset.
3603      */
3604     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3605       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3606       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3607       .readfn = pmsav7_read, .writefn = pmsav7_write,
3608       .resetfn = arm_cp_reset_ignore },
3609     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3610       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3611       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3612       .readfn = pmsav7_read, .writefn = pmsav7_write,
3613       .resetfn = arm_cp_reset_ignore },
3614     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3615       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3616       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3617       .readfn = pmsav7_read, .writefn = pmsav7_write,
3618       .resetfn = arm_cp_reset_ignore },
3619     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3620       .access = PL1_RW,
3621       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3622       .writefn = pmsav7_rgnr_write,
3623       .resetfn = arm_cp_reset_ignore },
3624 };
3625 
3626 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3627     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3628       .access = PL1_RW, .type = ARM_CP_ALIAS,
3629       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3630       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3631     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3632       .access = PL1_RW, .type = ARM_CP_ALIAS,
3633       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3634       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3635     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3636       .access = PL1_RW,
3637       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3638       .resetvalue = 0, },
3639     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3640       .access = PL1_RW,
3641       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3642       .resetvalue = 0, },
3643     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3644       .access = PL1_RW,
3645       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3646     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3647       .access = PL1_RW,
3648       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3649     /* Protection region base and size registers */
3650     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3651       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3652       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3653     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3654       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3655       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3656     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3657       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3658       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3659     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3660       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3661       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3662     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3663       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3664       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3665     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3666       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3667       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3668     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3669       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3670       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3671     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3672       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3673       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3674 };
3675 
3676 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3677                                  uint64_t value)
3678 {
3679     TCR *tcr = raw_ptr(env, ri);
3680     int maskshift = extract32(value, 0, 3);
3681 
3682     if (!arm_feature(env, ARM_FEATURE_V8)) {
3683         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3684             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3685              * using Long-desciptor translation table format */
3686             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3687         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3688             /* In an implementation that includes the Security Extensions
3689              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3690              * Short-descriptor translation table format.
3691              */
3692             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3693         } else {
3694             value &= TTBCR_N;
3695         }
3696     }
3697 
3698     /* Update the masks corresponding to the TCR bank being written
3699      * Note that we always calculate mask and base_mask, but
3700      * they are only used for short-descriptor tables (ie if EAE is 0);
3701      * for long-descriptor tables the TCR fields are used differently
3702      * and the mask and base_mask values are meaningless.
3703      */
3704     tcr->raw_tcr = value;
3705     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3706     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3707 }
3708 
3709 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3710                              uint64_t value)
3711 {
3712     ARMCPU *cpu = env_archcpu(env);
3713     TCR *tcr = raw_ptr(env, ri);
3714 
3715     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3716         /* With LPAE the TTBCR could result in a change of ASID
3717          * via the TTBCR.A1 bit, so do a TLB flush.
3718          */
3719         tlb_flush(CPU(cpu));
3720     }
3721     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3722     value = deposit64(tcr->raw_tcr, 0, 32, value);
3723     vmsa_ttbcr_raw_write(env, ri, value);
3724 }
3725 
3726 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3727 {
3728     TCR *tcr = raw_ptr(env, ri);
3729 
3730     /* Reset both the TCR as well as the masks corresponding to the bank of
3731      * the TCR being reset.
3732      */
3733     tcr->raw_tcr = 0;
3734     tcr->mask = 0;
3735     tcr->base_mask = 0xffffc000u;
3736 }
3737 
3738 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3739                                uint64_t value)
3740 {
3741     ARMCPU *cpu = env_archcpu(env);
3742     TCR *tcr = raw_ptr(env, ri);
3743 
3744     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3745     tlb_flush(CPU(cpu));
3746     tcr->raw_tcr = value;
3747 }
3748 
3749 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3750                             uint64_t value)
3751 {
3752     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3753     if (cpreg_field_is_64bit(ri) &&
3754         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3755         ARMCPU *cpu = env_archcpu(env);
3756         tlb_flush(CPU(cpu));
3757     }
3758     raw_write(env, ri, value);
3759 }
3760 
3761 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3762                                     uint64_t value)
3763 {
3764     /*
3765      * If we are running with E2&0 regime, then an ASID is active.
3766      * Flush if that might be changing.  Note we're not checking
3767      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
3768      * holds the active ASID, only checking the field that might.
3769      */
3770     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
3771         (arm_hcr_el2_eff(env) & HCR_E2H)) {
3772         uint16_t mask = ARMMMUIdxBit_E20_2 |
3773                         ARMMMUIdxBit_E20_2_PAN |
3774                         ARMMMUIdxBit_E20_0;
3775 
3776         if (arm_is_secure_below_el3(env)) {
3777             mask >>= ARM_MMU_IDX_A_NS;
3778         }
3779 
3780         tlb_flush_by_mmuidx(env_cpu(env), mask);
3781     }
3782     raw_write(env, ri, value);
3783 }
3784 
3785 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3786                         uint64_t value)
3787 {
3788     ARMCPU *cpu = env_archcpu(env);
3789     CPUState *cs = CPU(cpu);
3790 
3791     /*
3792      * A change in VMID to the stage2 page table (Stage2) invalidates
3793      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
3794      */
3795     if (raw_read(env, ri) != value) {
3796         uint16_t mask = ARMMMUIdxBit_E10_1 |
3797                         ARMMMUIdxBit_E10_1_PAN |
3798                         ARMMMUIdxBit_E10_0;
3799 
3800         if (arm_is_secure_below_el3(env)) {
3801             mask >>= ARM_MMU_IDX_A_NS;
3802         }
3803 
3804         tlb_flush_by_mmuidx(cs, mask);
3805         raw_write(env, ri, value);
3806     }
3807 }
3808 
3809 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3810     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3811       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
3812       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3813                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3814     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3815       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3816       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3817                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3818     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3819       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3820       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3821                              offsetof(CPUARMState, cp15.dfar_ns) } },
3822     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3823       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3824       .access = PL1_RW, .accessfn = access_tvm_trvm,
3825       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3826       .resetvalue = 0, },
3827 };
3828 
3829 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3830     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3831       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3832       .access = PL1_RW, .accessfn = access_tvm_trvm,
3833       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3834     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3835       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3836       .access = PL1_RW, .accessfn = access_tvm_trvm,
3837       .writefn = vmsa_ttbr_write, .resetvalue = 0,
3838       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3839                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3840     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3841       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3842       .access = PL1_RW, .accessfn = access_tvm_trvm,
3843       .writefn = vmsa_ttbr_write, .resetvalue = 0,
3844       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3845                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3846     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3847       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3848       .access = PL1_RW, .accessfn = access_tvm_trvm,
3849       .writefn = vmsa_tcr_el12_write,
3850       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3851       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3852     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3853       .access = PL1_RW, .accessfn = access_tvm_trvm,
3854       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3855       .raw_writefn = vmsa_ttbcr_raw_write,
3856       /* No offsetoflow32 -- pass the entire TCR to writefn/raw_writefn. */
3857       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.tcr_el[3]),
3858                              offsetof(CPUARMState, cp15.tcr_el[1])} },
3859 };
3860 
3861 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3862  * qemu tlbs nor adjusting cached masks.
3863  */
3864 static const ARMCPRegInfo ttbcr2_reginfo = {
3865     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3866     .access = PL1_RW, .accessfn = access_tvm_trvm,
3867     .type = ARM_CP_ALIAS,
3868     .bank_fieldoffsets = {
3869         offsetofhigh32(CPUARMState, cp15.tcr_el[3].raw_tcr),
3870         offsetofhigh32(CPUARMState, cp15.tcr_el[1].raw_tcr),
3871     },
3872 };
3873 
3874 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3875                                 uint64_t value)
3876 {
3877     env->cp15.c15_ticonfig = value & 0xe7;
3878     /* The OS_TYPE bit in this register changes the reported CPUID! */
3879     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3880         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3881 }
3882 
3883 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3884                                 uint64_t value)
3885 {
3886     env->cp15.c15_threadid = value & 0xffff;
3887 }
3888 
3889 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3890                            uint64_t value)
3891 {
3892     /* Wait-for-interrupt (deprecated) */
3893     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
3894 }
3895 
3896 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3897                                   uint64_t value)
3898 {
3899     /* On OMAP there are registers indicating the max/min index of dcache lines
3900      * containing a dirty line; cache flush operations have to reset these.
3901      */
3902     env->cp15.c15_i_max = 0x000;
3903     env->cp15.c15_i_min = 0xff0;
3904 }
3905 
3906 static const ARMCPRegInfo omap_cp_reginfo[] = {
3907     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3908       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3909       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3910       .resetvalue = 0, },
3911     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3912       .access = PL1_RW, .type = ARM_CP_NOP },
3913     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3914       .access = PL1_RW,
3915       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3916       .writefn = omap_ticonfig_write },
3917     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3918       .access = PL1_RW,
3919       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3920     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3921       .access = PL1_RW, .resetvalue = 0xff0,
3922       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3923     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3924       .access = PL1_RW,
3925       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3926       .writefn = omap_threadid_write },
3927     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3928       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3929       .type = ARM_CP_NO_RAW,
3930       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3931     /* TODO: Peripheral port remap register:
3932      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3933      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3934      * when MMU is off.
3935      */
3936     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3937       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3938       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3939       .writefn = omap_cachemaint_write },
3940     { .name = "C9", .cp = 15, .crn = 9,
3941       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3942       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3943 };
3944 
3945 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3946                               uint64_t value)
3947 {
3948     env->cp15.c15_cpar = value & 0x3fff;
3949 }
3950 
3951 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3952     { .name = "XSCALE_CPAR",
3953       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3954       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3955       .writefn = xscale_cpar_write, },
3956     { .name = "XSCALE_AUXCR",
3957       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3958       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3959       .resetvalue = 0, },
3960     /* XScale specific cache-lockdown: since we have no cache we NOP these
3961      * and hope the guest does not really rely on cache behaviour.
3962      */
3963     { .name = "XSCALE_LOCK_ICACHE_LINE",
3964       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3965       .access = PL1_W, .type = ARM_CP_NOP },
3966     { .name = "XSCALE_UNLOCK_ICACHE",
3967       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3968       .access = PL1_W, .type = ARM_CP_NOP },
3969     { .name = "XSCALE_DCACHE_LOCK",
3970       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3971       .access = PL1_RW, .type = ARM_CP_NOP },
3972     { .name = "XSCALE_UNLOCK_DCACHE",
3973       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3974       .access = PL1_W, .type = ARM_CP_NOP },
3975 };
3976 
3977 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3978     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3979      * implementation of this implementation-defined space.
3980      * Ideally this should eventually disappear in favour of actually
3981      * implementing the correct behaviour for all cores.
3982      */
3983     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3984       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3985       .access = PL1_RW,
3986       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3987       .resetvalue = 0 },
3988 };
3989 
3990 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3991     /* Cache status: RAZ because we have no cache so it's always clean */
3992     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3993       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3994       .resetvalue = 0 },
3995 };
3996 
3997 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
3998     /* We never have a a block transfer operation in progress */
3999     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
4000       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4001       .resetvalue = 0 },
4002     /* The cache ops themselves: these all NOP for QEMU */
4003     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
4004       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4005     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
4006       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4007     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
4008       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4009     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4010       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4011     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4012       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4013     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4014       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4015 };
4016 
4017 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4018     /* The cache test-and-clean instructions always return (1 << 30)
4019      * to indicate that there are no dirty cache lines.
4020      */
4021     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4022       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4023       .resetvalue = (1 << 30) },
4024     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4025       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4026       .resetvalue = (1 << 30) },
4027 };
4028 
4029 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4030     /* Ignore ReadBuffer accesses */
4031     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4032       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4033       .access = PL1_RW, .resetvalue = 0,
4034       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4035 };
4036 
4037 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4038 {
4039     unsigned int cur_el = arm_current_el(env);
4040 
4041     if (arm_is_el2_enabled(env) && cur_el == 1) {
4042         return env->cp15.vpidr_el2;
4043     }
4044     return raw_read(env, ri);
4045 }
4046 
4047 static uint64_t mpidr_read_val(CPUARMState *env)
4048 {
4049     ARMCPU *cpu = env_archcpu(env);
4050     uint64_t mpidr = cpu->mp_affinity;
4051 
4052     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4053         mpidr |= (1U << 31);
4054         /* Cores which are uniprocessor (non-coherent)
4055          * but still implement the MP extensions set
4056          * bit 30. (For instance, Cortex-R5).
4057          */
4058         if (cpu->mp_is_up) {
4059             mpidr |= (1u << 30);
4060         }
4061     }
4062     return mpidr;
4063 }
4064 
4065 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4066 {
4067     unsigned int cur_el = arm_current_el(env);
4068 
4069     if (arm_is_el2_enabled(env) && cur_el == 1) {
4070         return env->cp15.vmpidr_el2;
4071     }
4072     return mpidr_read_val(env);
4073 }
4074 
4075 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4076     /* NOP AMAIR0/1 */
4077     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4078       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4079       .access = PL1_RW, .accessfn = access_tvm_trvm,
4080       .type = ARM_CP_CONST, .resetvalue = 0 },
4081     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4082     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4083       .access = PL1_RW, .accessfn = access_tvm_trvm,
4084       .type = ARM_CP_CONST, .resetvalue = 0 },
4085     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4086       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4087       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4088                              offsetof(CPUARMState, cp15.par_ns)} },
4089     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4090       .access = PL1_RW, .accessfn = access_tvm_trvm,
4091       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4092       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4093                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4094       .writefn = vmsa_ttbr_write, },
4095     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4096       .access = PL1_RW, .accessfn = access_tvm_trvm,
4097       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4098       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4099                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4100       .writefn = vmsa_ttbr_write, },
4101 };
4102 
4103 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4104 {
4105     return vfp_get_fpcr(env);
4106 }
4107 
4108 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4109                             uint64_t value)
4110 {
4111     vfp_set_fpcr(env, value);
4112 }
4113 
4114 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4115 {
4116     return vfp_get_fpsr(env);
4117 }
4118 
4119 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4120                             uint64_t value)
4121 {
4122     vfp_set_fpsr(env, value);
4123 }
4124 
4125 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4126                                        bool isread)
4127 {
4128     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4129         return CP_ACCESS_TRAP;
4130     }
4131     return CP_ACCESS_OK;
4132 }
4133 
4134 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4135                             uint64_t value)
4136 {
4137     env->daif = value & PSTATE_DAIF;
4138 }
4139 
4140 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4141 {
4142     return env->pstate & PSTATE_PAN;
4143 }
4144 
4145 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4146                            uint64_t value)
4147 {
4148     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4149 }
4150 
4151 static const ARMCPRegInfo pan_reginfo = {
4152     .name = "PAN", .state = ARM_CP_STATE_AA64,
4153     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4154     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4155     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4156 };
4157 
4158 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4159 {
4160     return env->pstate & PSTATE_UAO;
4161 }
4162 
4163 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4164                            uint64_t value)
4165 {
4166     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4167 }
4168 
4169 static const ARMCPRegInfo uao_reginfo = {
4170     .name = "UAO", .state = ARM_CP_STATE_AA64,
4171     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4172     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4173     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4174 };
4175 
4176 static uint64_t aa64_dit_read(CPUARMState *env, const ARMCPRegInfo *ri)
4177 {
4178     return env->pstate & PSTATE_DIT;
4179 }
4180 
4181 static void aa64_dit_write(CPUARMState *env, const ARMCPRegInfo *ri,
4182                            uint64_t value)
4183 {
4184     env->pstate = (env->pstate & ~PSTATE_DIT) | (value & PSTATE_DIT);
4185 }
4186 
4187 static const ARMCPRegInfo dit_reginfo = {
4188     .name = "DIT", .state = ARM_CP_STATE_AA64,
4189     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 5,
4190     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4191     .readfn = aa64_dit_read, .writefn = aa64_dit_write
4192 };
4193 
4194 static uint64_t aa64_ssbs_read(CPUARMState *env, const ARMCPRegInfo *ri)
4195 {
4196     return env->pstate & PSTATE_SSBS;
4197 }
4198 
4199 static void aa64_ssbs_write(CPUARMState *env, const ARMCPRegInfo *ri,
4200                            uint64_t value)
4201 {
4202     env->pstate = (env->pstate & ~PSTATE_SSBS) | (value & PSTATE_SSBS);
4203 }
4204 
4205 static const ARMCPRegInfo ssbs_reginfo = {
4206     .name = "SSBS", .state = ARM_CP_STATE_AA64,
4207     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 6,
4208     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4209     .readfn = aa64_ssbs_read, .writefn = aa64_ssbs_write
4210 };
4211 
4212 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4213                                               const ARMCPRegInfo *ri,
4214                                               bool isread)
4215 {
4216     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4217     switch (arm_current_el(env)) {
4218     case 0:
4219         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4220         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4221             return CP_ACCESS_TRAP;
4222         }
4223         /* fall through */
4224     case 1:
4225         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4226         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4227             return CP_ACCESS_TRAP_EL2;
4228         }
4229         break;
4230     }
4231     return CP_ACCESS_OK;
4232 }
4233 
4234 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4235                                               const ARMCPRegInfo *ri,
4236                                               bool isread)
4237 {
4238     /* Cache invalidate/clean to Point of Unification... */
4239     switch (arm_current_el(env)) {
4240     case 0:
4241         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4242         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4243             return CP_ACCESS_TRAP;
4244         }
4245         /* fall through */
4246     case 1:
4247         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4248         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4249             return CP_ACCESS_TRAP_EL2;
4250         }
4251         break;
4252     }
4253     return CP_ACCESS_OK;
4254 }
4255 
4256 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4257  * Page D4-1736 (DDI0487A.b)
4258  */
4259 
4260 static int vae1_tlbmask(CPUARMState *env)
4261 {
4262     uint64_t hcr = arm_hcr_el2_eff(env);
4263     uint16_t mask;
4264 
4265     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4266         mask = ARMMMUIdxBit_E20_2 |
4267                ARMMMUIdxBit_E20_2_PAN |
4268                ARMMMUIdxBit_E20_0;
4269     } else {
4270         mask = ARMMMUIdxBit_E10_1 |
4271                ARMMMUIdxBit_E10_1_PAN |
4272                ARMMMUIdxBit_E10_0;
4273     }
4274 
4275     if (arm_is_secure_below_el3(env)) {
4276         mask >>= ARM_MMU_IDX_A_NS;
4277     }
4278 
4279     return mask;
4280 }
4281 
4282 /* Return 56 if TBI is enabled, 64 otherwise. */
4283 static int tlbbits_for_regime(CPUARMState *env, ARMMMUIdx mmu_idx,
4284                               uint64_t addr)
4285 {
4286     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
4287     int tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
4288     int select = extract64(addr, 55, 1);
4289 
4290     return (tbi >> select) & 1 ? 56 : 64;
4291 }
4292 
4293 static int vae1_tlbbits(CPUARMState *env, uint64_t addr)
4294 {
4295     uint64_t hcr = arm_hcr_el2_eff(env);
4296     ARMMMUIdx mmu_idx;
4297 
4298     /* Only the regime of the mmu_idx below is significant. */
4299     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4300         mmu_idx = ARMMMUIdx_E20_0;
4301     } else {
4302         mmu_idx = ARMMMUIdx_E10_0;
4303     }
4304 
4305     if (arm_is_secure_below_el3(env)) {
4306         mmu_idx &= ~ARM_MMU_IDX_A_NS;
4307     }
4308 
4309     return tlbbits_for_regime(env, mmu_idx, addr);
4310 }
4311 
4312 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4313                                       uint64_t value)
4314 {
4315     CPUState *cs = env_cpu(env);
4316     int mask = vae1_tlbmask(env);
4317 
4318     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4319 }
4320 
4321 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4322                                     uint64_t value)
4323 {
4324     CPUState *cs = env_cpu(env);
4325     int mask = vae1_tlbmask(env);
4326 
4327     if (tlb_force_broadcast(env)) {
4328         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4329     } else {
4330         tlb_flush_by_mmuidx(cs, mask);
4331     }
4332 }
4333 
4334 static int alle1_tlbmask(CPUARMState *env)
4335 {
4336     /*
4337      * Note that the 'ALL' scope must invalidate both stage 1 and
4338      * stage 2 translations, whereas most other scopes only invalidate
4339      * stage 1 translations.
4340      */
4341     if (arm_is_secure_below_el3(env)) {
4342         return ARMMMUIdxBit_SE10_1 |
4343                ARMMMUIdxBit_SE10_1_PAN |
4344                ARMMMUIdxBit_SE10_0;
4345     } else {
4346         return ARMMMUIdxBit_E10_1 |
4347                ARMMMUIdxBit_E10_1_PAN |
4348                ARMMMUIdxBit_E10_0;
4349     }
4350 }
4351 
4352 static int e2_tlbmask(CPUARMState *env)
4353 {
4354     if (arm_is_secure_below_el3(env)) {
4355         return ARMMMUIdxBit_SE20_0 |
4356                ARMMMUIdxBit_SE20_2 |
4357                ARMMMUIdxBit_SE20_2_PAN |
4358                ARMMMUIdxBit_SE2;
4359     } else {
4360         return ARMMMUIdxBit_E20_0 |
4361                ARMMMUIdxBit_E20_2 |
4362                ARMMMUIdxBit_E20_2_PAN |
4363                ARMMMUIdxBit_E2;
4364     }
4365 }
4366 
4367 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4368                                   uint64_t value)
4369 {
4370     CPUState *cs = env_cpu(env);
4371     int mask = alle1_tlbmask(env);
4372 
4373     tlb_flush_by_mmuidx(cs, mask);
4374 }
4375 
4376 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4377                                   uint64_t value)
4378 {
4379     CPUState *cs = env_cpu(env);
4380     int mask = e2_tlbmask(env);
4381 
4382     tlb_flush_by_mmuidx(cs, mask);
4383 }
4384 
4385 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4386                                   uint64_t value)
4387 {
4388     ARMCPU *cpu = env_archcpu(env);
4389     CPUState *cs = CPU(cpu);
4390 
4391     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4392 }
4393 
4394 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4395                                     uint64_t value)
4396 {
4397     CPUState *cs = env_cpu(env);
4398     int mask = alle1_tlbmask(env);
4399 
4400     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4401 }
4402 
4403 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4404                                     uint64_t value)
4405 {
4406     CPUState *cs = env_cpu(env);
4407     int mask = e2_tlbmask(env);
4408 
4409     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4410 }
4411 
4412 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4413                                     uint64_t value)
4414 {
4415     CPUState *cs = env_cpu(env);
4416 
4417     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4418 }
4419 
4420 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4421                                  uint64_t value)
4422 {
4423     /* Invalidate by VA, EL2
4424      * Currently handles both VAE2 and VALE2, since we don't support
4425      * flush-last-level-only.
4426      */
4427     CPUState *cs = env_cpu(env);
4428     int mask = e2_tlbmask(env);
4429     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4430 
4431     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4432 }
4433 
4434 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4435                                  uint64_t value)
4436 {
4437     /* Invalidate by VA, EL3
4438      * Currently handles both VAE3 and VALE3, since we don't support
4439      * flush-last-level-only.
4440      */
4441     ARMCPU *cpu = env_archcpu(env);
4442     CPUState *cs = CPU(cpu);
4443     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4444 
4445     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4446 }
4447 
4448 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4449                                    uint64_t value)
4450 {
4451     CPUState *cs = env_cpu(env);
4452     int mask = vae1_tlbmask(env);
4453     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4454     int bits = vae1_tlbbits(env, pageaddr);
4455 
4456     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4457 }
4458 
4459 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4460                                  uint64_t value)
4461 {
4462     /* Invalidate by VA, EL1&0 (AArch64 version).
4463      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4464      * since we don't support flush-for-specific-ASID-only or
4465      * flush-last-level-only.
4466      */
4467     CPUState *cs = env_cpu(env);
4468     int mask = vae1_tlbmask(env);
4469     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4470     int bits = vae1_tlbbits(env, pageaddr);
4471 
4472     if (tlb_force_broadcast(env)) {
4473         tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4474     } else {
4475         tlb_flush_page_bits_by_mmuidx(cs, pageaddr, mask, bits);
4476     }
4477 }
4478 
4479 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4480                                    uint64_t value)
4481 {
4482     CPUState *cs = env_cpu(env);
4483     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4484     bool secure = arm_is_secure_below_el3(env);
4485     int mask = secure ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2;
4486     int bits = tlbbits_for_regime(env, secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2,
4487                                   pageaddr);
4488 
4489     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4490 }
4491 
4492 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4493                                    uint64_t value)
4494 {
4495     CPUState *cs = env_cpu(env);
4496     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4497     int bits = tlbbits_for_regime(env, ARMMMUIdx_SE3, pageaddr);
4498 
4499     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr,
4500                                                   ARMMMUIdxBit_SE3, bits);
4501 }
4502 
4503 #ifdef TARGET_AARCH64
4504 typedef struct {
4505     uint64_t base;
4506     uint64_t length;
4507 } TLBIRange;
4508 
4509 static TLBIRange tlbi_aa64_get_range(CPUARMState *env, ARMMMUIdx mmuidx,
4510                                      uint64_t value)
4511 {
4512     unsigned int page_size_granule, page_shift, num, scale, exponent;
4513     /* Extract one bit to represent the va selector in use. */
4514     uint64_t select = sextract64(value, 36, 1);
4515     ARMVAParameters param = aa64_va_parameters(env, select, mmuidx, true);
4516     TLBIRange ret = { };
4517 
4518     page_size_granule = extract64(value, 46, 2);
4519 
4520     /* The granule encoded in value must match the granule in use. */
4521     if (page_size_granule != (param.using64k ? 3 : param.using16k ? 2 : 1)) {
4522         qemu_log_mask(LOG_GUEST_ERROR, "Invalid tlbi page size granule %d\n",
4523                       page_size_granule);
4524         return ret;
4525     }
4526 
4527     page_shift = (page_size_granule - 1) * 2 + 12;
4528     num = extract64(value, 39, 5);
4529     scale = extract64(value, 44, 2);
4530     exponent = (5 * scale) + 1;
4531 
4532     ret.length = (num + 1) << (exponent + page_shift);
4533 
4534     if (param.select) {
4535         ret.base = sextract64(value, 0, 37);
4536     } else {
4537         ret.base = extract64(value, 0, 37);
4538     }
4539     if (param.ds) {
4540         /*
4541          * With DS=1, BaseADDR is always shifted 16 so that it is able
4542          * to address all 52 va bits.  The input address is perforce
4543          * aligned on a 64k boundary regardless of translation granule.
4544          */
4545         page_shift = 16;
4546     }
4547     ret.base <<= page_shift;
4548 
4549     return ret;
4550 }
4551 
4552 static void do_rvae_write(CPUARMState *env, uint64_t value,
4553                           int idxmap, bool synced)
4554 {
4555     ARMMMUIdx one_idx = ARM_MMU_IDX_A | ctz32(idxmap);
4556     TLBIRange range;
4557     int bits;
4558 
4559     range = tlbi_aa64_get_range(env, one_idx, value);
4560     bits = tlbbits_for_regime(env, one_idx, range.base);
4561 
4562     if (synced) {
4563         tlb_flush_range_by_mmuidx_all_cpus_synced(env_cpu(env),
4564                                                   range.base,
4565                                                   range.length,
4566                                                   idxmap,
4567                                                   bits);
4568     } else {
4569         tlb_flush_range_by_mmuidx(env_cpu(env), range.base,
4570                                   range.length, idxmap, bits);
4571     }
4572 }
4573 
4574 static void tlbi_aa64_rvae1_write(CPUARMState *env,
4575                                   const ARMCPRegInfo *ri,
4576                                   uint64_t value)
4577 {
4578     /*
4579      * Invalidate by VA range, EL1&0.
4580      * Currently handles all of RVAE1, RVAAE1, RVAALE1 and RVALE1,
4581      * since we don't support flush-for-specific-ASID-only or
4582      * flush-last-level-only.
4583      */
4584 
4585     do_rvae_write(env, value, vae1_tlbmask(env),
4586                   tlb_force_broadcast(env));
4587 }
4588 
4589 static void tlbi_aa64_rvae1is_write(CPUARMState *env,
4590                                     const ARMCPRegInfo *ri,
4591                                     uint64_t value)
4592 {
4593     /*
4594      * Invalidate by VA range, Inner/Outer Shareable EL1&0.
4595      * Currently handles all of RVAE1IS, RVAE1OS, RVAAE1IS, RVAAE1OS,
4596      * RVAALE1IS, RVAALE1OS, RVALE1IS and RVALE1OS, since we don't support
4597      * flush-for-specific-ASID-only, flush-last-level-only or inner/outer
4598      * shareable specific flushes.
4599      */
4600 
4601     do_rvae_write(env, value, vae1_tlbmask(env), true);
4602 }
4603 
4604 static int vae2_tlbmask(CPUARMState *env)
4605 {
4606     return (arm_is_secure_below_el3(env)
4607             ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2);
4608 }
4609 
4610 static void tlbi_aa64_rvae2_write(CPUARMState *env,
4611                                   const ARMCPRegInfo *ri,
4612                                   uint64_t value)
4613 {
4614     /*
4615      * Invalidate by VA range, EL2.
4616      * Currently handles all of RVAE2 and RVALE2,
4617      * since we don't support flush-for-specific-ASID-only or
4618      * flush-last-level-only.
4619      */
4620 
4621     do_rvae_write(env, value, vae2_tlbmask(env),
4622                   tlb_force_broadcast(env));
4623 
4624 
4625 }
4626 
4627 static void tlbi_aa64_rvae2is_write(CPUARMState *env,
4628                                     const ARMCPRegInfo *ri,
4629                                     uint64_t value)
4630 {
4631     /*
4632      * Invalidate by VA range, Inner/Outer Shareable, EL2.
4633      * Currently handles all of RVAE2IS, RVAE2OS, RVALE2IS and RVALE2OS,
4634      * since we don't support flush-for-specific-ASID-only,
4635      * flush-last-level-only or inner/outer shareable specific flushes.
4636      */
4637 
4638     do_rvae_write(env, value, vae2_tlbmask(env), true);
4639 
4640 }
4641 
4642 static void tlbi_aa64_rvae3_write(CPUARMState *env,
4643                                   const ARMCPRegInfo *ri,
4644                                   uint64_t value)
4645 {
4646     /*
4647      * Invalidate by VA range, EL3.
4648      * Currently handles all of RVAE3 and RVALE3,
4649      * since we don't support flush-for-specific-ASID-only or
4650      * flush-last-level-only.
4651      */
4652 
4653     do_rvae_write(env, value, ARMMMUIdxBit_SE3,
4654                   tlb_force_broadcast(env));
4655 }
4656 
4657 static void tlbi_aa64_rvae3is_write(CPUARMState *env,
4658                                     const ARMCPRegInfo *ri,
4659                                     uint64_t value)
4660 {
4661     /*
4662      * Invalidate by VA range, EL3, Inner/Outer Shareable.
4663      * Currently handles all of RVAE3IS, RVAE3OS, RVALE3IS and RVALE3OS,
4664      * since we don't support flush-for-specific-ASID-only,
4665      * flush-last-level-only or inner/outer specific flushes.
4666      */
4667 
4668     do_rvae_write(env, value, ARMMMUIdxBit_SE3, true);
4669 }
4670 #endif
4671 
4672 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4673                                       bool isread)
4674 {
4675     int cur_el = arm_current_el(env);
4676 
4677     if (cur_el < 2) {
4678         uint64_t hcr = arm_hcr_el2_eff(env);
4679 
4680         if (cur_el == 0) {
4681             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4682                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4683                     return CP_ACCESS_TRAP_EL2;
4684                 }
4685             } else {
4686                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4687                     return CP_ACCESS_TRAP;
4688                 }
4689                 if (hcr & HCR_TDZ) {
4690                     return CP_ACCESS_TRAP_EL2;
4691                 }
4692             }
4693         } else if (hcr & HCR_TDZ) {
4694             return CP_ACCESS_TRAP_EL2;
4695         }
4696     }
4697     return CP_ACCESS_OK;
4698 }
4699 
4700 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4701 {
4702     ARMCPU *cpu = env_archcpu(env);
4703     int dzp_bit = 1 << 4;
4704 
4705     /* DZP indicates whether DC ZVA access is allowed */
4706     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4707         dzp_bit = 0;
4708     }
4709     return cpu->dcz_blocksize | dzp_bit;
4710 }
4711 
4712 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4713                                     bool isread)
4714 {
4715     if (!(env->pstate & PSTATE_SP)) {
4716         /* Access to SP_EL0 is undefined if it's being used as
4717          * the stack pointer.
4718          */
4719         return CP_ACCESS_TRAP_UNCATEGORIZED;
4720     }
4721     return CP_ACCESS_OK;
4722 }
4723 
4724 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4725 {
4726     return env->pstate & PSTATE_SP;
4727 }
4728 
4729 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4730 {
4731     update_spsel(env, val);
4732 }
4733 
4734 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4735                         uint64_t value)
4736 {
4737     ARMCPU *cpu = env_archcpu(env);
4738 
4739     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4740         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4741         value &= ~SCTLR_M;
4742     }
4743 
4744     /* ??? Lots of these bits are not implemented.  */
4745 
4746     if (ri->state == ARM_CP_STATE_AA64 && !cpu_isar_feature(aa64_mte, cpu)) {
4747         if (ri->opc1 == 6) { /* SCTLR_EL3 */
4748             value &= ~(SCTLR_ITFSB | SCTLR_TCF | SCTLR_ATA);
4749         } else {
4750             value &= ~(SCTLR_ITFSB | SCTLR_TCF0 | SCTLR_TCF |
4751                        SCTLR_ATA0 | SCTLR_ATA);
4752         }
4753     }
4754 
4755     if (raw_read(env, ri) == value) {
4756         /* Skip the TLB flush if nothing actually changed; Linux likes
4757          * to do a lot of pointless SCTLR writes.
4758          */
4759         return;
4760     }
4761 
4762     raw_write(env, ri, value);
4763 
4764     /* This may enable/disable the MMU, so do a TLB flush.  */
4765     tlb_flush(CPU(cpu));
4766 
4767     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4768         /*
4769          * Normally we would always end the TB on an SCTLR write; see the
4770          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4771          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4772          * of hflags from the translator, so do it here.
4773          */
4774         arm_rebuild_hflags(env);
4775     }
4776 }
4777 
4778 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4779                        uint64_t value)
4780 {
4781     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4782 }
4783 
4784 static const ARMCPRegInfo v8_cp_reginfo[] = {
4785     /* Minimal set of EL0-visible registers. This will need to be expanded
4786      * significantly for system emulation of AArch64 CPUs.
4787      */
4788     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4789       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4790       .access = PL0_RW, .type = ARM_CP_NZCV },
4791     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4792       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4793       .type = ARM_CP_NO_RAW,
4794       .access = PL0_RW, .accessfn = aa64_daif_access,
4795       .fieldoffset = offsetof(CPUARMState, daif),
4796       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4797     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4798       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4799       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4800       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4801     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4802       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4803       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4804       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4805     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4806       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4807       .access = PL0_R, .type = ARM_CP_NO_RAW,
4808       .readfn = aa64_dczid_read },
4809     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4810       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4811       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4812 #ifndef CONFIG_USER_ONLY
4813       /* Avoid overhead of an access check that always passes in user-mode */
4814       .accessfn = aa64_zva_access,
4815 #endif
4816     },
4817     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4818       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4819       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4820     /* Cache ops: all NOPs since we don't emulate caches */
4821     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4822       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4823       .access = PL1_W, .type = ARM_CP_NOP,
4824       .accessfn = aa64_cacheop_pou_access },
4825     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4826       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4827       .access = PL1_W, .type = ARM_CP_NOP,
4828       .accessfn = aa64_cacheop_pou_access },
4829     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4830       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4831       .access = PL0_W, .type = ARM_CP_NOP,
4832       .accessfn = aa64_cacheop_pou_access },
4833     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4834       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4835       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4836       .type = ARM_CP_NOP },
4837     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4838       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4839       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4840     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4841       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4842       .access = PL0_W, .type = ARM_CP_NOP,
4843       .accessfn = aa64_cacheop_poc_access },
4844     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4845       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4846       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4847     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4848       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4849       .access = PL0_W, .type = ARM_CP_NOP,
4850       .accessfn = aa64_cacheop_pou_access },
4851     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4852       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4853       .access = PL0_W, .type = ARM_CP_NOP,
4854       .accessfn = aa64_cacheop_poc_access },
4855     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4856       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4857       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4858     /* TLBI operations */
4859     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4860       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4861       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4862       .writefn = tlbi_aa64_vmalle1is_write },
4863     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4864       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4865       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4866       .writefn = tlbi_aa64_vae1is_write },
4867     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4868       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4869       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4870       .writefn = tlbi_aa64_vmalle1is_write },
4871     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4872       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4873       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4874       .writefn = tlbi_aa64_vae1is_write },
4875     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4876       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4877       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4878       .writefn = tlbi_aa64_vae1is_write },
4879     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4880       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4881       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4882       .writefn = tlbi_aa64_vae1is_write },
4883     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4884       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4885       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4886       .writefn = tlbi_aa64_vmalle1_write },
4887     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4888       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4889       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4890       .writefn = tlbi_aa64_vae1_write },
4891     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4892       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4893       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4894       .writefn = tlbi_aa64_vmalle1_write },
4895     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4896       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4897       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4898       .writefn = tlbi_aa64_vae1_write },
4899     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4900       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4901       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4902       .writefn = tlbi_aa64_vae1_write },
4903     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4904       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4905       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4906       .writefn = tlbi_aa64_vae1_write },
4907     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4908       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4909       .access = PL2_W, .type = ARM_CP_NOP },
4910     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4911       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4912       .access = PL2_W, .type = ARM_CP_NOP },
4913     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4914       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4915       .access = PL2_W, .type = ARM_CP_NO_RAW,
4916       .writefn = tlbi_aa64_alle1is_write },
4917     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4918       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4919       .access = PL2_W, .type = ARM_CP_NO_RAW,
4920       .writefn = tlbi_aa64_alle1is_write },
4921     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4922       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4923       .access = PL2_W, .type = ARM_CP_NOP },
4924     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4925       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4926       .access = PL2_W, .type = ARM_CP_NOP },
4927     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4928       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4929       .access = PL2_W, .type = ARM_CP_NO_RAW,
4930       .writefn = tlbi_aa64_alle1_write },
4931     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4932       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4933       .access = PL2_W, .type = ARM_CP_NO_RAW,
4934       .writefn = tlbi_aa64_alle1is_write },
4935 #ifndef CONFIG_USER_ONLY
4936     /* 64 bit address translation operations */
4937     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4938       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4939       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4940       .writefn = ats_write64 },
4941     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4942       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4943       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4944       .writefn = ats_write64 },
4945     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4946       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4947       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4948       .writefn = ats_write64 },
4949     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4950       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4951       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4952       .writefn = ats_write64 },
4953     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4954       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4955       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4956       .writefn = ats_write64 },
4957     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4958       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4959       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4960       .writefn = ats_write64 },
4961     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4962       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4963       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4964       .writefn = ats_write64 },
4965     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4966       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4967       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4968       .writefn = ats_write64 },
4969     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4970     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4971       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4972       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4973       .writefn = ats_write64 },
4974     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4975       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4976       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4977       .writefn = ats_write64 },
4978     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4979       .type = ARM_CP_ALIAS,
4980       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4981       .access = PL1_RW, .resetvalue = 0,
4982       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4983       .writefn = par_write },
4984 #endif
4985     /* TLB invalidate last level of translation table walk */
4986     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4987       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4988       .writefn = tlbimva_is_write },
4989     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4990       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4991       .writefn = tlbimvaa_is_write },
4992     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4993       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4994       .writefn = tlbimva_write },
4995     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4996       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4997       .writefn = tlbimvaa_write },
4998     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4999       .type = ARM_CP_NO_RAW, .access = PL2_W,
5000       .writefn = tlbimva_hyp_write },
5001     { .name = "TLBIMVALHIS",
5002       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5003       .type = ARM_CP_NO_RAW, .access = PL2_W,
5004       .writefn = tlbimva_hyp_is_write },
5005     { .name = "TLBIIPAS2",
5006       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5007       .type = ARM_CP_NOP, .access = PL2_W },
5008     { .name = "TLBIIPAS2IS",
5009       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5010       .type = ARM_CP_NOP, .access = PL2_W },
5011     { .name = "TLBIIPAS2L",
5012       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5013       .type = ARM_CP_NOP, .access = PL2_W },
5014     { .name = "TLBIIPAS2LIS",
5015       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5016       .type = ARM_CP_NOP, .access = PL2_W },
5017     /* 32 bit cache operations */
5018     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5019       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5020     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5021       .type = ARM_CP_NOP, .access = PL1_W },
5022     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5023       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5024     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5025       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5026     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5027       .type = ARM_CP_NOP, .access = PL1_W },
5028     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5029       .type = ARM_CP_NOP, .access = PL1_W },
5030     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5031       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5032     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5033       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5034     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5035       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5036     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5037       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5038     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5039       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5040     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5041       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5042     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5043       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5044     /* MMU Domain access control / MPU write buffer control */
5045     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5046       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5047       .writefn = dacr_write, .raw_writefn = raw_write,
5048       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5049                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5050     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5051       .type = ARM_CP_ALIAS,
5052       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5053       .access = PL1_RW,
5054       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5055     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5056       .type = ARM_CP_ALIAS,
5057       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5058       .access = PL1_RW,
5059       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5060     /* We rely on the access checks not allowing the guest to write to the
5061      * state field when SPSel indicates that it's being used as the stack
5062      * pointer.
5063      */
5064     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5065       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5066       .access = PL1_RW, .accessfn = sp_el0_access,
5067       .type = ARM_CP_ALIAS,
5068       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5069     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5070       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5071       .access = PL2_RW, .type = ARM_CP_ALIAS,
5072       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5073     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5074       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5075       .type = ARM_CP_NO_RAW,
5076       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5077     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5078       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5079       .access = PL2_RW,
5080       .type = ARM_CP_ALIAS | ARM_CP_FPU | ARM_CP_EL3_NO_EL2_KEEP,
5081       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]) },
5082     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5083       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5084       .access = PL2_RW, .resetvalue = 0, .type = ARM_CP_EL3_NO_EL2_KEEP,
5085       .writefn = dacr_write, .raw_writefn = raw_write,
5086       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5087     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5088       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5089       .access = PL2_RW, .resetvalue = 0, .type = ARM_CP_EL3_NO_EL2_KEEP,
5090       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5091     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5092       .type = ARM_CP_ALIAS,
5093       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5094       .access = PL2_RW,
5095       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5096     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5097       .type = ARM_CP_ALIAS,
5098       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5099       .access = PL2_RW,
5100       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5101     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5102       .type = ARM_CP_ALIAS,
5103       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5104       .access = PL2_RW,
5105       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5106     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5107       .type = ARM_CP_ALIAS,
5108       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5109       .access = PL2_RW,
5110       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5111     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5112       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5113       .resetvalue = 0,
5114       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5115     { .name = "SDCR", .type = ARM_CP_ALIAS,
5116       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5117       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5118       .writefn = sdcr_write,
5119       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5120 };
5121 
5122 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5123 {
5124     ARMCPU *cpu = env_archcpu(env);
5125 
5126     if (arm_feature(env, ARM_FEATURE_V8)) {
5127         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5128     } else {
5129         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5130     }
5131 
5132     if (arm_feature(env, ARM_FEATURE_EL3)) {
5133         valid_mask &= ~HCR_HCD;
5134     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5135         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5136          * However, if we're using the SMC PSCI conduit then QEMU is
5137          * effectively acting like EL3 firmware and so the guest at
5138          * EL2 should retain the ability to prevent EL1 from being
5139          * able to make SMC calls into the ersatz firmware, so in
5140          * that case HCR.TSC should be read/write.
5141          */
5142         valid_mask &= ~HCR_TSC;
5143     }
5144 
5145     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5146         if (cpu_isar_feature(aa64_vh, cpu)) {
5147             valid_mask |= HCR_E2H;
5148         }
5149         if (cpu_isar_feature(aa64_ras, cpu)) {
5150             valid_mask |= HCR_TERR | HCR_TEA;
5151         }
5152         if (cpu_isar_feature(aa64_lor, cpu)) {
5153             valid_mask |= HCR_TLOR;
5154         }
5155         if (cpu_isar_feature(aa64_pauth, cpu)) {
5156             valid_mask |= HCR_API | HCR_APK;
5157         }
5158         if (cpu_isar_feature(aa64_mte, cpu)) {
5159             valid_mask |= HCR_ATA | HCR_DCT | HCR_TID5;
5160         }
5161         if (cpu_isar_feature(aa64_scxtnum, cpu)) {
5162             valid_mask |= HCR_ENSCXT;
5163         }
5164         if (cpu_isar_feature(aa64_fwb, cpu)) {
5165             valid_mask |= HCR_FWB;
5166         }
5167     }
5168 
5169     /* Clear RES0 bits.  */
5170     value &= valid_mask;
5171 
5172     /*
5173      * These bits change the MMU setup:
5174      * HCR_VM enables stage 2 translation
5175      * HCR_PTW forbids certain page-table setups
5176      * HCR_DC disables stage1 and enables stage2 translation
5177      * HCR_DCT enables tagging on (disabled) stage1 translation
5178      * HCR_FWB changes the interpretation of stage2 descriptor bits
5179      */
5180     if ((env->cp15.hcr_el2 ^ value) &
5181         (HCR_VM | HCR_PTW | HCR_DC | HCR_DCT | HCR_FWB)) {
5182         tlb_flush(CPU(cpu));
5183     }
5184     env->cp15.hcr_el2 = value;
5185 
5186     /*
5187      * Updates to VI and VF require us to update the status of
5188      * virtual interrupts, which are the logical OR of these bits
5189      * and the state of the input lines from the GIC. (This requires
5190      * that we have the iothread lock, which is done by marking the
5191      * reginfo structs as ARM_CP_IO.)
5192      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5193      * possible for it to be taken immediately, because VIRQ and
5194      * VFIQ are masked unless running at EL0 or EL1, and HCR
5195      * can only be written at EL2.
5196      */
5197     g_assert(qemu_mutex_iothread_locked());
5198     arm_cpu_update_virq(cpu);
5199     arm_cpu_update_vfiq(cpu);
5200     arm_cpu_update_vserr(cpu);
5201 }
5202 
5203 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5204 {
5205     do_hcr_write(env, value, 0);
5206 }
5207 
5208 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5209                           uint64_t value)
5210 {
5211     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5212     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5213     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5214 }
5215 
5216 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5217                          uint64_t value)
5218 {
5219     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5220     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5221     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5222 }
5223 
5224 /*
5225  * Return the effective value of HCR_EL2.
5226  * Bits that are not included here:
5227  * RW       (read from SCR_EL3.RW as needed)
5228  */
5229 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5230 {
5231     uint64_t ret = env->cp15.hcr_el2;
5232 
5233     if (!arm_is_el2_enabled(env)) {
5234         /*
5235          * "This register has no effect if EL2 is not enabled in the
5236          * current Security state".  This is ARMv8.4-SecEL2 speak for
5237          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5238          *
5239          * Prior to that, the language was "In an implementation that
5240          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5241          * as if this field is 0 for all purposes other than a direct
5242          * read or write access of HCR_EL2".  With lots of enumeration
5243          * on a per-field basis.  In current QEMU, this is condition
5244          * is arm_is_secure_below_el3.
5245          *
5246          * Since the v8.4 language applies to the entire register, and
5247          * appears to be backward compatible, use that.
5248          */
5249         return 0;
5250     }
5251 
5252     /*
5253      * For a cpu that supports both aarch64 and aarch32, we can set bits
5254      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5255      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5256      */
5257     if (!arm_el_is_aa64(env, 2)) {
5258         uint64_t aa32_valid;
5259 
5260         /*
5261          * These bits are up-to-date as of ARMv8.6.
5262          * For HCR, it's easiest to list just the 2 bits that are invalid.
5263          * For HCR2, list those that are valid.
5264          */
5265         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5266         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5267                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5268         ret &= aa32_valid;
5269     }
5270 
5271     if (ret & HCR_TGE) {
5272         /* These bits are up-to-date as of ARMv8.6.  */
5273         if (ret & HCR_E2H) {
5274             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5275                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5276                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5277                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5278                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5279                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5280         } else {
5281             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5282         }
5283         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5284                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5285                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5286                  HCR_TLOR);
5287     }
5288 
5289     return ret;
5290 }
5291 
5292 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5293                            uint64_t value)
5294 {
5295     /*
5296      * For A-profile AArch32 EL3, if NSACR.CP10
5297      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5298      */
5299     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5300         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5301         value &= ~(0x3 << 10);
5302         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5303     }
5304     env->cp15.cptr_el[2] = value;
5305 }
5306 
5307 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5308 {
5309     /*
5310      * For A-profile AArch32 EL3, if NSACR.CP10
5311      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5312      */
5313     uint64_t value = env->cp15.cptr_el[2];
5314 
5315     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5316         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5317         value |= 0x3 << 10;
5318     }
5319     return value;
5320 }
5321 
5322 static const ARMCPRegInfo el2_cp_reginfo[] = {
5323     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5324       .type = ARM_CP_IO,
5325       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5326       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5327       .writefn = hcr_write },
5328     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5329       .type = ARM_CP_ALIAS | ARM_CP_IO,
5330       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5331       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5332       .writefn = hcr_writelow },
5333     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5334       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5335       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5336     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5337       .type = ARM_CP_ALIAS,
5338       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5339       .access = PL2_RW,
5340       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5341     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5342       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5343       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5344     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5345       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5346       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5347     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5348       .type = ARM_CP_ALIAS,
5349       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5350       .access = PL2_RW,
5351       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5352     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5353       .type = ARM_CP_ALIAS,
5354       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5355       .access = PL2_RW,
5356       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5357     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5358       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5359       .access = PL2_RW, .writefn = vbar_write,
5360       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5361       .resetvalue = 0 },
5362     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5363       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5364       .access = PL3_RW, .type = ARM_CP_ALIAS,
5365       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5366     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5367       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5368       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5369       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5370       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5371     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5372       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5373       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5374       .resetvalue = 0 },
5375     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5376       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5377       .access = PL2_RW, .type = ARM_CP_ALIAS,
5378       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5379     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5380       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5381       .access = PL2_RW, .type = ARM_CP_CONST,
5382       .resetvalue = 0 },
5383     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5384     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5385       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5386       .access = PL2_RW, .type = ARM_CP_CONST,
5387       .resetvalue = 0 },
5388     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5389       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5390       .access = PL2_RW, .type = ARM_CP_CONST,
5391       .resetvalue = 0 },
5392     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5393       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5394       .access = PL2_RW, .type = ARM_CP_CONST,
5395       .resetvalue = 0 },
5396     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5397       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5398       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5399       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5400       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5401     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5402       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5403       .type = ARM_CP_ALIAS,
5404       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5405       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5406     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5407       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5408       .access = PL2_RW,
5409       /* no .writefn needed as this can't cause an ASID change;
5410        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5411        */
5412       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5413     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5414       .cp = 15, .opc1 = 6, .crm = 2,
5415       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5416       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5417       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5418       .writefn = vttbr_write },
5419     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5420       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5421       .access = PL2_RW, .writefn = vttbr_write,
5422       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5423     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5424       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5425       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5426       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5427     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5428       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5429       .access = PL2_RW, .resetvalue = 0,
5430       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5431     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5432       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5433       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5434       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5435     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5436       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5437       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5438     { .name = "TLBIALLNSNH",
5439       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5440       .type = ARM_CP_NO_RAW, .access = PL2_W,
5441       .writefn = tlbiall_nsnh_write },
5442     { .name = "TLBIALLNSNHIS",
5443       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5444       .type = ARM_CP_NO_RAW, .access = PL2_W,
5445       .writefn = tlbiall_nsnh_is_write },
5446     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5447       .type = ARM_CP_NO_RAW, .access = PL2_W,
5448       .writefn = tlbiall_hyp_write },
5449     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5450       .type = ARM_CP_NO_RAW, .access = PL2_W,
5451       .writefn = tlbiall_hyp_is_write },
5452     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5453       .type = ARM_CP_NO_RAW, .access = PL2_W,
5454       .writefn = tlbimva_hyp_write },
5455     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5456       .type = ARM_CP_NO_RAW, .access = PL2_W,
5457       .writefn = tlbimva_hyp_is_write },
5458     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5459       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5460       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5461       .writefn = tlbi_aa64_alle2_write },
5462     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5463       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5464       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5465       .writefn = tlbi_aa64_vae2_write },
5466     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5467       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5468       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5469       .writefn = tlbi_aa64_vae2_write },
5470     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5471       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5472       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5473       .writefn = tlbi_aa64_alle2is_write },
5474     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5475       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5476       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5477       .writefn = tlbi_aa64_vae2is_write },
5478     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5479       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5480       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5481       .writefn = tlbi_aa64_vae2is_write },
5482 #ifndef CONFIG_USER_ONLY
5483     /* Unlike the other EL2-related AT operations, these must
5484      * UNDEF from EL3 if EL2 is not implemented, which is why we
5485      * define them here rather than with the rest of the AT ops.
5486      */
5487     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5488       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5489       .access = PL2_W, .accessfn = at_s1e2_access,
5490       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC | ARM_CP_EL3_NO_EL2_UNDEF,
5491       .writefn = ats_write64 },
5492     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5493       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5494       .access = PL2_W, .accessfn = at_s1e2_access,
5495       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC | ARM_CP_EL3_NO_EL2_UNDEF,
5496       .writefn = ats_write64 },
5497     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5498      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5499      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5500      * to behave as if SCR.NS was 1.
5501      */
5502     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5503       .access = PL2_W,
5504       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5505     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5506       .access = PL2_W,
5507       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5508     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5509       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5510       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5511        * reset values as IMPDEF. We choose to reset to 3 to comply with
5512        * both ARMv7 and ARMv8.
5513        */
5514       .access = PL2_RW, .resetvalue = 3,
5515       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5516     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5517       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5518       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5519       .writefn = gt_cntvoff_write,
5520       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5521     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5522       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5523       .writefn = gt_cntvoff_write,
5524       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5525     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5526       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5527       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5528       .type = ARM_CP_IO, .access = PL2_RW,
5529       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5530     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5531       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5532       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5533       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5534     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5535       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5536       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5537       .resetfn = gt_hyp_timer_reset,
5538       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5539     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5540       .type = ARM_CP_IO,
5541       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5542       .access = PL2_RW,
5543       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5544       .resetvalue = 0,
5545       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5546 #endif
5547     /* The only field of MDCR_EL2 that has a defined architectural reset value
5548      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N.
5549      */
5550     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5551       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5552       .access = PL2_RW, .resetvalue = PMCR_NUM_COUNTERS,
5553       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5554     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5555       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5556       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5557       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5558     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5559       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5560       .access = PL2_RW,
5561       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5562     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5563       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5564       .access = PL2_RW,
5565       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5566 };
5567 
5568 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5569     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5570       .type = ARM_CP_ALIAS | ARM_CP_IO,
5571       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5572       .access = PL2_RW,
5573       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5574       .writefn = hcr_writehigh },
5575 };
5576 
5577 static CPAccessResult sel2_access(CPUARMState *env, const ARMCPRegInfo *ri,
5578                                   bool isread)
5579 {
5580     if (arm_current_el(env) == 3 || arm_is_secure_below_el3(env)) {
5581         return CP_ACCESS_OK;
5582     }
5583     return CP_ACCESS_TRAP_UNCATEGORIZED;
5584 }
5585 
5586 static const ARMCPRegInfo el2_sec_cp_reginfo[] = {
5587     { .name = "VSTTBR_EL2", .state = ARM_CP_STATE_AA64,
5588       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 0,
5589       .access = PL2_RW, .accessfn = sel2_access,
5590       .fieldoffset = offsetof(CPUARMState, cp15.vsttbr_el2) },
5591     { .name = "VSTCR_EL2", .state = ARM_CP_STATE_AA64,
5592       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 2,
5593       .access = PL2_RW, .accessfn = sel2_access,
5594       .fieldoffset = offsetof(CPUARMState, cp15.vstcr_el2) },
5595 };
5596 
5597 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5598                                    bool isread)
5599 {
5600     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5601      * At Secure EL1 it traps to EL3 or EL2.
5602      */
5603     if (arm_current_el(env) == 3) {
5604         return CP_ACCESS_OK;
5605     }
5606     if (arm_is_secure_below_el3(env)) {
5607         if (env->cp15.scr_el3 & SCR_EEL2) {
5608             return CP_ACCESS_TRAP_EL2;
5609         }
5610         return CP_ACCESS_TRAP_EL3;
5611     }
5612     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5613     if (isread) {
5614         return CP_ACCESS_OK;
5615     }
5616     return CP_ACCESS_TRAP_UNCATEGORIZED;
5617 }
5618 
5619 static const ARMCPRegInfo el3_cp_reginfo[] = {
5620     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5621       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5622       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5623       .resetfn = scr_reset, .writefn = scr_write },
5624     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5625       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5626       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5627       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5628       .writefn = scr_write },
5629     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5630       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5631       .access = PL3_RW, .resetvalue = 0,
5632       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5633     { .name = "SDER",
5634       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5635       .access = PL3_RW, .resetvalue = 0,
5636       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5637     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5638       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5639       .writefn = vbar_write, .resetvalue = 0,
5640       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5641     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5642       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5643       .access = PL3_RW, .resetvalue = 0,
5644       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5645     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5646       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5647       .access = PL3_RW,
5648       /* no .writefn needed as this can't cause an ASID change;
5649        * we must provide a .raw_writefn and .resetfn because we handle
5650        * reset and migration for the AArch32 TTBCR(S), which might be
5651        * using mask and base_mask.
5652        */
5653       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5654       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5655     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5656       .type = ARM_CP_ALIAS,
5657       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5658       .access = PL3_RW,
5659       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5660     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5661       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5662       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5663     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5664       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5665       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5666     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5667       .type = ARM_CP_ALIAS,
5668       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5669       .access = PL3_RW,
5670       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5671     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5672       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5673       .access = PL3_RW, .writefn = vbar_write,
5674       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5675       .resetvalue = 0 },
5676     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5677       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5678       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5679       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5680     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5681       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5682       .access = PL3_RW, .resetvalue = 0,
5683       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5684     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5685       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5686       .access = PL3_RW, .type = ARM_CP_CONST,
5687       .resetvalue = 0 },
5688     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5689       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5690       .access = PL3_RW, .type = ARM_CP_CONST,
5691       .resetvalue = 0 },
5692     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5693       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5694       .access = PL3_RW, .type = ARM_CP_CONST,
5695       .resetvalue = 0 },
5696     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5697       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5698       .access = PL3_W, .type = ARM_CP_NO_RAW,
5699       .writefn = tlbi_aa64_alle3is_write },
5700     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5701       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5702       .access = PL3_W, .type = ARM_CP_NO_RAW,
5703       .writefn = tlbi_aa64_vae3is_write },
5704     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5705       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5706       .access = PL3_W, .type = ARM_CP_NO_RAW,
5707       .writefn = tlbi_aa64_vae3is_write },
5708     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5709       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5710       .access = PL3_W, .type = ARM_CP_NO_RAW,
5711       .writefn = tlbi_aa64_alle3_write },
5712     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5713       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5714       .access = PL3_W, .type = ARM_CP_NO_RAW,
5715       .writefn = tlbi_aa64_vae3_write },
5716     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5717       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5718       .access = PL3_W, .type = ARM_CP_NO_RAW,
5719       .writefn = tlbi_aa64_vae3_write },
5720 };
5721 
5722 #ifndef CONFIG_USER_ONLY
5723 /* Test if system register redirection is to occur in the current state.  */
5724 static bool redirect_for_e2h(CPUARMState *env)
5725 {
5726     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5727 }
5728 
5729 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5730 {
5731     CPReadFn *readfn;
5732 
5733     if (redirect_for_e2h(env)) {
5734         /* Switch to the saved EL2 version of the register.  */
5735         ri = ri->opaque;
5736         readfn = ri->readfn;
5737     } else {
5738         readfn = ri->orig_readfn;
5739     }
5740     if (readfn == NULL) {
5741         readfn = raw_read;
5742     }
5743     return readfn(env, ri);
5744 }
5745 
5746 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5747                           uint64_t value)
5748 {
5749     CPWriteFn *writefn;
5750 
5751     if (redirect_for_e2h(env)) {
5752         /* Switch to the saved EL2 version of the register.  */
5753         ri = ri->opaque;
5754         writefn = ri->writefn;
5755     } else {
5756         writefn = ri->orig_writefn;
5757     }
5758     if (writefn == NULL) {
5759         writefn = raw_write;
5760     }
5761     writefn(env, ri, value);
5762 }
5763 
5764 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5765 {
5766     struct E2HAlias {
5767         uint32_t src_key, dst_key, new_key;
5768         const char *src_name, *dst_name, *new_name;
5769         bool (*feature)(const ARMISARegisters *id);
5770     };
5771 
5772 #define K(op0, op1, crn, crm, op2) \
5773     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5774 
5775     static const struct E2HAlias aliases[] = {
5776         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5777           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5778         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5779           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5780         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5781           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5782         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5783           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5784         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5785           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5786         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5787           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5788         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5789           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5790         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5791           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5792         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5793           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5794         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5795           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5796         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5797           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5798         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5799           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5800         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5801           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5802         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5803           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5804         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
5805           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
5806         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
5807           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
5808 
5809         /*
5810          * Note that redirection of ZCR is mentioned in the description
5811          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
5812          * not in the summary table.
5813          */
5814         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
5815           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
5816 
5817         { K(3, 0,  5, 6, 0), K(3, 4,  5, 6, 0), K(3, 5, 5, 6, 0),
5818           "TFSR_EL1", "TFSR_EL2", "TFSR_EL12", isar_feature_aa64_mte },
5819 
5820         { K(3, 0, 13, 0, 7), K(3, 4, 13, 0, 7), K(3, 5, 13, 0, 7),
5821           "SCXTNUM_EL1", "SCXTNUM_EL2", "SCXTNUM_EL12",
5822           isar_feature_aa64_scxtnum },
5823 
5824         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
5825         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
5826     };
5827 #undef K
5828 
5829     size_t i;
5830 
5831     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
5832         const struct E2HAlias *a = &aliases[i];
5833         ARMCPRegInfo *src_reg, *dst_reg, *new_reg;
5834         bool ok;
5835 
5836         if (a->feature && !a->feature(&cpu->isar)) {
5837             continue;
5838         }
5839 
5840         src_reg = g_hash_table_lookup(cpu->cp_regs,
5841                                       (gpointer)(uintptr_t)a->src_key);
5842         dst_reg = g_hash_table_lookup(cpu->cp_regs,
5843                                       (gpointer)(uintptr_t)a->dst_key);
5844         g_assert(src_reg != NULL);
5845         g_assert(dst_reg != NULL);
5846 
5847         /* Cross-compare names to detect typos in the keys.  */
5848         g_assert(strcmp(src_reg->name, a->src_name) == 0);
5849         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
5850 
5851         /* None of the core system registers use opaque; we will.  */
5852         g_assert(src_reg->opaque == NULL);
5853 
5854         /* Create alias before redirection so we dup the right data. */
5855         new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
5856 
5857         new_reg->name = a->new_name;
5858         new_reg->type |= ARM_CP_ALIAS;
5859         /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
5860         new_reg->access &= PL2_RW | PL3_RW;
5861 
5862         ok = g_hash_table_insert(cpu->cp_regs,
5863                                  (gpointer)(uintptr_t)a->new_key, new_reg);
5864         g_assert(ok);
5865 
5866         src_reg->opaque = dst_reg;
5867         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
5868         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
5869         if (!src_reg->raw_readfn) {
5870             src_reg->raw_readfn = raw_read;
5871         }
5872         if (!src_reg->raw_writefn) {
5873             src_reg->raw_writefn = raw_write;
5874         }
5875         src_reg->readfn = el2_e2h_read;
5876         src_reg->writefn = el2_e2h_write;
5877     }
5878 }
5879 #endif
5880 
5881 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5882                                      bool isread)
5883 {
5884     int cur_el = arm_current_el(env);
5885 
5886     if (cur_el < 2) {
5887         uint64_t hcr = arm_hcr_el2_eff(env);
5888 
5889         if (cur_el == 0) {
5890             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
5891                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
5892                     return CP_ACCESS_TRAP_EL2;
5893                 }
5894             } else {
5895                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5896                     return CP_ACCESS_TRAP;
5897                 }
5898                 if (hcr & HCR_TID2) {
5899                     return CP_ACCESS_TRAP_EL2;
5900                 }
5901             }
5902         } else if (hcr & HCR_TID2) {
5903             return CP_ACCESS_TRAP_EL2;
5904         }
5905     }
5906 
5907     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
5908         return CP_ACCESS_TRAP_EL2;
5909     }
5910 
5911     return CP_ACCESS_OK;
5912 }
5913 
5914 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5915                         uint64_t value)
5916 {
5917     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5918      * read via a bit in OSLSR_EL1.
5919      */
5920     int oslock;
5921 
5922     if (ri->state == ARM_CP_STATE_AA32) {
5923         oslock = (value == 0xC5ACCE55);
5924     } else {
5925         oslock = value & 1;
5926     }
5927 
5928     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5929 }
5930 
5931 static const ARMCPRegInfo debug_cp_reginfo[] = {
5932     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5933      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5934      * unlike DBGDRAR it is never accessible from EL0.
5935      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5936      * accessor.
5937      */
5938     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5939       .access = PL0_R, .accessfn = access_tdra,
5940       .type = ARM_CP_CONST, .resetvalue = 0 },
5941     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5942       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5943       .access = PL1_R, .accessfn = access_tdra,
5944       .type = ARM_CP_CONST, .resetvalue = 0 },
5945     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5946       .access = PL0_R, .accessfn = access_tdra,
5947       .type = ARM_CP_CONST, .resetvalue = 0 },
5948     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5949     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5950       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5951       .access = PL1_RW, .accessfn = access_tda,
5952       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5953       .resetvalue = 0 },
5954     /*
5955      * MDCCSR_EL0[30:29] map to EDSCR[30:29].  Simply RAZ as the external
5956      * Debug Communication Channel is not implemented.
5957      */
5958     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_AA64,
5959       .opc0 = 2, .opc1 = 3, .crn = 0, .crm = 1, .opc2 = 0,
5960       .access = PL0_R, .accessfn = access_tda,
5961       .type = ARM_CP_CONST, .resetvalue = 0 },
5962     /*
5963      * DBGDSCRint[15,12,5:2] map to MDSCR_EL1[15,12,5:2].  Map all bits as
5964      * it is unlikely a guest will care.
5965      * We don't implement the configurable EL0 access.
5966      */
5967     { .name = "DBGDSCRint", .state = ARM_CP_STATE_AA32,
5968       .cp = 14, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5969       .type = ARM_CP_ALIAS,
5970       .access = PL1_R, .accessfn = access_tda,
5971       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
5972     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
5973       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
5974       .access = PL1_W, .type = ARM_CP_NO_RAW,
5975       .accessfn = access_tdosa,
5976       .writefn = oslar_write },
5977     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
5978       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
5979       .access = PL1_R, .resetvalue = 10,
5980       .accessfn = access_tdosa,
5981       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
5982     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
5983     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
5984       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
5985       .access = PL1_RW, .accessfn = access_tdosa,
5986       .type = ARM_CP_NOP },
5987     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
5988      * implement vector catch debug events yet.
5989      */
5990     { .name = "DBGVCR",
5991       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5992       .access = PL1_RW, .accessfn = access_tda,
5993       .type = ARM_CP_NOP },
5994     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
5995      * to save and restore a 32-bit guest's DBGVCR)
5996      */
5997     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
5998       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
5999       .access = PL2_RW, .accessfn = access_tda,
6000       .type = ARM_CP_NOP | ARM_CP_EL3_NO_EL2_KEEP },
6001     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6002      * Channel but Linux may try to access this register. The 32-bit
6003      * alias is DBGDCCINT.
6004      */
6005     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6006       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6007       .access = PL1_RW, .accessfn = access_tda,
6008       .type = ARM_CP_NOP },
6009 };
6010 
6011 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6012     /* 64 bit access versions of the (dummy) debug registers */
6013     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6014       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6015     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6016       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6017 };
6018 
6019 /*
6020  * Check for traps to RAS registers, which are controlled
6021  * by HCR_EL2.TERR and SCR_EL3.TERR.
6022  */
6023 static CPAccessResult access_terr(CPUARMState *env, const ARMCPRegInfo *ri,
6024                                   bool isread)
6025 {
6026     int el = arm_current_el(env);
6027 
6028     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TERR)) {
6029         return CP_ACCESS_TRAP_EL2;
6030     }
6031     if (el < 3 && (env->cp15.scr_el3 & SCR_TERR)) {
6032         return CP_ACCESS_TRAP_EL3;
6033     }
6034     return CP_ACCESS_OK;
6035 }
6036 
6037 static uint64_t disr_read(CPUARMState *env, const ARMCPRegInfo *ri)
6038 {
6039     int el = arm_current_el(env);
6040 
6041     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_AMO)) {
6042         return env->cp15.vdisr_el2;
6043     }
6044     if (el < 3 && (env->cp15.scr_el3 & SCR_EA)) {
6045         return 0; /* RAZ/WI */
6046     }
6047     return env->cp15.disr_el1;
6048 }
6049 
6050 static void disr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
6051 {
6052     int el = arm_current_el(env);
6053 
6054     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_AMO)) {
6055         env->cp15.vdisr_el2 = val;
6056         return;
6057     }
6058     if (el < 3 && (env->cp15.scr_el3 & SCR_EA)) {
6059         return; /* RAZ/WI */
6060     }
6061     env->cp15.disr_el1 = val;
6062 }
6063 
6064 /*
6065  * Minimal RAS implementation with no Error Records.
6066  * Which means that all of the Error Record registers:
6067  *   ERXADDR_EL1
6068  *   ERXCTLR_EL1
6069  *   ERXFR_EL1
6070  *   ERXMISC0_EL1
6071  *   ERXMISC1_EL1
6072  *   ERXMISC2_EL1
6073  *   ERXMISC3_EL1
6074  *   ERXPFGCDN_EL1  (RASv1p1)
6075  *   ERXPFGCTL_EL1  (RASv1p1)
6076  *   ERXPFGF_EL1    (RASv1p1)
6077  *   ERXSTATUS_EL1
6078  * and
6079  *   ERRSELR_EL1
6080  * may generate UNDEFINED, which is the effect we get by not
6081  * listing them at all.
6082  */
6083 static const ARMCPRegInfo minimal_ras_reginfo[] = {
6084     { .name = "DISR_EL1", .state = ARM_CP_STATE_BOTH,
6085       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 1,
6086       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.disr_el1),
6087       .readfn = disr_read, .writefn = disr_write, .raw_writefn = raw_write },
6088     { .name = "ERRIDR_EL1", .state = ARM_CP_STATE_BOTH,
6089       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 3, .opc2 = 0,
6090       .access = PL1_R, .accessfn = access_terr,
6091       .type = ARM_CP_CONST, .resetvalue = 0 },
6092     { .name = "VDISR_EL2", .state = ARM_CP_STATE_BOTH,
6093       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 1, .opc2 = 1,
6094       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.vdisr_el2) },
6095     { .name = "VSESR_EL2", .state = ARM_CP_STATE_BOTH,
6096       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 3,
6097       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.vsesr_el2) },
6098 };
6099 
6100 /* Return the exception level to which exceptions should be taken
6101  * via SVEAccessTrap.  If an exception should be routed through
6102  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6103  * take care of raising that exception.
6104  * C.f. the ARM pseudocode function CheckSVEEnabled.
6105  */
6106 int sve_exception_el(CPUARMState *env, int el)
6107 {
6108 #ifndef CONFIG_USER_ONLY
6109     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6110 
6111     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6112         /* Check CPACR.ZEN.  */
6113         switch (extract32(env->cp15.cpacr_el1, 16, 2)) {
6114         case 1:
6115             if (el != 0) {
6116                 break;
6117             }
6118             /* fall through */
6119         case 0:
6120         case 2:
6121             /* route_to_el2 */
6122             return hcr_el2 & HCR_TGE ? 2 : 1;
6123         }
6124 
6125         /* Check CPACR.FPEN.  */
6126         switch (extract32(env->cp15.cpacr_el1, 20, 2)) {
6127         case 1:
6128             if (el != 0) {
6129                 break;
6130             }
6131             /* fall through */
6132         case 0:
6133         case 2:
6134             return 0;
6135         }
6136     }
6137 
6138     /*
6139      * CPTR_EL2 changes format with HCR_EL2.E2H (regardless of TGE).
6140      */
6141     if (el <= 2) {
6142         if (hcr_el2 & HCR_E2H) {
6143             /* Check CPTR_EL2.ZEN.  */
6144             switch (extract32(env->cp15.cptr_el[2], 16, 2)) {
6145             case 1:
6146                 if (el != 0 || !(hcr_el2 & HCR_TGE)) {
6147                     break;
6148                 }
6149                 /* fall through */
6150             case 0:
6151             case 2:
6152                 return 2;
6153             }
6154 
6155             /* Check CPTR_EL2.FPEN.  */
6156             switch (extract32(env->cp15.cptr_el[2], 20, 2)) {
6157             case 1:
6158                 if (el == 2 || !(hcr_el2 & HCR_TGE)) {
6159                     break;
6160                 }
6161                 /* fall through */
6162             case 0:
6163             case 2:
6164                 return 0;
6165             }
6166         } else if (arm_is_el2_enabled(env)) {
6167             if (env->cp15.cptr_el[2] & CPTR_TZ) {
6168                 return 2;
6169             }
6170             if (env->cp15.cptr_el[2] & CPTR_TFP) {
6171                 return 0;
6172             }
6173         }
6174     }
6175 
6176     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6177     if (arm_feature(env, ARM_FEATURE_EL3)
6178         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6179         return 3;
6180     }
6181 #endif
6182     return 0;
6183 }
6184 
6185 uint32_t aarch64_sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6186 {
6187     uint32_t end_len;
6188 
6189     start_len = MIN(start_len, ARM_MAX_VQ - 1);
6190     end_len = start_len;
6191 
6192     if (!test_bit(start_len, cpu->sve_vq_map)) {
6193         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6194         assert(end_len < start_len);
6195     }
6196     return end_len;
6197 }
6198 
6199 /*
6200  * Given that SVE is enabled, return the vector length for EL.
6201  */
6202 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6203 {
6204     ARMCPU *cpu = env_archcpu(env);
6205     uint32_t zcr_len = cpu->sve_max_vq - 1;
6206 
6207     if (el <= 1 &&
6208         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6209         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6210     }
6211     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6212         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6213     }
6214     if (arm_feature(env, ARM_FEATURE_EL3)) {
6215         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6216     }
6217 
6218     return aarch64_sve_zcr_get_valid_len(cpu, zcr_len);
6219 }
6220 
6221 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6222                       uint64_t value)
6223 {
6224     int cur_el = arm_current_el(env);
6225     int old_len = sve_zcr_len_for_el(env, cur_el);
6226     int new_len;
6227 
6228     /* Bits other than [3:0] are RAZ/WI.  */
6229     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6230     raw_write(env, ri, value & 0xf);
6231 
6232     /*
6233      * Because we arrived here, we know both FP and SVE are enabled;
6234      * otherwise we would have trapped access to the ZCR_ELn register.
6235      */
6236     new_len = sve_zcr_len_for_el(env, cur_el);
6237     if (new_len < old_len) {
6238         aarch64_sve_narrow_vq(env, new_len + 1);
6239     }
6240 }
6241 
6242 static const ARMCPRegInfo zcr_reginfo[] = {
6243     { .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6244       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6245       .access = PL1_RW, .type = ARM_CP_SVE,
6246       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6247       .writefn = zcr_write, .raw_writefn = raw_write },
6248     { .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6249       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6250       .access = PL2_RW, .type = ARM_CP_SVE,
6251       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6252       .writefn = zcr_write, .raw_writefn = raw_write },
6253     { .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6254       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6255       .access = PL3_RW, .type = ARM_CP_SVE,
6256       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6257       .writefn = zcr_write, .raw_writefn = raw_write },
6258 };
6259 
6260 void hw_watchpoint_update(ARMCPU *cpu, int n)
6261 {
6262     CPUARMState *env = &cpu->env;
6263     vaddr len = 0;
6264     vaddr wvr = env->cp15.dbgwvr[n];
6265     uint64_t wcr = env->cp15.dbgwcr[n];
6266     int mask;
6267     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6268 
6269     if (env->cpu_watchpoint[n]) {
6270         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6271         env->cpu_watchpoint[n] = NULL;
6272     }
6273 
6274     if (!FIELD_EX64(wcr, DBGWCR, E)) {
6275         /* E bit clear : watchpoint disabled */
6276         return;
6277     }
6278 
6279     switch (FIELD_EX64(wcr, DBGWCR, LSC)) {
6280     case 0:
6281         /* LSC 00 is reserved and must behave as if the wp is disabled */
6282         return;
6283     case 1:
6284         flags |= BP_MEM_READ;
6285         break;
6286     case 2:
6287         flags |= BP_MEM_WRITE;
6288         break;
6289     case 3:
6290         flags |= BP_MEM_ACCESS;
6291         break;
6292     }
6293 
6294     /* Attempts to use both MASK and BAS fields simultaneously are
6295      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6296      * thus generating a watchpoint for every byte in the masked region.
6297      */
6298     mask = FIELD_EX64(wcr, DBGWCR, MASK);
6299     if (mask == 1 || mask == 2) {
6300         /* Reserved values of MASK; we must act as if the mask value was
6301          * some non-reserved value, or as if the watchpoint were disabled.
6302          * We choose the latter.
6303          */
6304         return;
6305     } else if (mask) {
6306         /* Watchpoint covers an aligned area up to 2GB in size */
6307         len = 1ULL << mask;
6308         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6309          * whether the watchpoint fires when the unmasked bits match; we opt
6310          * to generate the exceptions.
6311          */
6312         wvr &= ~(len - 1);
6313     } else {
6314         /* Watchpoint covers bytes defined by the byte address select bits */
6315         int bas = FIELD_EX64(wcr, DBGWCR, BAS);
6316         int basstart;
6317 
6318         if (extract64(wvr, 2, 1)) {
6319             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6320              * ignored, and BAS[3:0] define which bytes to watch.
6321              */
6322             bas &= 0xf;
6323         }
6324 
6325         if (bas == 0) {
6326             /* This must act as if the watchpoint is disabled */
6327             return;
6328         }
6329 
6330         /* The BAS bits are supposed to be programmed to indicate a contiguous
6331          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6332          * we fire for each byte in the word/doubleword addressed by the WVR.
6333          * We choose to ignore any non-zero bits after the first range of 1s.
6334          */
6335         basstart = ctz32(bas);
6336         len = cto32(bas >> basstart);
6337         wvr += basstart;
6338     }
6339 
6340     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6341                           &env->cpu_watchpoint[n]);
6342 }
6343 
6344 void hw_watchpoint_update_all(ARMCPU *cpu)
6345 {
6346     int i;
6347     CPUARMState *env = &cpu->env;
6348 
6349     /* Completely clear out existing QEMU watchpoints and our array, to
6350      * avoid possible stale entries following migration load.
6351      */
6352     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6353     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6354 
6355     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6356         hw_watchpoint_update(cpu, i);
6357     }
6358 }
6359 
6360 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6361                          uint64_t value)
6362 {
6363     ARMCPU *cpu = env_archcpu(env);
6364     int i = ri->crm;
6365 
6366     /*
6367      * Bits [1:0] are RES0.
6368      *
6369      * It is IMPLEMENTATION DEFINED whether [63:49] ([63:53] with FEAT_LVA)
6370      * are hardwired to the value of bit [48] ([52] with FEAT_LVA), or if
6371      * they contain the value written.  It is CONSTRAINED UNPREDICTABLE
6372      * whether the RESS bits are ignored when comparing an address.
6373      *
6374      * Therefore we are allowed to compare the entire register, which lets
6375      * us avoid considering whether or not FEAT_LVA is actually enabled.
6376      */
6377     value &= ~3ULL;
6378 
6379     raw_write(env, ri, value);
6380     hw_watchpoint_update(cpu, i);
6381 }
6382 
6383 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6384                          uint64_t value)
6385 {
6386     ARMCPU *cpu = env_archcpu(env);
6387     int i = ri->crm;
6388 
6389     raw_write(env, ri, value);
6390     hw_watchpoint_update(cpu, i);
6391 }
6392 
6393 void hw_breakpoint_update(ARMCPU *cpu, int n)
6394 {
6395     CPUARMState *env = &cpu->env;
6396     uint64_t bvr = env->cp15.dbgbvr[n];
6397     uint64_t bcr = env->cp15.dbgbcr[n];
6398     vaddr addr;
6399     int bt;
6400     int flags = BP_CPU;
6401 
6402     if (env->cpu_breakpoint[n]) {
6403         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6404         env->cpu_breakpoint[n] = NULL;
6405     }
6406 
6407     if (!extract64(bcr, 0, 1)) {
6408         /* E bit clear : watchpoint disabled */
6409         return;
6410     }
6411 
6412     bt = extract64(bcr, 20, 4);
6413 
6414     switch (bt) {
6415     case 4: /* unlinked address mismatch (reserved if AArch64) */
6416     case 5: /* linked address mismatch (reserved if AArch64) */
6417         qemu_log_mask(LOG_UNIMP,
6418                       "arm: address mismatch breakpoint types not implemented\n");
6419         return;
6420     case 0: /* unlinked address match */
6421     case 1: /* linked address match */
6422     {
6423         /*
6424          * Bits [1:0] are RES0.
6425          *
6426          * It is IMPLEMENTATION DEFINED whether bits [63:49]
6427          * ([63:53] for FEAT_LVA) are hardwired to a copy of the sign bit
6428          * of the VA field ([48] or [52] for FEAT_LVA), or whether the
6429          * value is read as written.  It is CONSTRAINED UNPREDICTABLE
6430          * whether the RESS bits are ignored when comparing an address.
6431          * Therefore we are allowed to compare the entire register, which
6432          * lets us avoid considering whether FEAT_LVA is actually enabled.
6433          *
6434          * The BAS field is used to allow setting breakpoints on 16-bit
6435          * wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6436          * a bp will fire if the addresses covered by the bp and the addresses
6437          * covered by the insn overlap but the insn doesn't start at the
6438          * start of the bp address range. We choose to require the insn and
6439          * the bp to have the same address. The constraints on writing to
6440          * BAS enforced in dbgbcr_write mean we have only four cases:
6441          *  0b0000  => no breakpoint
6442          *  0b0011  => breakpoint on addr
6443          *  0b1100  => breakpoint on addr + 2
6444          *  0b1111  => breakpoint on addr
6445          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6446          */
6447         int bas = extract64(bcr, 5, 4);
6448         addr = bvr & ~3ULL;
6449         if (bas == 0) {
6450             return;
6451         }
6452         if (bas == 0xc) {
6453             addr += 2;
6454         }
6455         break;
6456     }
6457     case 2: /* unlinked context ID match */
6458     case 8: /* unlinked VMID match (reserved if no EL2) */
6459     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6460         qemu_log_mask(LOG_UNIMP,
6461                       "arm: unlinked context breakpoint types not implemented\n");
6462         return;
6463     case 9: /* linked VMID match (reserved if no EL2) */
6464     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6465     case 3: /* linked context ID match */
6466     default:
6467         /* We must generate no events for Linked context matches (unless
6468          * they are linked to by some other bp/wp, which is handled in
6469          * updates for the linking bp/wp). We choose to also generate no events
6470          * for reserved values.
6471          */
6472         return;
6473     }
6474 
6475     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6476 }
6477 
6478 void hw_breakpoint_update_all(ARMCPU *cpu)
6479 {
6480     int i;
6481     CPUARMState *env = &cpu->env;
6482 
6483     /* Completely clear out existing QEMU breakpoints and our array, to
6484      * avoid possible stale entries following migration load.
6485      */
6486     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6487     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6488 
6489     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6490         hw_breakpoint_update(cpu, i);
6491     }
6492 }
6493 
6494 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6495                          uint64_t value)
6496 {
6497     ARMCPU *cpu = env_archcpu(env);
6498     int i = ri->crm;
6499 
6500     raw_write(env, ri, value);
6501     hw_breakpoint_update(cpu, i);
6502 }
6503 
6504 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6505                          uint64_t value)
6506 {
6507     ARMCPU *cpu = env_archcpu(env);
6508     int i = ri->crm;
6509 
6510     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6511      * copy of BAS[0].
6512      */
6513     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6514     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6515 
6516     raw_write(env, ri, value);
6517     hw_breakpoint_update(cpu, i);
6518 }
6519 
6520 static void define_debug_regs(ARMCPU *cpu)
6521 {
6522     /* Define v7 and v8 architectural debug registers.
6523      * These are just dummy implementations for now.
6524      */
6525     int i;
6526     int wrps, brps, ctx_cmps;
6527 
6528     /*
6529      * The Arm ARM says DBGDIDR is optional and deprecated if EL1 cannot
6530      * use AArch32.  Given that bit 15 is RES1, if the value is 0 then
6531      * the register must not exist for this cpu.
6532      */
6533     if (cpu->isar.dbgdidr != 0) {
6534         ARMCPRegInfo dbgdidr = {
6535             .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0,
6536             .opc1 = 0, .opc2 = 0,
6537             .access = PL0_R, .accessfn = access_tda,
6538             .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6539         };
6540         define_one_arm_cp_reg(cpu, &dbgdidr);
6541     }
6542 
6543     /* Note that all these register fields hold "number of Xs minus 1". */
6544     brps = arm_num_brps(cpu);
6545     wrps = arm_num_wrps(cpu);
6546     ctx_cmps = arm_num_ctx_cmps(cpu);
6547 
6548     assert(ctx_cmps <= brps);
6549 
6550     define_arm_cp_regs(cpu, debug_cp_reginfo);
6551 
6552     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6553         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6554     }
6555 
6556     for (i = 0; i < brps; i++) {
6557         char *dbgbvr_el1_name = g_strdup_printf("DBGBVR%d_EL1", i);
6558         char *dbgbcr_el1_name = g_strdup_printf("DBGBCR%d_EL1", i);
6559         ARMCPRegInfo dbgregs[] = {
6560             { .name = dbgbvr_el1_name, .state = ARM_CP_STATE_BOTH,
6561               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6562               .access = PL1_RW, .accessfn = access_tda,
6563               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6564               .writefn = dbgbvr_write, .raw_writefn = raw_write
6565             },
6566             { .name = dbgbcr_el1_name, .state = ARM_CP_STATE_BOTH,
6567               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6568               .access = PL1_RW, .accessfn = access_tda,
6569               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6570               .writefn = dbgbcr_write, .raw_writefn = raw_write
6571             },
6572         };
6573         define_arm_cp_regs(cpu, dbgregs);
6574         g_free(dbgbvr_el1_name);
6575         g_free(dbgbcr_el1_name);
6576     }
6577 
6578     for (i = 0; i < wrps; i++) {
6579         char *dbgwvr_el1_name = g_strdup_printf("DBGWVR%d_EL1", i);
6580         char *dbgwcr_el1_name = g_strdup_printf("DBGWCR%d_EL1", i);
6581         ARMCPRegInfo dbgregs[] = {
6582             { .name = dbgwvr_el1_name, .state = ARM_CP_STATE_BOTH,
6583               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6584               .access = PL1_RW, .accessfn = access_tda,
6585               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6586               .writefn = dbgwvr_write, .raw_writefn = raw_write
6587             },
6588             { .name = dbgwcr_el1_name, .state = ARM_CP_STATE_BOTH,
6589               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6590               .access = PL1_RW, .accessfn = access_tda,
6591               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6592               .writefn = dbgwcr_write, .raw_writefn = raw_write
6593             },
6594         };
6595         define_arm_cp_regs(cpu, dbgregs);
6596         g_free(dbgwvr_el1_name);
6597         g_free(dbgwcr_el1_name);
6598     }
6599 }
6600 
6601 static void define_pmu_regs(ARMCPU *cpu)
6602 {
6603     /*
6604      * v7 performance monitor control register: same implementor
6605      * field as main ID register, and we implement four counters in
6606      * addition to the cycle count register.
6607      */
6608     unsigned int i, pmcrn = PMCR_NUM_COUNTERS;
6609     ARMCPRegInfo pmcr = {
6610         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6611         .access = PL0_RW,
6612         .type = ARM_CP_IO | ARM_CP_ALIAS,
6613         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6614         .accessfn = pmreg_access, .writefn = pmcr_write,
6615         .raw_writefn = raw_write,
6616     };
6617     ARMCPRegInfo pmcr64 = {
6618         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6619         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6620         .access = PL0_RW, .accessfn = pmreg_access,
6621         .type = ARM_CP_IO,
6622         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6623         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6624                       PMCRLC,
6625         .writefn = pmcr_write, .raw_writefn = raw_write,
6626     };
6627     define_one_arm_cp_reg(cpu, &pmcr);
6628     define_one_arm_cp_reg(cpu, &pmcr64);
6629     for (i = 0; i < pmcrn; i++) {
6630         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6631         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6632         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6633         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6634         ARMCPRegInfo pmev_regs[] = {
6635             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6636               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6637               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6638               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6639               .accessfn = pmreg_access_xevcntr },
6640             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6641               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6642               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access_xevcntr,
6643               .type = ARM_CP_IO,
6644               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6645               .raw_readfn = pmevcntr_rawread,
6646               .raw_writefn = pmevcntr_rawwrite },
6647             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6648               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6649               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6650               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6651               .accessfn = pmreg_access },
6652             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6653               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6654               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6655               .type = ARM_CP_IO,
6656               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6657               .raw_writefn = pmevtyper_rawwrite },
6658         };
6659         define_arm_cp_regs(cpu, pmev_regs);
6660         g_free(pmevcntr_name);
6661         g_free(pmevcntr_el0_name);
6662         g_free(pmevtyper_name);
6663         g_free(pmevtyper_el0_name);
6664     }
6665     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6666         ARMCPRegInfo v81_pmu_regs[] = {
6667             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6668               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6669               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6670               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6671             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6672               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6673               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6674               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6675         };
6676         define_arm_cp_regs(cpu, v81_pmu_regs);
6677     }
6678     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6679         static const ARMCPRegInfo v84_pmmir = {
6680             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6681             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6682             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6683             .resetvalue = 0
6684         };
6685         define_one_arm_cp_reg(cpu, &v84_pmmir);
6686     }
6687 }
6688 
6689 /* We don't know until after realize whether there's a GICv3
6690  * attached, and that is what registers the gicv3 sysregs.
6691  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6692  * at runtime.
6693  */
6694 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6695 {
6696     ARMCPU *cpu = env_archcpu(env);
6697     uint64_t pfr1 = cpu->isar.id_pfr1;
6698 
6699     if (env->gicv3state) {
6700         pfr1 |= 1 << 28;
6701     }
6702     return pfr1;
6703 }
6704 
6705 #ifndef CONFIG_USER_ONLY
6706 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6707 {
6708     ARMCPU *cpu = env_archcpu(env);
6709     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6710 
6711     if (env->gicv3state) {
6712         pfr0 |= 1 << 24;
6713     }
6714     return pfr0;
6715 }
6716 #endif
6717 
6718 /* Shared logic between LORID and the rest of the LOR* registers.
6719  * Secure state exclusion has already been dealt with.
6720  */
6721 static CPAccessResult access_lor_ns(CPUARMState *env,
6722                                     const ARMCPRegInfo *ri, bool isread)
6723 {
6724     int el = arm_current_el(env);
6725 
6726     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6727         return CP_ACCESS_TRAP_EL2;
6728     }
6729     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6730         return CP_ACCESS_TRAP_EL3;
6731     }
6732     return CP_ACCESS_OK;
6733 }
6734 
6735 static CPAccessResult access_lor_other(CPUARMState *env,
6736                                        const ARMCPRegInfo *ri, bool isread)
6737 {
6738     if (arm_is_secure_below_el3(env)) {
6739         /* Access denied in secure mode.  */
6740         return CP_ACCESS_TRAP;
6741     }
6742     return access_lor_ns(env, ri, isread);
6743 }
6744 
6745 /*
6746  * A trivial implementation of ARMv8.1-LOR leaves all of these
6747  * registers fixed at 0, which indicates that there are zero
6748  * supported Limited Ordering regions.
6749  */
6750 static const ARMCPRegInfo lor_reginfo[] = {
6751     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6752       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6753       .access = PL1_RW, .accessfn = access_lor_other,
6754       .type = ARM_CP_CONST, .resetvalue = 0 },
6755     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6756       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6757       .access = PL1_RW, .accessfn = access_lor_other,
6758       .type = ARM_CP_CONST, .resetvalue = 0 },
6759     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6760       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6761       .access = PL1_RW, .accessfn = access_lor_other,
6762       .type = ARM_CP_CONST, .resetvalue = 0 },
6763     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6764       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6765       .access = PL1_RW, .accessfn = access_lor_other,
6766       .type = ARM_CP_CONST, .resetvalue = 0 },
6767     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6768       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6769       .access = PL1_R, .accessfn = access_lor_ns,
6770       .type = ARM_CP_CONST, .resetvalue = 0 },
6771 };
6772 
6773 #ifdef TARGET_AARCH64
6774 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6775                                    bool isread)
6776 {
6777     int el = arm_current_el(env);
6778 
6779     if (el < 2 &&
6780         arm_feature(env, ARM_FEATURE_EL2) &&
6781         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6782         return CP_ACCESS_TRAP_EL2;
6783     }
6784     if (el < 3 &&
6785         arm_feature(env, ARM_FEATURE_EL3) &&
6786         !(env->cp15.scr_el3 & SCR_APK)) {
6787         return CP_ACCESS_TRAP_EL3;
6788     }
6789     return CP_ACCESS_OK;
6790 }
6791 
6792 static const ARMCPRegInfo pauth_reginfo[] = {
6793     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6794       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6795       .access = PL1_RW, .accessfn = access_pauth,
6796       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6797     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6798       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6799       .access = PL1_RW, .accessfn = access_pauth,
6800       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6801     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6802       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6803       .access = PL1_RW, .accessfn = access_pauth,
6804       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6805     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6806       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6807       .access = PL1_RW, .accessfn = access_pauth,
6808       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6809     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6810       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6811       .access = PL1_RW, .accessfn = access_pauth,
6812       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6813     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6814       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6815       .access = PL1_RW, .accessfn = access_pauth,
6816       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6817     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6818       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6819       .access = PL1_RW, .accessfn = access_pauth,
6820       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6821     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6822       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6823       .access = PL1_RW, .accessfn = access_pauth,
6824       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6825     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6826       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6827       .access = PL1_RW, .accessfn = access_pauth,
6828       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6829     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6830       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6831       .access = PL1_RW, .accessfn = access_pauth,
6832       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6833 };
6834 
6835 static const ARMCPRegInfo tlbirange_reginfo[] = {
6836     { .name = "TLBI_RVAE1IS", .state = ARM_CP_STATE_AA64,
6837       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 1,
6838       .access = PL1_W, .type = ARM_CP_NO_RAW,
6839       .writefn = tlbi_aa64_rvae1is_write },
6840     { .name = "TLBI_RVAAE1IS", .state = ARM_CP_STATE_AA64,
6841       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 3,
6842       .access = PL1_W, .type = ARM_CP_NO_RAW,
6843       .writefn = tlbi_aa64_rvae1is_write },
6844    { .name = "TLBI_RVALE1IS", .state = ARM_CP_STATE_AA64,
6845       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 5,
6846       .access = PL1_W, .type = ARM_CP_NO_RAW,
6847       .writefn = tlbi_aa64_rvae1is_write },
6848     { .name = "TLBI_RVAALE1IS", .state = ARM_CP_STATE_AA64,
6849       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 7,
6850       .access = PL1_W, .type = ARM_CP_NO_RAW,
6851       .writefn = tlbi_aa64_rvae1is_write },
6852     { .name = "TLBI_RVAE1OS", .state = ARM_CP_STATE_AA64,
6853       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
6854       .access = PL1_W, .type = ARM_CP_NO_RAW,
6855       .writefn = tlbi_aa64_rvae1is_write },
6856     { .name = "TLBI_RVAAE1OS", .state = ARM_CP_STATE_AA64,
6857       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 3,
6858       .access = PL1_W, .type = ARM_CP_NO_RAW,
6859       .writefn = tlbi_aa64_rvae1is_write },
6860    { .name = "TLBI_RVALE1OS", .state = ARM_CP_STATE_AA64,
6861       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 5,
6862       .access = PL1_W, .type = ARM_CP_NO_RAW,
6863       .writefn = tlbi_aa64_rvae1is_write },
6864     { .name = "TLBI_RVAALE1OS", .state = ARM_CP_STATE_AA64,
6865       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 7,
6866       .access = PL1_W, .type = ARM_CP_NO_RAW,
6867       .writefn = tlbi_aa64_rvae1is_write },
6868     { .name = "TLBI_RVAE1", .state = ARM_CP_STATE_AA64,
6869       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
6870       .access = PL1_W, .type = ARM_CP_NO_RAW,
6871       .writefn = tlbi_aa64_rvae1_write },
6872     { .name = "TLBI_RVAAE1", .state = ARM_CP_STATE_AA64,
6873       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 3,
6874       .access = PL1_W, .type = ARM_CP_NO_RAW,
6875       .writefn = tlbi_aa64_rvae1_write },
6876    { .name = "TLBI_RVALE1", .state = ARM_CP_STATE_AA64,
6877       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 5,
6878       .access = PL1_W, .type = ARM_CP_NO_RAW,
6879       .writefn = tlbi_aa64_rvae1_write },
6880     { .name = "TLBI_RVAALE1", .state = ARM_CP_STATE_AA64,
6881       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 7,
6882       .access = PL1_W, .type = ARM_CP_NO_RAW,
6883       .writefn = tlbi_aa64_rvae1_write },
6884     { .name = "TLBI_RIPAS2E1IS", .state = ARM_CP_STATE_AA64,
6885       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 2,
6886       .access = PL2_W, .type = ARM_CP_NOP },
6887     { .name = "TLBI_RIPAS2LE1IS", .state = ARM_CP_STATE_AA64,
6888       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 6,
6889       .access = PL2_W, .type = ARM_CP_NOP },
6890     { .name = "TLBI_RVAE2IS", .state = ARM_CP_STATE_AA64,
6891       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 1,
6892       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6893       .writefn = tlbi_aa64_rvae2is_write },
6894    { .name = "TLBI_RVALE2IS", .state = ARM_CP_STATE_AA64,
6895       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 5,
6896       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6897       .writefn = tlbi_aa64_rvae2is_write },
6898     { .name = "TLBI_RIPAS2E1", .state = ARM_CP_STATE_AA64,
6899       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 2,
6900       .access = PL2_W, .type = ARM_CP_NOP },
6901    { .name = "TLBI_RIPAS2LE1", .state = ARM_CP_STATE_AA64,
6902       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 6,
6903       .access = PL2_W, .type = ARM_CP_NOP },
6904    { .name = "TLBI_RVAE2OS", .state = ARM_CP_STATE_AA64,
6905       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 1,
6906       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6907       .writefn = tlbi_aa64_rvae2is_write },
6908    { .name = "TLBI_RVALE2OS", .state = ARM_CP_STATE_AA64,
6909       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 5,
6910       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6911       .writefn = tlbi_aa64_rvae2is_write },
6912     { .name = "TLBI_RVAE2", .state = ARM_CP_STATE_AA64,
6913       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 1,
6914       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6915       .writefn = tlbi_aa64_rvae2_write },
6916    { .name = "TLBI_RVALE2", .state = ARM_CP_STATE_AA64,
6917       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 5,
6918       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6919       .writefn = tlbi_aa64_rvae2_write },
6920    { .name = "TLBI_RVAE3IS", .state = ARM_CP_STATE_AA64,
6921       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 1,
6922       .access = PL3_W, .type = ARM_CP_NO_RAW,
6923       .writefn = tlbi_aa64_rvae3is_write },
6924    { .name = "TLBI_RVALE3IS", .state = ARM_CP_STATE_AA64,
6925       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 5,
6926       .access = PL3_W, .type = ARM_CP_NO_RAW,
6927       .writefn = tlbi_aa64_rvae3is_write },
6928    { .name = "TLBI_RVAE3OS", .state = ARM_CP_STATE_AA64,
6929       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 1,
6930       .access = PL3_W, .type = ARM_CP_NO_RAW,
6931       .writefn = tlbi_aa64_rvae3is_write },
6932    { .name = "TLBI_RVALE3OS", .state = ARM_CP_STATE_AA64,
6933       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 5,
6934       .access = PL3_W, .type = ARM_CP_NO_RAW,
6935       .writefn = tlbi_aa64_rvae3is_write },
6936    { .name = "TLBI_RVAE3", .state = ARM_CP_STATE_AA64,
6937       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 1,
6938       .access = PL3_W, .type = ARM_CP_NO_RAW,
6939       .writefn = tlbi_aa64_rvae3_write },
6940    { .name = "TLBI_RVALE3", .state = ARM_CP_STATE_AA64,
6941       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 5,
6942       .access = PL3_W, .type = ARM_CP_NO_RAW,
6943       .writefn = tlbi_aa64_rvae3_write },
6944 };
6945 
6946 static const ARMCPRegInfo tlbios_reginfo[] = {
6947     { .name = "TLBI_VMALLE1OS", .state = ARM_CP_STATE_AA64,
6948       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 0,
6949       .access = PL1_W, .type = ARM_CP_NO_RAW,
6950       .writefn = tlbi_aa64_vmalle1is_write },
6951     { .name = "TLBI_VAE1OS", .state = ARM_CP_STATE_AA64,
6952       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 1,
6953       .access = PL1_W, .type = ARM_CP_NO_RAW,
6954       .writefn = tlbi_aa64_vae1is_write },
6955     { .name = "TLBI_ASIDE1OS", .state = ARM_CP_STATE_AA64,
6956       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 2,
6957       .access = PL1_W, .type = ARM_CP_NO_RAW,
6958       .writefn = tlbi_aa64_vmalle1is_write },
6959     { .name = "TLBI_VAAE1OS", .state = ARM_CP_STATE_AA64,
6960       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 3,
6961       .access = PL1_W, .type = ARM_CP_NO_RAW,
6962       .writefn = tlbi_aa64_vae1is_write },
6963     { .name = "TLBI_VALE1OS", .state = ARM_CP_STATE_AA64,
6964       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 5,
6965       .access = PL1_W, .type = ARM_CP_NO_RAW,
6966       .writefn = tlbi_aa64_vae1is_write },
6967     { .name = "TLBI_VAALE1OS", .state = ARM_CP_STATE_AA64,
6968       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 7,
6969       .access = PL1_W, .type = ARM_CP_NO_RAW,
6970       .writefn = tlbi_aa64_vae1is_write },
6971     { .name = "TLBI_ALLE2OS", .state = ARM_CP_STATE_AA64,
6972       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 0,
6973       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6974       .writefn = tlbi_aa64_alle2is_write },
6975     { .name = "TLBI_VAE2OS", .state = ARM_CP_STATE_AA64,
6976       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 1,
6977       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6978       .writefn = tlbi_aa64_vae2is_write },
6979    { .name = "TLBI_ALLE1OS", .state = ARM_CP_STATE_AA64,
6980       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 4,
6981       .access = PL2_W, .type = ARM_CP_NO_RAW,
6982       .writefn = tlbi_aa64_alle1is_write },
6983     { .name = "TLBI_VALE2OS", .state = ARM_CP_STATE_AA64,
6984       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 5,
6985       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6986       .writefn = tlbi_aa64_vae2is_write },
6987     { .name = "TLBI_VMALLS12E1OS", .state = ARM_CP_STATE_AA64,
6988       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 6,
6989       .access = PL2_W, .type = ARM_CP_NO_RAW,
6990       .writefn = tlbi_aa64_alle1is_write },
6991     { .name = "TLBI_IPAS2E1OS", .state = ARM_CP_STATE_AA64,
6992       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 0,
6993       .access = PL2_W, .type = ARM_CP_NOP },
6994     { .name = "TLBI_RIPAS2E1OS", .state = ARM_CP_STATE_AA64,
6995       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 3,
6996       .access = PL2_W, .type = ARM_CP_NOP },
6997     { .name = "TLBI_IPAS2LE1OS", .state = ARM_CP_STATE_AA64,
6998       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 4,
6999       .access = PL2_W, .type = ARM_CP_NOP },
7000     { .name = "TLBI_RIPAS2LE1OS", .state = ARM_CP_STATE_AA64,
7001       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 7,
7002       .access = PL2_W, .type = ARM_CP_NOP },
7003     { .name = "TLBI_ALLE3OS", .state = ARM_CP_STATE_AA64,
7004       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 0,
7005       .access = PL3_W, .type = ARM_CP_NO_RAW,
7006       .writefn = tlbi_aa64_alle3is_write },
7007     { .name = "TLBI_VAE3OS", .state = ARM_CP_STATE_AA64,
7008       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 1,
7009       .access = PL3_W, .type = ARM_CP_NO_RAW,
7010       .writefn = tlbi_aa64_vae3is_write },
7011     { .name = "TLBI_VALE3OS", .state = ARM_CP_STATE_AA64,
7012       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 5,
7013       .access = PL3_W, .type = ARM_CP_NO_RAW,
7014       .writefn = tlbi_aa64_vae3is_write },
7015 };
7016 
7017 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
7018 {
7019     Error *err = NULL;
7020     uint64_t ret;
7021 
7022     /* Success sets NZCV = 0000.  */
7023     env->NF = env->CF = env->VF = 0, env->ZF = 1;
7024 
7025     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
7026         /*
7027          * ??? Failed, for unknown reasons in the crypto subsystem.
7028          * The best we can do is log the reason and return the
7029          * timed-out indication to the guest.  There is no reason
7030          * we know to expect this failure to be transitory, so the
7031          * guest may well hang retrying the operation.
7032          */
7033         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
7034                       ri->name, error_get_pretty(err));
7035         error_free(err);
7036 
7037         env->ZF = 0; /* NZCF = 0100 */
7038         return 0;
7039     }
7040     return ret;
7041 }
7042 
7043 /* We do not support re-seeding, so the two registers operate the same.  */
7044 static const ARMCPRegInfo rndr_reginfo[] = {
7045     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
7046       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7047       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
7048       .access = PL0_R, .readfn = rndr_readfn },
7049     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
7050       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7051       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
7052       .access = PL0_R, .readfn = rndr_readfn },
7053 };
7054 
7055 #ifndef CONFIG_USER_ONLY
7056 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
7057                           uint64_t value)
7058 {
7059     ARMCPU *cpu = env_archcpu(env);
7060     /* CTR_EL0 System register -> DminLine, bits [19:16] */
7061     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
7062     uint64_t vaddr_in = (uint64_t) value;
7063     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
7064     void *haddr;
7065     int mem_idx = cpu_mmu_index(env, false);
7066 
7067     /* This won't be crossing page boundaries */
7068     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
7069     if (haddr) {
7070 
7071         ram_addr_t offset;
7072         MemoryRegion *mr;
7073 
7074         /* RCU lock is already being held */
7075         mr = memory_region_from_host(haddr, &offset);
7076 
7077         if (mr) {
7078             memory_region_writeback(mr, offset, dline_size);
7079         }
7080     }
7081 }
7082 
7083 static const ARMCPRegInfo dcpop_reg[] = {
7084     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
7085       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
7086       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7087       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7088 };
7089 
7090 static const ARMCPRegInfo dcpodp_reg[] = {
7091     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
7092       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
7093       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7094       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7095 };
7096 #endif /*CONFIG_USER_ONLY*/
7097 
7098 static CPAccessResult access_aa64_tid5(CPUARMState *env, const ARMCPRegInfo *ri,
7099                                        bool isread)
7100 {
7101     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID5)) {
7102         return CP_ACCESS_TRAP_EL2;
7103     }
7104 
7105     return CP_ACCESS_OK;
7106 }
7107 
7108 static CPAccessResult access_mte(CPUARMState *env, const ARMCPRegInfo *ri,
7109                                  bool isread)
7110 {
7111     int el = arm_current_el(env);
7112 
7113     if (el < 2 && arm_is_el2_enabled(env)) {
7114         uint64_t hcr = arm_hcr_el2_eff(env);
7115         if (!(hcr & HCR_ATA) && (!(hcr & HCR_E2H) || !(hcr & HCR_TGE))) {
7116             return CP_ACCESS_TRAP_EL2;
7117         }
7118     }
7119     if (el < 3 &&
7120         arm_feature(env, ARM_FEATURE_EL3) &&
7121         !(env->cp15.scr_el3 & SCR_ATA)) {
7122         return CP_ACCESS_TRAP_EL3;
7123     }
7124     return CP_ACCESS_OK;
7125 }
7126 
7127 static uint64_t tco_read(CPUARMState *env, const ARMCPRegInfo *ri)
7128 {
7129     return env->pstate & PSTATE_TCO;
7130 }
7131 
7132 static void tco_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
7133 {
7134     env->pstate = (env->pstate & ~PSTATE_TCO) | (val & PSTATE_TCO);
7135 }
7136 
7137 static const ARMCPRegInfo mte_reginfo[] = {
7138     { .name = "TFSRE0_EL1", .state = ARM_CP_STATE_AA64,
7139       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 1,
7140       .access = PL1_RW, .accessfn = access_mte,
7141       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[0]) },
7142     { .name = "TFSR_EL1", .state = ARM_CP_STATE_AA64,
7143       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 0,
7144       .access = PL1_RW, .accessfn = access_mte,
7145       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[1]) },
7146     { .name = "TFSR_EL2", .state = ARM_CP_STATE_AA64,
7147       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 6, .opc2 = 0,
7148       .access = PL2_RW, .accessfn = access_mte,
7149       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[2]) },
7150     { .name = "TFSR_EL3", .state = ARM_CP_STATE_AA64,
7151       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 6, .opc2 = 0,
7152       .access = PL3_RW,
7153       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[3]) },
7154     { .name = "RGSR_EL1", .state = ARM_CP_STATE_AA64,
7155       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 5,
7156       .access = PL1_RW, .accessfn = access_mte,
7157       .fieldoffset = offsetof(CPUARMState, cp15.rgsr_el1) },
7158     { .name = "GCR_EL1", .state = ARM_CP_STATE_AA64,
7159       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 6,
7160       .access = PL1_RW, .accessfn = access_mte,
7161       .fieldoffset = offsetof(CPUARMState, cp15.gcr_el1) },
7162     { .name = "GMID_EL1", .state = ARM_CP_STATE_AA64,
7163       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 4,
7164       .access = PL1_R, .accessfn = access_aa64_tid5,
7165       .type = ARM_CP_CONST, .resetvalue = GMID_EL1_BS },
7166     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7167       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7168       .type = ARM_CP_NO_RAW,
7169       .access = PL0_RW, .readfn = tco_read, .writefn = tco_write },
7170     { .name = "DC_IGVAC", .state = ARM_CP_STATE_AA64,
7171       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 3,
7172       .type = ARM_CP_NOP, .access = PL1_W,
7173       .accessfn = aa64_cacheop_poc_access },
7174     { .name = "DC_IGSW", .state = ARM_CP_STATE_AA64,
7175       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 4,
7176       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7177     { .name = "DC_IGDVAC", .state = ARM_CP_STATE_AA64,
7178       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 5,
7179       .type = ARM_CP_NOP, .access = PL1_W,
7180       .accessfn = aa64_cacheop_poc_access },
7181     { .name = "DC_IGDSW", .state = ARM_CP_STATE_AA64,
7182       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 6,
7183       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7184     { .name = "DC_CGSW", .state = ARM_CP_STATE_AA64,
7185       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 4,
7186       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7187     { .name = "DC_CGDSW", .state = ARM_CP_STATE_AA64,
7188       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 6,
7189       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7190     { .name = "DC_CIGSW", .state = ARM_CP_STATE_AA64,
7191       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 4,
7192       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7193     { .name = "DC_CIGDSW", .state = ARM_CP_STATE_AA64,
7194       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 6,
7195       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7196 };
7197 
7198 static const ARMCPRegInfo mte_tco_ro_reginfo[] = {
7199     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7200       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7201       .type = ARM_CP_CONST, .access = PL0_RW, },
7202 };
7203 
7204 static const ARMCPRegInfo mte_el0_cacheop_reginfo[] = {
7205     { .name = "DC_CGVAC", .state = ARM_CP_STATE_AA64,
7206       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 3,
7207       .type = ARM_CP_NOP, .access = PL0_W,
7208       .accessfn = aa64_cacheop_poc_access },
7209     { .name = "DC_CGDVAC", .state = ARM_CP_STATE_AA64,
7210       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 5,
7211       .type = ARM_CP_NOP, .access = PL0_W,
7212       .accessfn = aa64_cacheop_poc_access },
7213     { .name = "DC_CGVAP", .state = ARM_CP_STATE_AA64,
7214       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 3,
7215       .type = ARM_CP_NOP, .access = PL0_W,
7216       .accessfn = aa64_cacheop_poc_access },
7217     { .name = "DC_CGDVAP", .state = ARM_CP_STATE_AA64,
7218       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 5,
7219       .type = ARM_CP_NOP, .access = PL0_W,
7220       .accessfn = aa64_cacheop_poc_access },
7221     { .name = "DC_CGVADP", .state = ARM_CP_STATE_AA64,
7222       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 3,
7223       .type = ARM_CP_NOP, .access = PL0_W,
7224       .accessfn = aa64_cacheop_poc_access },
7225     { .name = "DC_CGDVADP", .state = ARM_CP_STATE_AA64,
7226       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 5,
7227       .type = ARM_CP_NOP, .access = PL0_W,
7228       .accessfn = aa64_cacheop_poc_access },
7229     { .name = "DC_CIGVAC", .state = ARM_CP_STATE_AA64,
7230       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 3,
7231       .type = ARM_CP_NOP, .access = PL0_W,
7232       .accessfn = aa64_cacheop_poc_access },
7233     { .name = "DC_CIGDVAC", .state = ARM_CP_STATE_AA64,
7234       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 5,
7235       .type = ARM_CP_NOP, .access = PL0_W,
7236       .accessfn = aa64_cacheop_poc_access },
7237     { .name = "DC_GVA", .state = ARM_CP_STATE_AA64,
7238       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 3,
7239       .access = PL0_W, .type = ARM_CP_DC_GVA,
7240 #ifndef CONFIG_USER_ONLY
7241       /* Avoid overhead of an access check that always passes in user-mode */
7242       .accessfn = aa64_zva_access,
7243 #endif
7244     },
7245     { .name = "DC_GZVA", .state = ARM_CP_STATE_AA64,
7246       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 4,
7247       .access = PL0_W, .type = ARM_CP_DC_GZVA,
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 };
7254 
7255 static CPAccessResult access_scxtnum(CPUARMState *env, const ARMCPRegInfo *ri,
7256                                      bool isread)
7257 {
7258     uint64_t hcr = arm_hcr_el2_eff(env);
7259     int el = arm_current_el(env);
7260 
7261     if (el == 0 && !((hcr & HCR_E2H) && (hcr & HCR_TGE))) {
7262         if (env->cp15.sctlr_el[1] & SCTLR_TSCXT) {
7263             if (hcr & HCR_TGE) {
7264                 return CP_ACCESS_TRAP_EL2;
7265             }
7266             return CP_ACCESS_TRAP;
7267         }
7268     } else if (el < 2 && (env->cp15.sctlr_el[2] & SCTLR_TSCXT)) {
7269         return CP_ACCESS_TRAP_EL2;
7270     }
7271     if (el < 2 && arm_is_el2_enabled(env) && !(hcr & HCR_ENSCXT)) {
7272         return CP_ACCESS_TRAP_EL2;
7273     }
7274     if (el < 3
7275         && arm_feature(env, ARM_FEATURE_EL3)
7276         && !(env->cp15.scr_el3 & SCR_ENSCXT)) {
7277         return CP_ACCESS_TRAP_EL3;
7278     }
7279     return CP_ACCESS_OK;
7280 }
7281 
7282 static const ARMCPRegInfo scxtnum_reginfo[] = {
7283     { .name = "SCXTNUM_EL0", .state = ARM_CP_STATE_AA64,
7284       .opc0 = 3, .opc1 = 3, .crn = 13, .crm = 0, .opc2 = 7,
7285       .access = PL0_RW, .accessfn = access_scxtnum,
7286       .fieldoffset = offsetof(CPUARMState, scxtnum_el[0]) },
7287     { .name = "SCXTNUM_EL1", .state = ARM_CP_STATE_AA64,
7288       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 7,
7289       .access = PL1_RW, .accessfn = access_scxtnum,
7290       .fieldoffset = offsetof(CPUARMState, scxtnum_el[1]) },
7291     { .name = "SCXTNUM_EL2", .state = ARM_CP_STATE_AA64,
7292       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 7,
7293       .access = PL2_RW, .accessfn = access_scxtnum,
7294       .fieldoffset = offsetof(CPUARMState, scxtnum_el[2]) },
7295     { .name = "SCXTNUM_EL3", .state = ARM_CP_STATE_AA64,
7296       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 7,
7297       .access = PL3_RW,
7298       .fieldoffset = offsetof(CPUARMState, scxtnum_el[3]) },
7299 };
7300 #endif /* TARGET_AARCH64 */
7301 
7302 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
7303                                      bool isread)
7304 {
7305     int el = arm_current_el(env);
7306 
7307     if (el == 0) {
7308         uint64_t sctlr = arm_sctlr(env, el);
7309         if (!(sctlr & SCTLR_EnRCTX)) {
7310             return CP_ACCESS_TRAP;
7311         }
7312     } else if (el == 1) {
7313         uint64_t hcr = arm_hcr_el2_eff(env);
7314         if (hcr & HCR_NV) {
7315             return CP_ACCESS_TRAP_EL2;
7316         }
7317     }
7318     return CP_ACCESS_OK;
7319 }
7320 
7321 static const ARMCPRegInfo predinv_reginfo[] = {
7322     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
7323       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
7324       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7325     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
7326       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
7327       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7328     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
7329       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
7330       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7331     /*
7332      * Note the AArch32 opcodes have a different OPC1.
7333      */
7334     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
7335       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
7336       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7337     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
7338       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
7339       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7340     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
7341       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
7342       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7343 };
7344 
7345 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
7346 {
7347     /* Read the high 32 bits of the current CCSIDR */
7348     return extract64(ccsidr_read(env, ri), 32, 32);
7349 }
7350 
7351 static const ARMCPRegInfo ccsidr2_reginfo[] = {
7352     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
7353       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
7354       .access = PL1_R,
7355       .accessfn = access_aa64_tid2,
7356       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7357 };
7358 
7359 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7360                                        bool isread)
7361 {
7362     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7363         return CP_ACCESS_TRAP_EL2;
7364     }
7365 
7366     return CP_ACCESS_OK;
7367 }
7368 
7369 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7370                                        bool isread)
7371 {
7372     if (arm_feature(env, ARM_FEATURE_V8)) {
7373         return access_aa64_tid3(env, ri, isread);
7374     }
7375 
7376     return CP_ACCESS_OK;
7377 }
7378 
7379 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7380                                      bool isread)
7381 {
7382     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7383         return CP_ACCESS_TRAP_EL2;
7384     }
7385 
7386     return CP_ACCESS_OK;
7387 }
7388 
7389 static CPAccessResult access_joscr_jmcr(CPUARMState *env,
7390                                         const ARMCPRegInfo *ri, bool isread)
7391 {
7392     /*
7393      * HSTR.TJDBX traps JOSCR and JMCR accesses, but it exists only
7394      * in v7A, not in v8A.
7395      */
7396     if (!arm_feature(env, ARM_FEATURE_V8) &&
7397         arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
7398         (env->cp15.hstr_el2 & HSTR_TJDBX)) {
7399         return CP_ACCESS_TRAP_EL2;
7400     }
7401     return CP_ACCESS_OK;
7402 }
7403 
7404 static const ARMCPRegInfo jazelle_regs[] = {
7405     { .name = "JIDR",
7406       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7407       .access = PL1_R, .accessfn = access_jazelle,
7408       .type = ARM_CP_CONST, .resetvalue = 0 },
7409     { .name = "JOSCR",
7410       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7411       .accessfn = access_joscr_jmcr,
7412       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7413     { .name = "JMCR",
7414       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7415       .accessfn = access_joscr_jmcr,
7416       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7417 };
7418 
7419 static const ARMCPRegInfo contextidr_el2 = {
7420     .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7421     .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7422     .access = PL2_RW,
7423     .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2])
7424 };
7425 
7426 static const ARMCPRegInfo vhe_reginfo[] = {
7427     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7428       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7429       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7430       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7431 #ifndef CONFIG_USER_ONLY
7432     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7433       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7434       .fieldoffset =
7435         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7436       .type = ARM_CP_IO, .access = PL2_RW,
7437       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7438     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7439       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7440       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7441       .resetfn = gt_hv_timer_reset,
7442       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7443     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7444       .type = ARM_CP_IO,
7445       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7446       .access = PL2_RW,
7447       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7448       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7449     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7450       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7451       .type = ARM_CP_IO | ARM_CP_ALIAS,
7452       .access = PL2_RW, .accessfn = e2h_access,
7453       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7454       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7455     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7456       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7457       .type = ARM_CP_IO | ARM_CP_ALIAS,
7458       .access = PL2_RW, .accessfn = e2h_access,
7459       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7460       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7461     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7462       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7463       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7464       .access = PL2_RW, .accessfn = e2h_access,
7465       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7466     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7467       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7468       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7469       .access = PL2_RW, .accessfn = e2h_access,
7470       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7471     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7472       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7473       .type = ARM_CP_IO | ARM_CP_ALIAS,
7474       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7475       .access = PL2_RW, .accessfn = e2h_access,
7476       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7477     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7478       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7479       .type = ARM_CP_IO | ARM_CP_ALIAS,
7480       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7481       .access = PL2_RW, .accessfn = e2h_access,
7482       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7483 #endif
7484 };
7485 
7486 #ifndef CONFIG_USER_ONLY
7487 static const ARMCPRegInfo ats1e1_reginfo[] = {
7488     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7489       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7490       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7491       .writefn = ats_write64 },
7492     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7493       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7494       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7495       .writefn = ats_write64 },
7496 };
7497 
7498 static const ARMCPRegInfo ats1cp_reginfo[] = {
7499     { .name = "ATS1CPRP",
7500       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7501       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7502       .writefn = ats_write },
7503     { .name = "ATS1CPWP",
7504       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7505       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7506       .writefn = ats_write },
7507 };
7508 #endif
7509 
7510 /*
7511  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7512  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7513  * is non-zero, which is never for ARMv7, optionally in ARMv8
7514  * and mandatorily for ARMv8.2 and up.
7515  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7516  * implementation is RAZ/WI we can ignore this detail, as we
7517  * do for ACTLR.
7518  */
7519 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7520     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7521       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7522       .access = PL1_RW, .accessfn = access_tacr,
7523       .type = ARM_CP_CONST, .resetvalue = 0 },
7524     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7525       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7526       .access = PL2_RW, .type = ARM_CP_CONST,
7527       .resetvalue = 0 },
7528 };
7529 
7530 void register_cp_regs_for_features(ARMCPU *cpu)
7531 {
7532     /* Register all the coprocessor registers based on feature bits */
7533     CPUARMState *env = &cpu->env;
7534     if (arm_feature(env, ARM_FEATURE_M)) {
7535         /* M profile has no coprocessor registers */
7536         return;
7537     }
7538 
7539     define_arm_cp_regs(cpu, cp_reginfo);
7540     if (!arm_feature(env, ARM_FEATURE_V8)) {
7541         /* Must go early as it is full of wildcards that may be
7542          * overridden by later definitions.
7543          */
7544         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7545     }
7546 
7547     if (arm_feature(env, ARM_FEATURE_V6)) {
7548         /* The ID registers all have impdef reset values */
7549         ARMCPRegInfo v6_idregs[] = {
7550             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7551               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7552               .access = PL1_R, .type = ARM_CP_CONST,
7553               .accessfn = access_aa32_tid3,
7554               .resetvalue = cpu->isar.id_pfr0 },
7555             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7556              * the value of the GIC field until after we define these regs.
7557              */
7558             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7559               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7560               .access = PL1_R, .type = ARM_CP_NO_RAW,
7561               .accessfn = access_aa32_tid3,
7562               .readfn = id_pfr1_read,
7563               .writefn = arm_cp_write_ignore },
7564             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7565               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7566               .access = PL1_R, .type = ARM_CP_CONST,
7567               .accessfn = access_aa32_tid3,
7568               .resetvalue = cpu->isar.id_dfr0 },
7569             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7570               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7571               .access = PL1_R, .type = ARM_CP_CONST,
7572               .accessfn = access_aa32_tid3,
7573               .resetvalue = cpu->id_afr0 },
7574             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7575               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7576               .access = PL1_R, .type = ARM_CP_CONST,
7577               .accessfn = access_aa32_tid3,
7578               .resetvalue = cpu->isar.id_mmfr0 },
7579             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7580               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7581               .access = PL1_R, .type = ARM_CP_CONST,
7582               .accessfn = access_aa32_tid3,
7583               .resetvalue = cpu->isar.id_mmfr1 },
7584             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7585               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7586               .access = PL1_R, .type = ARM_CP_CONST,
7587               .accessfn = access_aa32_tid3,
7588               .resetvalue = cpu->isar.id_mmfr2 },
7589             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7590               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7591               .access = PL1_R, .type = ARM_CP_CONST,
7592               .accessfn = access_aa32_tid3,
7593               .resetvalue = cpu->isar.id_mmfr3 },
7594             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7595               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7596               .access = PL1_R, .type = ARM_CP_CONST,
7597               .accessfn = access_aa32_tid3,
7598               .resetvalue = cpu->isar.id_isar0 },
7599             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7600               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7601               .access = PL1_R, .type = ARM_CP_CONST,
7602               .accessfn = access_aa32_tid3,
7603               .resetvalue = cpu->isar.id_isar1 },
7604             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7605               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7606               .access = PL1_R, .type = ARM_CP_CONST,
7607               .accessfn = access_aa32_tid3,
7608               .resetvalue = cpu->isar.id_isar2 },
7609             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7610               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7611               .access = PL1_R, .type = ARM_CP_CONST,
7612               .accessfn = access_aa32_tid3,
7613               .resetvalue = cpu->isar.id_isar3 },
7614             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7615               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7616               .access = PL1_R, .type = ARM_CP_CONST,
7617               .accessfn = access_aa32_tid3,
7618               .resetvalue = cpu->isar.id_isar4 },
7619             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7620               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7621               .access = PL1_R, .type = ARM_CP_CONST,
7622               .accessfn = access_aa32_tid3,
7623               .resetvalue = cpu->isar.id_isar5 },
7624             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7625               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7626               .access = PL1_R, .type = ARM_CP_CONST,
7627               .accessfn = access_aa32_tid3,
7628               .resetvalue = cpu->isar.id_mmfr4 },
7629             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7630               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7631               .access = PL1_R, .type = ARM_CP_CONST,
7632               .accessfn = access_aa32_tid3,
7633               .resetvalue = cpu->isar.id_isar6 },
7634         };
7635         define_arm_cp_regs(cpu, v6_idregs);
7636         define_arm_cp_regs(cpu, v6_cp_reginfo);
7637     } else {
7638         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7639     }
7640     if (arm_feature(env, ARM_FEATURE_V6K)) {
7641         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7642     }
7643     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7644         !arm_feature(env, ARM_FEATURE_PMSA)) {
7645         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7646     }
7647     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7648         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7649     }
7650     if (arm_feature(env, ARM_FEATURE_V7)) {
7651         ARMCPRegInfo clidr = {
7652             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7653             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7654             .access = PL1_R, .type = ARM_CP_CONST,
7655             .accessfn = access_aa64_tid2,
7656             .resetvalue = cpu->clidr
7657         };
7658         define_one_arm_cp_reg(cpu, &clidr);
7659         define_arm_cp_regs(cpu, v7_cp_reginfo);
7660         define_debug_regs(cpu);
7661         define_pmu_regs(cpu);
7662     } else {
7663         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7664     }
7665     if (arm_feature(env, ARM_FEATURE_V8)) {
7666         /* AArch64 ID registers, which all have impdef reset values.
7667          * Note that within the ID register ranges the unused slots
7668          * must all RAZ, not UNDEF; future architecture versions may
7669          * define new registers here.
7670          */
7671         ARMCPRegInfo v8_idregs[] = {
7672             /*
7673              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7674              * emulation because we don't know the right value for the
7675              * GIC field until after we define these regs.
7676              */
7677             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7678               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7679               .access = PL1_R,
7680 #ifdef CONFIG_USER_ONLY
7681               .type = ARM_CP_CONST,
7682               .resetvalue = cpu->isar.id_aa64pfr0
7683 #else
7684               .type = ARM_CP_NO_RAW,
7685               .accessfn = access_aa64_tid3,
7686               .readfn = id_aa64pfr0_read,
7687               .writefn = arm_cp_write_ignore
7688 #endif
7689             },
7690             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7691               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7692               .access = PL1_R, .type = ARM_CP_CONST,
7693               .accessfn = access_aa64_tid3,
7694               .resetvalue = cpu->isar.id_aa64pfr1},
7695             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7696               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7697               .access = PL1_R, .type = ARM_CP_CONST,
7698               .accessfn = access_aa64_tid3,
7699               .resetvalue = 0 },
7700             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7701               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7702               .access = PL1_R, .type = ARM_CP_CONST,
7703               .accessfn = access_aa64_tid3,
7704               .resetvalue = 0 },
7705             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7706               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7707               .access = PL1_R, .type = ARM_CP_CONST,
7708               .accessfn = access_aa64_tid3,
7709               .resetvalue = cpu->isar.id_aa64zfr0 },
7710             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7711               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7712               .access = PL1_R, .type = ARM_CP_CONST,
7713               .accessfn = access_aa64_tid3,
7714               .resetvalue = 0 },
7715             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7716               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7717               .access = PL1_R, .type = ARM_CP_CONST,
7718               .accessfn = access_aa64_tid3,
7719               .resetvalue = 0 },
7720             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7721               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7722               .access = PL1_R, .type = ARM_CP_CONST,
7723               .accessfn = access_aa64_tid3,
7724               .resetvalue = 0 },
7725             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7726               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7727               .access = PL1_R, .type = ARM_CP_CONST,
7728               .accessfn = access_aa64_tid3,
7729               .resetvalue = cpu->isar.id_aa64dfr0 },
7730             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7731               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7732               .access = PL1_R, .type = ARM_CP_CONST,
7733               .accessfn = access_aa64_tid3,
7734               .resetvalue = cpu->isar.id_aa64dfr1 },
7735             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7736               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7737               .access = PL1_R, .type = ARM_CP_CONST,
7738               .accessfn = access_aa64_tid3,
7739               .resetvalue = 0 },
7740             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7741               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7742               .access = PL1_R, .type = ARM_CP_CONST,
7743               .accessfn = access_aa64_tid3,
7744               .resetvalue = 0 },
7745             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7746               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7747               .access = PL1_R, .type = ARM_CP_CONST,
7748               .accessfn = access_aa64_tid3,
7749               .resetvalue = cpu->id_aa64afr0 },
7750             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7751               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7752               .access = PL1_R, .type = ARM_CP_CONST,
7753               .accessfn = access_aa64_tid3,
7754               .resetvalue = cpu->id_aa64afr1 },
7755             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7756               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7757               .access = PL1_R, .type = ARM_CP_CONST,
7758               .accessfn = access_aa64_tid3,
7759               .resetvalue = 0 },
7760             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7761               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7762               .access = PL1_R, .type = ARM_CP_CONST,
7763               .accessfn = access_aa64_tid3,
7764               .resetvalue = 0 },
7765             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7766               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7767               .access = PL1_R, .type = ARM_CP_CONST,
7768               .accessfn = access_aa64_tid3,
7769               .resetvalue = cpu->isar.id_aa64isar0 },
7770             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7771               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7772               .access = PL1_R, .type = ARM_CP_CONST,
7773               .accessfn = access_aa64_tid3,
7774               .resetvalue = cpu->isar.id_aa64isar1 },
7775             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7776               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7777               .access = PL1_R, .type = ARM_CP_CONST,
7778               .accessfn = access_aa64_tid3,
7779               .resetvalue = 0 },
7780             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7781               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7782               .access = PL1_R, .type = ARM_CP_CONST,
7783               .accessfn = access_aa64_tid3,
7784               .resetvalue = 0 },
7785             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7786               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7787               .access = PL1_R, .type = ARM_CP_CONST,
7788               .accessfn = access_aa64_tid3,
7789               .resetvalue = 0 },
7790             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7791               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7792               .access = PL1_R, .type = ARM_CP_CONST,
7793               .accessfn = access_aa64_tid3,
7794               .resetvalue = 0 },
7795             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7796               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7797               .access = PL1_R, .type = ARM_CP_CONST,
7798               .accessfn = access_aa64_tid3,
7799               .resetvalue = 0 },
7800             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7801               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7802               .access = PL1_R, .type = ARM_CP_CONST,
7803               .accessfn = access_aa64_tid3,
7804               .resetvalue = 0 },
7805             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7806               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7807               .access = PL1_R, .type = ARM_CP_CONST,
7808               .accessfn = access_aa64_tid3,
7809               .resetvalue = cpu->isar.id_aa64mmfr0 },
7810             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7811               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7812               .access = PL1_R, .type = ARM_CP_CONST,
7813               .accessfn = access_aa64_tid3,
7814               .resetvalue = cpu->isar.id_aa64mmfr1 },
7815             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7816               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7817               .access = PL1_R, .type = ARM_CP_CONST,
7818               .accessfn = access_aa64_tid3,
7819               .resetvalue = cpu->isar.id_aa64mmfr2 },
7820             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7821               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7822               .access = PL1_R, .type = ARM_CP_CONST,
7823               .accessfn = access_aa64_tid3,
7824               .resetvalue = 0 },
7825             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7826               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7827               .access = PL1_R, .type = ARM_CP_CONST,
7828               .accessfn = access_aa64_tid3,
7829               .resetvalue = 0 },
7830             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7831               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7832               .access = PL1_R, .type = ARM_CP_CONST,
7833               .accessfn = access_aa64_tid3,
7834               .resetvalue = 0 },
7835             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7836               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7837               .access = PL1_R, .type = ARM_CP_CONST,
7838               .accessfn = access_aa64_tid3,
7839               .resetvalue = 0 },
7840             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7841               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7842               .access = PL1_R, .type = ARM_CP_CONST,
7843               .accessfn = access_aa64_tid3,
7844               .resetvalue = 0 },
7845             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7846               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7847               .access = PL1_R, .type = ARM_CP_CONST,
7848               .accessfn = access_aa64_tid3,
7849               .resetvalue = cpu->isar.mvfr0 },
7850             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7851               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7852               .access = PL1_R, .type = ARM_CP_CONST,
7853               .accessfn = access_aa64_tid3,
7854               .resetvalue = cpu->isar.mvfr1 },
7855             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7856               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7857               .access = PL1_R, .type = ARM_CP_CONST,
7858               .accessfn = access_aa64_tid3,
7859               .resetvalue = cpu->isar.mvfr2 },
7860             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7861               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7862               .access = PL1_R, .type = ARM_CP_CONST,
7863               .accessfn = access_aa64_tid3,
7864               .resetvalue = 0 },
7865             { .name = "ID_PFR2", .state = ARM_CP_STATE_BOTH,
7866               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7867               .access = PL1_R, .type = ARM_CP_CONST,
7868               .accessfn = access_aa64_tid3,
7869               .resetvalue = cpu->isar.id_pfr2 },
7870             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7871               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7872               .access = PL1_R, .type = ARM_CP_CONST,
7873               .accessfn = access_aa64_tid3,
7874               .resetvalue = 0 },
7875             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7876               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7877               .access = PL1_R, .type = ARM_CP_CONST,
7878               .accessfn = access_aa64_tid3,
7879               .resetvalue = 0 },
7880             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7881               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7882               .access = PL1_R, .type = ARM_CP_CONST,
7883               .accessfn = access_aa64_tid3,
7884               .resetvalue = 0 },
7885             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7886               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7887               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7888               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7889             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7890               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7891               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7892               .resetvalue = cpu->pmceid0 },
7893             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7894               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7895               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7896               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7897             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7898               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7899               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7900               .resetvalue = cpu->pmceid1 },
7901         };
7902 #ifdef CONFIG_USER_ONLY
7903         static const ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7904             { .name = "ID_AA64PFR0_EL1",
7905               .exported_bits = 0x000f000f00ff0000,
7906               .fixed_bits    = 0x0000000000000011 },
7907             { .name = "ID_AA64PFR1_EL1",
7908               .exported_bits = 0x00000000000000f0 },
7909             { .name = "ID_AA64PFR*_EL1_RESERVED",
7910               .is_glob = true                     },
7911             { .name = "ID_AA64ZFR0_EL1"           },
7912             { .name = "ID_AA64MMFR0_EL1",
7913               .fixed_bits    = 0x00000000ff000000 },
7914             { .name = "ID_AA64MMFR1_EL1"          },
7915             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7916               .is_glob = true                     },
7917             { .name = "ID_AA64DFR0_EL1",
7918               .fixed_bits    = 0x0000000000000006 },
7919             { .name = "ID_AA64DFR1_EL1"           },
7920             { .name = "ID_AA64DFR*_EL1_RESERVED",
7921               .is_glob = true                     },
7922             { .name = "ID_AA64AFR*",
7923               .is_glob = true                     },
7924             { .name = "ID_AA64ISAR0_EL1",
7925               .exported_bits = 0x00fffffff0fffff0 },
7926             { .name = "ID_AA64ISAR1_EL1",
7927               .exported_bits = 0x000000f0ffffffff },
7928             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7929               .is_glob = true                     },
7930         };
7931         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7932 #endif
7933         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7934         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7935             !arm_feature(env, ARM_FEATURE_EL2)) {
7936             ARMCPRegInfo rvbar = {
7937                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7938                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7939                 .access = PL1_R,
7940                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7941             };
7942             define_one_arm_cp_reg(cpu, &rvbar);
7943         }
7944         define_arm_cp_regs(cpu, v8_idregs);
7945         define_arm_cp_regs(cpu, v8_cp_reginfo);
7946     }
7947 
7948     /*
7949      * Register the base EL2 cpregs.
7950      * Pre v8, these registers are implemented only as part of the
7951      * Virtualization Extensions (EL2 present).  Beginning with v8,
7952      * if EL2 is missing but EL3 is enabled, mostly these become
7953      * RES0 from EL3, with some specific exceptions.
7954      */
7955     if (arm_feature(env, ARM_FEATURE_EL2)
7956         || (arm_feature(env, ARM_FEATURE_EL3)
7957             && arm_feature(env, ARM_FEATURE_V8))) {
7958         uint64_t vmpidr_def = mpidr_read_val(env);
7959         ARMCPRegInfo vpidr_regs[] = {
7960             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7961               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7962               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7963               .resetvalue = cpu->midr,
7964               .type = ARM_CP_ALIAS | ARM_CP_EL3_NO_EL2_C_NZ,
7965               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7966             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7967               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7968               .access = PL2_RW, .resetvalue = cpu->midr,
7969               .type = ARM_CP_EL3_NO_EL2_C_NZ,
7970               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7971             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7972               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7973               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7974               .resetvalue = vmpidr_def,
7975               .type = ARM_CP_ALIAS | ARM_CP_EL3_NO_EL2_C_NZ,
7976               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7977             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7978               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7979               .access = PL2_RW, .resetvalue = vmpidr_def,
7980               .type = ARM_CP_EL3_NO_EL2_C_NZ,
7981               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7982         };
7983         define_arm_cp_regs(cpu, vpidr_regs);
7984         define_arm_cp_regs(cpu, el2_cp_reginfo);
7985         if (arm_feature(env, ARM_FEATURE_V8)) {
7986             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
7987         }
7988         if (cpu_isar_feature(aa64_sel2, cpu)) {
7989             define_arm_cp_regs(cpu, el2_sec_cp_reginfo);
7990         }
7991         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
7992         if (!arm_feature(env, ARM_FEATURE_EL3)) {
7993             ARMCPRegInfo rvbar = {
7994                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
7995                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
7996                 .access = PL2_R,
7997                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7998             };
7999             define_one_arm_cp_reg(cpu, &rvbar);
8000         }
8001     }
8002 
8003     /* Register the base EL3 cpregs. */
8004     if (arm_feature(env, ARM_FEATURE_EL3)) {
8005         define_arm_cp_regs(cpu, el3_cp_reginfo);
8006         ARMCPRegInfo el3_regs[] = {
8007             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
8008               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
8009               .access = PL3_R,
8010               .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
8011             },
8012             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
8013               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
8014               .access = PL3_RW,
8015               .raw_writefn = raw_write, .writefn = sctlr_write,
8016               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
8017               .resetvalue = cpu->reset_sctlr },
8018         };
8019 
8020         define_arm_cp_regs(cpu, el3_regs);
8021     }
8022     /* The behaviour of NSACR is sufficiently various that we don't
8023      * try to describe it in a single reginfo:
8024      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
8025      *     reads as constant 0xc00 from NS EL1 and NS EL2
8026      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
8027      *  if v7 without EL3, register doesn't exist
8028      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
8029      */
8030     if (arm_feature(env, ARM_FEATURE_EL3)) {
8031         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8032             static const ARMCPRegInfo nsacr = {
8033                 .name = "NSACR", .type = ARM_CP_CONST,
8034                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8035                 .access = PL1_RW, .accessfn = nsacr_access,
8036                 .resetvalue = 0xc00
8037             };
8038             define_one_arm_cp_reg(cpu, &nsacr);
8039         } else {
8040             static const ARMCPRegInfo nsacr = {
8041                 .name = "NSACR",
8042                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8043                 .access = PL3_RW | PL1_R,
8044                 .resetvalue = 0,
8045                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
8046             };
8047             define_one_arm_cp_reg(cpu, &nsacr);
8048         }
8049     } else {
8050         if (arm_feature(env, ARM_FEATURE_V8)) {
8051             static const ARMCPRegInfo nsacr = {
8052                 .name = "NSACR", .type = ARM_CP_CONST,
8053                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8054                 .access = PL1_R,
8055                 .resetvalue = 0xc00
8056             };
8057             define_one_arm_cp_reg(cpu, &nsacr);
8058         }
8059     }
8060 
8061     if (arm_feature(env, ARM_FEATURE_PMSA)) {
8062         if (arm_feature(env, ARM_FEATURE_V6)) {
8063             /* PMSAv6 not implemented */
8064             assert(arm_feature(env, ARM_FEATURE_V7));
8065             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8066             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
8067         } else {
8068             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
8069         }
8070     } else {
8071         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8072         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
8073         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
8074         if (cpu_isar_feature(aa32_hpd, cpu)) {
8075             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
8076         }
8077     }
8078     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
8079         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
8080     }
8081     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
8082         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
8083     }
8084     if (arm_feature(env, ARM_FEATURE_VAPA)) {
8085         define_arm_cp_regs(cpu, vapa_cp_reginfo);
8086     }
8087     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
8088         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
8089     }
8090     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
8091         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
8092     }
8093     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
8094         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
8095     }
8096     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
8097         define_arm_cp_regs(cpu, omap_cp_reginfo);
8098     }
8099     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
8100         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
8101     }
8102     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8103         define_arm_cp_regs(cpu, xscale_cp_reginfo);
8104     }
8105     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
8106         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
8107     }
8108     if (arm_feature(env, ARM_FEATURE_LPAE)) {
8109         define_arm_cp_regs(cpu, lpae_cp_reginfo);
8110     }
8111     if (cpu_isar_feature(aa32_jazelle, cpu)) {
8112         define_arm_cp_regs(cpu, jazelle_regs);
8113     }
8114     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
8115      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
8116      * be read-only (ie write causes UNDEF exception).
8117      */
8118     {
8119         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
8120             /* Pre-v8 MIDR space.
8121              * Note that the MIDR isn't a simple constant register because
8122              * of the TI925 behaviour where writes to another register can
8123              * cause the MIDR value to change.
8124              *
8125              * Unimplemented registers in the c15 0 0 0 space default to
8126              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
8127              * and friends override accordingly.
8128              */
8129             { .name = "MIDR",
8130               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
8131               .access = PL1_R, .resetvalue = cpu->midr,
8132               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
8133               .readfn = midr_read,
8134               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8135               .type = ARM_CP_OVERRIDE },
8136             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
8137             { .name = "DUMMY",
8138               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
8139               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8140             { .name = "DUMMY",
8141               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
8142               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8143             { .name = "DUMMY",
8144               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
8145               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8146             { .name = "DUMMY",
8147               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
8148               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8149             { .name = "DUMMY",
8150               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
8151               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8152         };
8153         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
8154             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
8155               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
8156               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
8157               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8158               .readfn = midr_read },
8159             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
8160             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8161               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8162               .access = PL1_R, .resetvalue = cpu->midr },
8163             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8164               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
8165               .access = PL1_R, .resetvalue = cpu->midr },
8166             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
8167               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
8168               .access = PL1_R,
8169               .accessfn = access_aa64_tid1,
8170               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
8171         };
8172         ARMCPRegInfo id_cp_reginfo[] = {
8173             /* These are common to v8 and pre-v8 */
8174             { .name = "CTR",
8175               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
8176               .access = PL1_R, .accessfn = ctr_el0_access,
8177               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8178             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
8179               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
8180               .access = PL0_R, .accessfn = ctr_el0_access,
8181               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8182             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
8183             { .name = "TCMTR",
8184               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
8185               .access = PL1_R,
8186               .accessfn = access_aa32_tid1,
8187               .type = ARM_CP_CONST, .resetvalue = 0 },
8188         };
8189         /* TLBTR is specific to VMSA */
8190         ARMCPRegInfo id_tlbtr_reginfo = {
8191               .name = "TLBTR",
8192               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
8193               .access = PL1_R,
8194               .accessfn = access_aa32_tid1,
8195               .type = ARM_CP_CONST, .resetvalue = 0,
8196         };
8197         /* MPUIR is specific to PMSA V6+ */
8198         ARMCPRegInfo id_mpuir_reginfo = {
8199               .name = "MPUIR",
8200               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8201               .access = PL1_R, .type = ARM_CP_CONST,
8202               .resetvalue = cpu->pmsav7_dregion << 8
8203         };
8204         static const ARMCPRegInfo crn0_wi_reginfo = {
8205             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
8206             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
8207             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
8208         };
8209 #ifdef CONFIG_USER_ONLY
8210         static const ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
8211             { .name = "MIDR_EL1",
8212               .exported_bits = 0x00000000ffffffff },
8213             { .name = "REVIDR_EL1"                },
8214         };
8215         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
8216 #endif
8217         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
8218             arm_feature(env, ARM_FEATURE_STRONGARM)) {
8219             size_t i;
8220             /* Register the blanket "writes ignored" value first to cover the
8221              * whole space. Then update the specific ID registers to allow write
8222              * access, so that they ignore writes rather than causing them to
8223              * UNDEF.
8224              */
8225             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
8226             for (i = 0; i < ARRAY_SIZE(id_pre_v8_midr_cp_reginfo); ++i) {
8227                 id_pre_v8_midr_cp_reginfo[i].access = PL1_RW;
8228             }
8229             for (i = 0; i < ARRAY_SIZE(id_cp_reginfo); ++i) {
8230                 id_cp_reginfo[i].access = PL1_RW;
8231             }
8232             id_mpuir_reginfo.access = PL1_RW;
8233             id_tlbtr_reginfo.access = PL1_RW;
8234         }
8235         if (arm_feature(env, ARM_FEATURE_V8)) {
8236             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
8237         } else {
8238             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
8239         }
8240         define_arm_cp_regs(cpu, id_cp_reginfo);
8241         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
8242             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
8243         } else if (arm_feature(env, ARM_FEATURE_V7)) {
8244             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
8245         }
8246     }
8247 
8248     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
8249         ARMCPRegInfo mpidr_cp_reginfo[] = {
8250             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
8251               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
8252               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
8253         };
8254 #ifdef CONFIG_USER_ONLY
8255         static const ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
8256             { .name = "MPIDR_EL1",
8257               .fixed_bits = 0x0000000080000000 },
8258         };
8259         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
8260 #endif
8261         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
8262     }
8263 
8264     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
8265         ARMCPRegInfo auxcr_reginfo[] = {
8266             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
8267               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
8268               .access = PL1_RW, .accessfn = access_tacr,
8269               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
8270             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
8271               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
8272               .access = PL2_RW, .type = ARM_CP_CONST,
8273               .resetvalue = 0 },
8274             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
8275               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
8276               .access = PL3_RW, .type = ARM_CP_CONST,
8277               .resetvalue = 0 },
8278         };
8279         define_arm_cp_regs(cpu, auxcr_reginfo);
8280         if (cpu_isar_feature(aa32_ac2, cpu)) {
8281             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
8282         }
8283     }
8284 
8285     if (arm_feature(env, ARM_FEATURE_CBAR)) {
8286         /*
8287          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
8288          * There are two flavours:
8289          *  (1) older 32-bit only cores have a simple 32-bit CBAR
8290          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
8291          *      32-bit register visible to AArch32 at a different encoding
8292          *      to the "flavour 1" register and with the bits rearranged to
8293          *      be able to squash a 64-bit address into the 32-bit view.
8294          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
8295          * in future if we support AArch32-only configs of some of the
8296          * AArch64 cores we might need to add a specific feature flag
8297          * to indicate cores with "flavour 2" CBAR.
8298          */
8299         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8300             /* 32 bit view is [31:18] 0...0 [43:32]. */
8301             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
8302                 | extract64(cpu->reset_cbar, 32, 12);
8303             ARMCPRegInfo cbar_reginfo[] = {
8304                 { .name = "CBAR",
8305                   .type = ARM_CP_CONST,
8306                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
8307                   .access = PL1_R, .resetvalue = cbar32 },
8308                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
8309                   .type = ARM_CP_CONST,
8310                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
8311                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
8312             };
8313             /* We don't implement a r/w 64 bit CBAR currently */
8314             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
8315             define_arm_cp_regs(cpu, cbar_reginfo);
8316         } else {
8317             ARMCPRegInfo cbar = {
8318                 .name = "CBAR",
8319                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
8320                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
8321                 .fieldoffset = offsetof(CPUARMState,
8322                                         cp15.c15_config_base_address)
8323             };
8324             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
8325                 cbar.access = PL1_R;
8326                 cbar.fieldoffset = 0;
8327                 cbar.type = ARM_CP_CONST;
8328             }
8329             define_one_arm_cp_reg(cpu, &cbar);
8330         }
8331     }
8332 
8333     if (arm_feature(env, ARM_FEATURE_VBAR)) {
8334         static const ARMCPRegInfo vbar_cp_reginfo[] = {
8335             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
8336               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
8337               .access = PL1_RW, .writefn = vbar_write,
8338               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
8339                                      offsetof(CPUARMState, cp15.vbar_ns) },
8340               .resetvalue = 0 },
8341         };
8342         define_arm_cp_regs(cpu, vbar_cp_reginfo);
8343     }
8344 
8345     /* Generic registers whose values depend on the implementation */
8346     {
8347         ARMCPRegInfo sctlr = {
8348             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8349             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8350             .access = PL1_RW, .accessfn = access_tvm_trvm,
8351             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8352                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8353             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8354             .raw_writefn = raw_write,
8355         };
8356         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8357             /* Normally we would always end the TB on an SCTLR write, but Linux
8358              * arch/arm/mach-pxa/sleep.S expects two instructions following
8359              * an MMU enable to execute from cache.  Imitate this behaviour.
8360              */
8361             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8362         }
8363         define_one_arm_cp_reg(cpu, &sctlr);
8364     }
8365 
8366     if (cpu_isar_feature(aa64_lor, cpu)) {
8367         define_arm_cp_regs(cpu, lor_reginfo);
8368     }
8369     if (cpu_isar_feature(aa64_pan, cpu)) {
8370         define_one_arm_cp_reg(cpu, &pan_reginfo);
8371     }
8372 #ifndef CONFIG_USER_ONLY
8373     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8374         define_arm_cp_regs(cpu, ats1e1_reginfo);
8375     }
8376     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8377         define_arm_cp_regs(cpu, ats1cp_reginfo);
8378     }
8379 #endif
8380     if (cpu_isar_feature(aa64_uao, cpu)) {
8381         define_one_arm_cp_reg(cpu, &uao_reginfo);
8382     }
8383 
8384     if (cpu_isar_feature(aa64_dit, cpu)) {
8385         define_one_arm_cp_reg(cpu, &dit_reginfo);
8386     }
8387     if (cpu_isar_feature(aa64_ssbs, cpu)) {
8388         define_one_arm_cp_reg(cpu, &ssbs_reginfo);
8389     }
8390     if (cpu_isar_feature(any_ras, cpu)) {
8391         define_arm_cp_regs(cpu, minimal_ras_reginfo);
8392     }
8393 
8394     if (cpu_isar_feature(aa64_vh, cpu) ||
8395         cpu_isar_feature(aa64_debugv8p2, cpu)) {
8396         define_one_arm_cp_reg(cpu, &contextidr_el2);
8397     }
8398     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8399         define_arm_cp_regs(cpu, vhe_reginfo);
8400     }
8401 
8402     if (cpu_isar_feature(aa64_sve, cpu)) {
8403         define_arm_cp_regs(cpu, zcr_reginfo);
8404     }
8405 
8406 #ifdef TARGET_AARCH64
8407     if (cpu_isar_feature(aa64_pauth, cpu)) {
8408         define_arm_cp_regs(cpu, pauth_reginfo);
8409     }
8410     if (cpu_isar_feature(aa64_rndr, cpu)) {
8411         define_arm_cp_regs(cpu, rndr_reginfo);
8412     }
8413     if (cpu_isar_feature(aa64_tlbirange, cpu)) {
8414         define_arm_cp_regs(cpu, tlbirange_reginfo);
8415     }
8416     if (cpu_isar_feature(aa64_tlbios, cpu)) {
8417         define_arm_cp_regs(cpu, tlbios_reginfo);
8418     }
8419 #ifndef CONFIG_USER_ONLY
8420     /* Data Cache clean instructions up to PoP */
8421     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8422         define_one_arm_cp_reg(cpu, dcpop_reg);
8423 
8424         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8425             define_one_arm_cp_reg(cpu, dcpodp_reg);
8426         }
8427     }
8428 #endif /*CONFIG_USER_ONLY*/
8429 
8430     /*
8431      * If full MTE is enabled, add all of the system registers.
8432      * If only "instructions available at EL0" are enabled,
8433      * then define only a RAZ/WI version of PSTATE.TCO.
8434      */
8435     if (cpu_isar_feature(aa64_mte, cpu)) {
8436         define_arm_cp_regs(cpu, mte_reginfo);
8437         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8438     } else if (cpu_isar_feature(aa64_mte_insn_reg, cpu)) {
8439         define_arm_cp_regs(cpu, mte_tco_ro_reginfo);
8440         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8441     }
8442 
8443     if (cpu_isar_feature(aa64_scxtnum, cpu)) {
8444         define_arm_cp_regs(cpu, scxtnum_reginfo);
8445     }
8446 #endif
8447 
8448     if (cpu_isar_feature(any_predinv, cpu)) {
8449         define_arm_cp_regs(cpu, predinv_reginfo);
8450     }
8451 
8452     if (cpu_isar_feature(any_ccidx, cpu)) {
8453         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8454     }
8455 
8456 #ifndef CONFIG_USER_ONLY
8457     /*
8458      * Register redirections and aliases must be done last,
8459      * after the registers from the other extensions have been defined.
8460      */
8461     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8462         define_arm_vh_e2h_redirects_aliases(cpu);
8463     }
8464 #endif
8465 }
8466 
8467 /* Sort alphabetically by type name, except for "any". */
8468 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8469 {
8470     ObjectClass *class_a = (ObjectClass *)a;
8471     ObjectClass *class_b = (ObjectClass *)b;
8472     const char *name_a, *name_b;
8473 
8474     name_a = object_class_get_name(class_a);
8475     name_b = object_class_get_name(class_b);
8476     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8477         return 1;
8478     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8479         return -1;
8480     } else {
8481         return strcmp(name_a, name_b);
8482     }
8483 }
8484 
8485 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8486 {
8487     ObjectClass *oc = data;
8488     const char *typename;
8489     char *name;
8490 
8491     typename = object_class_get_name(oc);
8492     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8493     qemu_printf("  %s\n", name);
8494     g_free(name);
8495 }
8496 
8497 void arm_cpu_list(void)
8498 {
8499     GSList *list;
8500 
8501     list = object_class_get_list(TYPE_ARM_CPU, false);
8502     list = g_slist_sort(list, arm_cpu_list_compare);
8503     qemu_printf("Available CPUs:\n");
8504     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8505     g_slist_free(list);
8506 }
8507 
8508 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8509 {
8510     ObjectClass *oc = data;
8511     CpuDefinitionInfoList **cpu_list = user_data;
8512     CpuDefinitionInfo *info;
8513     const char *typename;
8514 
8515     typename = object_class_get_name(oc);
8516     info = g_malloc0(sizeof(*info));
8517     info->name = g_strndup(typename,
8518                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8519     info->q_typename = g_strdup(typename);
8520 
8521     QAPI_LIST_PREPEND(*cpu_list, info);
8522 }
8523 
8524 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8525 {
8526     CpuDefinitionInfoList *cpu_list = NULL;
8527     GSList *list;
8528 
8529     list = object_class_get_list(TYPE_ARM_CPU, false);
8530     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8531     g_slist_free(list);
8532 
8533     return cpu_list;
8534 }
8535 
8536 /*
8537  * Private utility function for define_one_arm_cp_reg_with_opaque():
8538  * add a single reginfo struct to the hash table.
8539  */
8540 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8541                                    void *opaque, CPState state,
8542                                    CPSecureState secstate,
8543                                    int crm, int opc1, int opc2,
8544                                    const char *name)
8545 {
8546     CPUARMState *env = &cpu->env;
8547     uint32_t key;
8548     ARMCPRegInfo *r2;
8549     bool is64 = r->type & ARM_CP_64BIT;
8550     bool ns = secstate & ARM_CP_SECSTATE_NS;
8551     int cp = r->cp;
8552     size_t name_len;
8553     bool make_const;
8554 
8555     switch (state) {
8556     case ARM_CP_STATE_AA32:
8557         /* We assume it is a cp15 register if the .cp field is left unset. */
8558         if (cp == 0 && r->state == ARM_CP_STATE_BOTH) {
8559             cp = 15;
8560         }
8561         key = ENCODE_CP_REG(cp, is64, ns, r->crn, crm, opc1, opc2);
8562         break;
8563     case ARM_CP_STATE_AA64:
8564         /*
8565          * To allow abbreviation of ARMCPRegInfo definitions, we treat
8566          * cp == 0 as equivalent to the value for "standard guest-visible
8567          * sysreg".  STATE_BOTH definitions are also always "standard sysreg"
8568          * in their AArch64 view (the .cp value may be non-zero for the
8569          * benefit of the AArch32 view).
8570          */
8571         if (cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8572             cp = CP_REG_ARM64_SYSREG_CP;
8573         }
8574         key = ENCODE_AA64_CP_REG(cp, r->crn, crm, r->opc0, opc1, opc2);
8575         break;
8576     default:
8577         g_assert_not_reached();
8578     }
8579 
8580     /* Overriding of an existing definition must be explicitly requested. */
8581     if (!(r->type & ARM_CP_OVERRIDE)) {
8582         const ARMCPRegInfo *oldreg = get_arm_cp_reginfo(cpu->cp_regs, key);
8583         if (oldreg) {
8584             assert(oldreg->type & ARM_CP_OVERRIDE);
8585         }
8586     }
8587 
8588     /*
8589      * Eliminate registers that are not present because the EL is missing.
8590      * Doing this here makes it easier to put all registers for a given
8591      * feature into the same ARMCPRegInfo array and define them all at once.
8592      */
8593     make_const = false;
8594     if (arm_feature(env, ARM_FEATURE_EL3)) {
8595         /*
8596          * An EL2 register without EL2 but with EL3 is (usually) RES0.
8597          * See rule RJFFP in section D1.1.3 of DDI0487H.a.
8598          */
8599         int min_el = ctz32(r->access) / 2;
8600         if (min_el == 2 && !arm_feature(env, ARM_FEATURE_EL2)) {
8601             if (r->type & ARM_CP_EL3_NO_EL2_UNDEF) {
8602                 return;
8603             }
8604             make_const = !(r->type & ARM_CP_EL3_NO_EL2_KEEP);
8605         }
8606     } else {
8607         CPAccessRights max_el = (arm_feature(env, ARM_FEATURE_EL2)
8608                                  ? PL2_RW : PL1_RW);
8609         if ((r->access & max_el) == 0) {
8610             return;
8611         }
8612     }
8613 
8614     /* Combine cpreg and name into one allocation. */
8615     name_len = strlen(name) + 1;
8616     r2 = g_malloc(sizeof(*r2) + name_len);
8617     *r2 = *r;
8618     r2->name = memcpy(r2 + 1, name, name_len);
8619 
8620     /*
8621      * Update fields to match the instantiation, overwiting wildcards
8622      * such as CP_ANY, ARM_CP_STATE_BOTH, or ARM_CP_SECSTATE_BOTH.
8623      */
8624     r2->cp = cp;
8625     r2->crm = crm;
8626     r2->opc1 = opc1;
8627     r2->opc2 = opc2;
8628     r2->state = state;
8629     r2->secure = secstate;
8630     if (opaque) {
8631         r2->opaque = opaque;
8632     }
8633 
8634     if (make_const) {
8635         /* This should not have been a very special register to begin. */
8636         int old_special = r2->type & ARM_CP_SPECIAL_MASK;
8637         assert(old_special == 0 || old_special == ARM_CP_NOP);
8638         /*
8639          * Set the special function to CONST, retaining the other flags.
8640          * This is important for e.g. ARM_CP_SVE so that we still
8641          * take the SVE trap if CPTR_EL3.EZ == 0.
8642          */
8643         r2->type = (r2->type & ~ARM_CP_SPECIAL_MASK) | ARM_CP_CONST;
8644         /*
8645          * Usually, these registers become RES0, but there are a few
8646          * special cases like VPIDR_EL2 which have a constant non-zero
8647          * value with writes ignored.
8648          */
8649         if (!(r->type & ARM_CP_EL3_NO_EL2_C_NZ)) {
8650             r2->resetvalue = 0;
8651         }
8652         /*
8653          * ARM_CP_CONST has precedence, so removing the callbacks and
8654          * offsets are not strictly necessary, but it is potentially
8655          * less confusing to debug later.
8656          */
8657         r2->readfn = NULL;
8658         r2->writefn = NULL;
8659         r2->raw_readfn = NULL;
8660         r2->raw_writefn = NULL;
8661         r2->resetfn = NULL;
8662         r2->fieldoffset = 0;
8663         r2->bank_fieldoffsets[0] = 0;
8664         r2->bank_fieldoffsets[1] = 0;
8665     } else {
8666         bool isbanked = r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1];
8667 
8668         if (isbanked) {
8669             /*
8670              * Register is banked (using both entries in array).
8671              * Overwriting fieldoffset as the array is only used to define
8672              * banked registers but later only fieldoffset is used.
8673              */
8674             r2->fieldoffset = r->bank_fieldoffsets[ns];
8675         }
8676         if (state == ARM_CP_STATE_AA32) {
8677             if (isbanked) {
8678                 /*
8679                  * If the register is banked then we don't need to migrate or
8680                  * reset the 32-bit instance in certain cases:
8681                  *
8682                  * 1) If the register has both 32-bit and 64-bit instances
8683                  *    then we can count on the 64-bit instance taking care
8684                  *    of the non-secure bank.
8685                  * 2) If ARMv8 is enabled then we can count on a 64-bit
8686                  *    version taking care of the secure bank.  This requires
8687                  *    that separate 32 and 64-bit definitions are provided.
8688                  */
8689                 if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8690                     (arm_feature(env, ARM_FEATURE_V8) && !ns)) {
8691                     r2->type |= ARM_CP_ALIAS;
8692                 }
8693             } else if ((secstate != r->secure) && !ns) {
8694                 /*
8695                  * The register is not banked so we only want to allow
8696                  * migration of the non-secure instance.
8697                  */
8698                 r2->type |= ARM_CP_ALIAS;
8699             }
8700 
8701             if (HOST_BIG_ENDIAN &&
8702                 r->state == ARM_CP_STATE_BOTH && r2->fieldoffset) {
8703                 r2->fieldoffset += sizeof(uint32_t);
8704             }
8705         }
8706     }
8707 
8708     /*
8709      * By convention, for wildcarded registers only the first
8710      * entry is used for migration; the others are marked as
8711      * ALIAS so we don't try to transfer the register
8712      * multiple times. Special registers (ie NOP/WFI) are
8713      * never migratable and not even raw-accessible.
8714      */
8715     if (r2->type & ARM_CP_SPECIAL_MASK) {
8716         r2->type |= ARM_CP_NO_RAW;
8717     }
8718     if (((r->crm == CP_ANY) && crm != 0) ||
8719         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8720         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8721         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8722     }
8723 
8724     /*
8725      * Check that raw accesses are either forbidden or handled. Note that
8726      * we can't assert this earlier because the setup of fieldoffset for
8727      * banked registers has to be done first.
8728      */
8729     if (!(r2->type & ARM_CP_NO_RAW)) {
8730         assert(!raw_accessors_invalid(r2));
8731     }
8732 
8733     g_hash_table_insert(cpu->cp_regs, (gpointer)(uintptr_t)key, r2);
8734 }
8735 
8736 
8737 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8738                                        const ARMCPRegInfo *r, void *opaque)
8739 {
8740     /* Define implementations of coprocessor registers.
8741      * We store these in a hashtable because typically
8742      * there are less than 150 registers in a space which
8743      * is 16*16*16*8*8 = 262144 in size.
8744      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8745      * If a register is defined twice then the second definition is
8746      * used, so this can be used to define some generic registers and
8747      * then override them with implementation specific variations.
8748      * At least one of the original and the second definition should
8749      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8750      * against accidental use.
8751      *
8752      * The state field defines whether the register is to be
8753      * visible in the AArch32 or AArch64 execution state. If the
8754      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8755      * reginfo structure for the AArch32 view, which sees the lower
8756      * 32 bits of the 64 bit register.
8757      *
8758      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8759      * be wildcarded. AArch64 registers are always considered to be 64
8760      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8761      * the register, if any.
8762      */
8763     int crm, opc1, opc2;
8764     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8765     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8766     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8767     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8768     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8769     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8770     CPState state;
8771 
8772     /* 64 bit registers have only CRm and Opc1 fields */
8773     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8774     /* op0 only exists in the AArch64 encodings */
8775     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8776     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8777     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8778     /*
8779      * This API is only for Arm's system coprocessors (14 and 15) or
8780      * (M-profile or v7A-and-earlier only) for implementation defined
8781      * coprocessors in the range 0..7.  Our decode assumes this, since
8782      * 8..13 can be used for other insns including VFP and Neon. See
8783      * valid_cp() in translate.c.  Assert here that we haven't tried
8784      * to use an invalid coprocessor number.
8785      */
8786     switch (r->state) {
8787     case ARM_CP_STATE_BOTH:
8788         /* 0 has a special meaning, but otherwise the same rules as AA32. */
8789         if (r->cp == 0) {
8790             break;
8791         }
8792         /* fall through */
8793     case ARM_CP_STATE_AA32:
8794         if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
8795             !arm_feature(&cpu->env, ARM_FEATURE_M)) {
8796             assert(r->cp >= 14 && r->cp <= 15);
8797         } else {
8798             assert(r->cp < 8 || (r->cp >= 14 && r->cp <= 15));
8799         }
8800         break;
8801     case ARM_CP_STATE_AA64:
8802         assert(r->cp == 0 || r->cp == CP_REG_ARM64_SYSREG_CP);
8803         break;
8804     default:
8805         g_assert_not_reached();
8806     }
8807     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8808      * encodes a minimum access level for the register. We roll this
8809      * runtime check into our general permission check code, so check
8810      * here that the reginfo's specified permissions are strict enough
8811      * to encompass the generic architectural permission check.
8812      */
8813     if (r->state != ARM_CP_STATE_AA32) {
8814         CPAccessRights mask;
8815         switch (r->opc1) {
8816         case 0:
8817             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8818             mask = PL0U_R | PL1_RW;
8819             break;
8820         case 1: case 2:
8821             /* min_EL EL1 */
8822             mask = PL1_RW;
8823             break;
8824         case 3:
8825             /* min_EL EL0 */
8826             mask = PL0_RW;
8827             break;
8828         case 4:
8829         case 5:
8830             /* min_EL EL2 */
8831             mask = PL2_RW;
8832             break;
8833         case 6:
8834             /* min_EL EL3 */
8835             mask = PL3_RW;
8836             break;
8837         case 7:
8838             /* min_EL EL1, secure mode only (we don't check the latter) */
8839             mask = PL1_RW;
8840             break;
8841         default:
8842             /* broken reginfo with out-of-range opc1 */
8843             g_assert_not_reached();
8844         }
8845         /* assert our permissions are not too lax (stricter is fine) */
8846         assert((r->access & ~mask) == 0);
8847     }
8848 
8849     /* Check that the register definition has enough info to handle
8850      * reads and writes if they are permitted.
8851      */
8852     if (!(r->type & (ARM_CP_SPECIAL_MASK | ARM_CP_CONST))) {
8853         if (r->access & PL3_R) {
8854             assert((r->fieldoffset ||
8855                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8856                    r->readfn);
8857         }
8858         if (r->access & PL3_W) {
8859             assert((r->fieldoffset ||
8860                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8861                    r->writefn);
8862         }
8863     }
8864 
8865     for (crm = crmmin; crm <= crmmax; crm++) {
8866         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8867             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8868                 for (state = ARM_CP_STATE_AA32;
8869                      state <= ARM_CP_STATE_AA64; state++) {
8870                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8871                         continue;
8872                     }
8873                     if (state == ARM_CP_STATE_AA32) {
8874                         /* Under AArch32 CP registers can be common
8875                          * (same for secure and non-secure world) or banked.
8876                          */
8877                         char *name;
8878 
8879                         switch (r->secure) {
8880                         case ARM_CP_SECSTATE_S:
8881                         case ARM_CP_SECSTATE_NS:
8882                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8883                                                    r->secure, crm, opc1, opc2,
8884                                                    r->name);
8885                             break;
8886                         case ARM_CP_SECSTATE_BOTH:
8887                             name = g_strdup_printf("%s_S", r->name);
8888                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8889                                                    ARM_CP_SECSTATE_S,
8890                                                    crm, opc1, opc2, name);
8891                             g_free(name);
8892                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8893                                                    ARM_CP_SECSTATE_NS,
8894                                                    crm, opc1, opc2, r->name);
8895                             break;
8896                         default:
8897                             g_assert_not_reached();
8898                         }
8899                     } else {
8900                         /* AArch64 registers get mapped to non-secure instance
8901                          * of AArch32 */
8902                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8903                                                ARM_CP_SECSTATE_NS,
8904                                                crm, opc1, opc2, r->name);
8905                     }
8906                 }
8907             }
8908         }
8909     }
8910 }
8911 
8912 /* Define a whole list of registers */
8913 void define_arm_cp_regs_with_opaque_len(ARMCPU *cpu, const ARMCPRegInfo *regs,
8914                                         void *opaque, size_t len)
8915 {
8916     size_t i;
8917     for (i = 0; i < len; ++i) {
8918         define_one_arm_cp_reg_with_opaque(cpu, regs + i, opaque);
8919     }
8920 }
8921 
8922 /*
8923  * Modify ARMCPRegInfo for access from userspace.
8924  *
8925  * This is a data driven modification directed by
8926  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8927  * user-space cannot alter any values and dynamic values pertaining to
8928  * execution state are hidden from user space view anyway.
8929  */
8930 void modify_arm_cp_regs_with_len(ARMCPRegInfo *regs, size_t regs_len,
8931                                  const ARMCPRegUserSpaceInfo *mods,
8932                                  size_t mods_len)
8933 {
8934     for (size_t mi = 0; mi < mods_len; ++mi) {
8935         const ARMCPRegUserSpaceInfo *m = mods + mi;
8936         GPatternSpec *pat = NULL;
8937 
8938         if (m->is_glob) {
8939             pat = g_pattern_spec_new(m->name);
8940         }
8941         for (size_t ri = 0; ri < regs_len; ++ri) {
8942             ARMCPRegInfo *r = regs + ri;
8943 
8944             if (pat && g_pattern_match_string(pat, r->name)) {
8945                 r->type = ARM_CP_CONST;
8946                 r->access = PL0U_R;
8947                 r->resetvalue = 0;
8948                 /* continue */
8949             } else if (strcmp(r->name, m->name) == 0) {
8950                 r->type = ARM_CP_CONST;
8951                 r->access = PL0U_R;
8952                 r->resetvalue &= m->exported_bits;
8953                 r->resetvalue |= m->fixed_bits;
8954                 break;
8955             }
8956         }
8957         if (pat) {
8958             g_pattern_spec_free(pat);
8959         }
8960     }
8961 }
8962 
8963 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8964 {
8965     return g_hash_table_lookup(cpregs, (gpointer)(uintptr_t)encoded_cp);
8966 }
8967 
8968 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8969                          uint64_t value)
8970 {
8971     /* Helper coprocessor write function for write-ignore registers */
8972 }
8973 
8974 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8975 {
8976     /* Helper coprocessor write function for read-as-zero registers */
8977     return 0;
8978 }
8979 
8980 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8981 {
8982     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8983 }
8984 
8985 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8986 {
8987     /* Return true if it is not valid for us to switch to
8988      * this CPU mode (ie all the UNPREDICTABLE cases in
8989      * the ARM ARM CPSRWriteByInstr pseudocode).
8990      */
8991 
8992     /* Changes to or from Hyp via MSR and CPS are illegal. */
8993     if (write_type == CPSRWriteByInstr &&
8994         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8995          mode == ARM_CPU_MODE_HYP)) {
8996         return 1;
8997     }
8998 
8999     switch (mode) {
9000     case ARM_CPU_MODE_USR:
9001         return 0;
9002     case ARM_CPU_MODE_SYS:
9003     case ARM_CPU_MODE_SVC:
9004     case ARM_CPU_MODE_ABT:
9005     case ARM_CPU_MODE_UND:
9006     case ARM_CPU_MODE_IRQ:
9007     case ARM_CPU_MODE_FIQ:
9008         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
9009          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
9010          */
9011         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
9012          * and CPS are treated as illegal mode changes.
9013          */
9014         if (write_type == CPSRWriteByInstr &&
9015             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
9016             (arm_hcr_el2_eff(env) & HCR_TGE)) {
9017             return 1;
9018         }
9019         return 0;
9020     case ARM_CPU_MODE_HYP:
9021         return !arm_is_el2_enabled(env) || arm_current_el(env) < 2;
9022     case ARM_CPU_MODE_MON:
9023         return arm_current_el(env) < 3;
9024     default:
9025         return 1;
9026     }
9027 }
9028 
9029 uint32_t cpsr_read(CPUARMState *env)
9030 {
9031     int ZF;
9032     ZF = (env->ZF == 0);
9033     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
9034         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
9035         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
9036         | ((env->condexec_bits & 0xfc) << 8)
9037         | (env->GE << 16) | (env->daif & CPSR_AIF);
9038 }
9039 
9040 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
9041                 CPSRWriteType write_type)
9042 {
9043     uint32_t changed_daif;
9044     bool rebuild_hflags = (write_type != CPSRWriteRaw) &&
9045         (mask & (CPSR_M | CPSR_E | CPSR_IL));
9046 
9047     if (mask & CPSR_NZCV) {
9048         env->ZF = (~val) & CPSR_Z;
9049         env->NF = val;
9050         env->CF = (val >> 29) & 1;
9051         env->VF = (val << 3) & 0x80000000;
9052     }
9053     if (mask & CPSR_Q)
9054         env->QF = ((val & CPSR_Q) != 0);
9055     if (mask & CPSR_T)
9056         env->thumb = ((val & CPSR_T) != 0);
9057     if (mask & CPSR_IT_0_1) {
9058         env->condexec_bits &= ~3;
9059         env->condexec_bits |= (val >> 25) & 3;
9060     }
9061     if (mask & CPSR_IT_2_7) {
9062         env->condexec_bits &= 3;
9063         env->condexec_bits |= (val >> 8) & 0xfc;
9064     }
9065     if (mask & CPSR_GE) {
9066         env->GE = (val >> 16) & 0xf;
9067     }
9068 
9069     /* In a V7 implementation that includes the security extensions but does
9070      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
9071      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
9072      * bits respectively.
9073      *
9074      * In a V8 implementation, it is permitted for privileged software to
9075      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
9076      */
9077     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
9078         arm_feature(env, ARM_FEATURE_EL3) &&
9079         !arm_feature(env, ARM_FEATURE_EL2) &&
9080         !arm_is_secure(env)) {
9081 
9082         changed_daif = (env->daif ^ val) & mask;
9083 
9084         if (changed_daif & CPSR_A) {
9085             /* Check to see if we are allowed to change the masking of async
9086              * abort exceptions from a non-secure state.
9087              */
9088             if (!(env->cp15.scr_el3 & SCR_AW)) {
9089                 qemu_log_mask(LOG_GUEST_ERROR,
9090                               "Ignoring attempt to switch CPSR_A flag from "
9091                               "non-secure world with SCR.AW bit clear\n");
9092                 mask &= ~CPSR_A;
9093             }
9094         }
9095 
9096         if (changed_daif & CPSR_F) {
9097             /* Check to see if we are allowed to change the masking of FIQ
9098              * exceptions from a non-secure state.
9099              */
9100             if (!(env->cp15.scr_el3 & SCR_FW)) {
9101                 qemu_log_mask(LOG_GUEST_ERROR,
9102                               "Ignoring attempt to switch CPSR_F flag from "
9103                               "non-secure world with SCR.FW bit clear\n");
9104                 mask &= ~CPSR_F;
9105             }
9106 
9107             /* Check whether non-maskable FIQ (NMFI) support is enabled.
9108              * If this bit is set software is not allowed to mask
9109              * FIQs, but is allowed to set CPSR_F to 0.
9110              */
9111             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
9112                 (val & CPSR_F)) {
9113                 qemu_log_mask(LOG_GUEST_ERROR,
9114                               "Ignoring attempt to enable CPSR_F flag "
9115                               "(non-maskable FIQ [NMFI] support enabled)\n");
9116                 mask &= ~CPSR_F;
9117             }
9118         }
9119     }
9120 
9121     env->daif &= ~(CPSR_AIF & mask);
9122     env->daif |= val & CPSR_AIF & mask;
9123 
9124     if (write_type != CPSRWriteRaw &&
9125         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
9126         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
9127             /* Note that we can only get here in USR mode if this is a
9128              * gdb stub write; for this case we follow the architectural
9129              * behaviour for guest writes in USR mode of ignoring an attempt
9130              * to switch mode. (Those are caught by translate.c for writes
9131              * triggered by guest instructions.)
9132              */
9133             mask &= ~CPSR_M;
9134         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
9135             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
9136              * v7, and has defined behaviour in v8:
9137              *  + leave CPSR.M untouched
9138              *  + allow changes to the other CPSR fields
9139              *  + set PSTATE.IL
9140              * For user changes via the GDB stub, we don't set PSTATE.IL,
9141              * as this would be unnecessarily harsh for a user error.
9142              */
9143             mask &= ~CPSR_M;
9144             if (write_type != CPSRWriteByGDBStub &&
9145                 arm_feature(env, ARM_FEATURE_V8)) {
9146                 mask |= CPSR_IL;
9147                 val |= CPSR_IL;
9148             }
9149             qemu_log_mask(LOG_GUEST_ERROR,
9150                           "Illegal AArch32 mode switch attempt from %s to %s\n",
9151                           aarch32_mode_name(env->uncached_cpsr),
9152                           aarch32_mode_name(val));
9153         } else {
9154             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
9155                           write_type == CPSRWriteExceptionReturn ?
9156                           "Exception return from AArch32" :
9157                           "AArch32 mode switch from",
9158                           aarch32_mode_name(env->uncached_cpsr),
9159                           aarch32_mode_name(val), env->regs[15]);
9160             switch_mode(env, val & CPSR_M);
9161         }
9162     }
9163     mask &= ~CACHED_CPSR_BITS;
9164     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
9165     if (rebuild_hflags) {
9166         arm_rebuild_hflags(env);
9167     }
9168 }
9169 
9170 /* Sign/zero extend */
9171 uint32_t HELPER(sxtb16)(uint32_t x)
9172 {
9173     uint32_t res;
9174     res = (uint16_t)(int8_t)x;
9175     res |= (uint32_t)(int8_t)(x >> 16) << 16;
9176     return res;
9177 }
9178 
9179 static void handle_possible_div0_trap(CPUARMState *env, uintptr_t ra)
9180 {
9181     /*
9182      * Take a division-by-zero exception if necessary; otherwise return
9183      * to get the usual non-trapping division behaviour (result of 0)
9184      */
9185     if (arm_feature(env, ARM_FEATURE_M)
9186         && (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_DIV_0_TRP_MASK)) {
9187         raise_exception_ra(env, EXCP_DIVBYZERO, 0, 1, ra);
9188     }
9189 }
9190 
9191 uint32_t HELPER(uxtb16)(uint32_t x)
9192 {
9193     uint32_t res;
9194     res = (uint16_t)(uint8_t)x;
9195     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
9196     return res;
9197 }
9198 
9199 int32_t HELPER(sdiv)(CPUARMState *env, int32_t num, int32_t den)
9200 {
9201     if (den == 0) {
9202         handle_possible_div0_trap(env, GETPC());
9203         return 0;
9204     }
9205     if (num == INT_MIN && den == -1) {
9206         return INT_MIN;
9207     }
9208     return num / den;
9209 }
9210 
9211 uint32_t HELPER(udiv)(CPUARMState *env, uint32_t num, uint32_t den)
9212 {
9213     if (den == 0) {
9214         handle_possible_div0_trap(env, GETPC());
9215         return 0;
9216     }
9217     return num / den;
9218 }
9219 
9220 uint32_t HELPER(rbit)(uint32_t x)
9221 {
9222     return revbit32(x);
9223 }
9224 
9225 #ifdef CONFIG_USER_ONLY
9226 
9227 static void switch_mode(CPUARMState *env, int mode)
9228 {
9229     ARMCPU *cpu = env_archcpu(env);
9230 
9231     if (mode != ARM_CPU_MODE_USR) {
9232         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
9233     }
9234 }
9235 
9236 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9237                                  uint32_t cur_el, bool secure)
9238 {
9239     return 1;
9240 }
9241 
9242 void aarch64_sync_64_to_32(CPUARMState *env)
9243 {
9244     g_assert_not_reached();
9245 }
9246 
9247 #else
9248 
9249 static void switch_mode(CPUARMState *env, int mode)
9250 {
9251     int old_mode;
9252     int i;
9253 
9254     old_mode = env->uncached_cpsr & CPSR_M;
9255     if (mode == old_mode)
9256         return;
9257 
9258     if (old_mode == ARM_CPU_MODE_FIQ) {
9259         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
9260         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
9261     } else if (mode == ARM_CPU_MODE_FIQ) {
9262         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
9263         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
9264     }
9265 
9266     i = bank_number(old_mode);
9267     env->banked_r13[i] = env->regs[13];
9268     env->banked_spsr[i] = env->spsr;
9269 
9270     i = bank_number(mode);
9271     env->regs[13] = env->banked_r13[i];
9272     env->spsr = env->banked_spsr[i];
9273 
9274     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
9275     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
9276 }
9277 
9278 /* Physical Interrupt Target EL Lookup Table
9279  *
9280  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
9281  *
9282  * The below multi-dimensional table is used for looking up the target
9283  * exception level given numerous condition criteria.  Specifically, the
9284  * target EL is based on SCR and HCR routing controls as well as the
9285  * currently executing EL and secure state.
9286  *
9287  *    Dimensions:
9288  *    target_el_table[2][2][2][2][2][4]
9289  *                    |  |  |  |  |  +--- Current EL
9290  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
9291  *                    |  |  |  +--------- HCR mask override
9292  *                    |  |  +------------ SCR exec state control
9293  *                    |  +--------------- SCR mask override
9294  *                    +------------------ 32-bit(0)/64-bit(1) EL3
9295  *
9296  *    The table values are as such:
9297  *    0-3 = EL0-EL3
9298  *     -1 = Cannot occur
9299  *
9300  * The ARM ARM target EL table includes entries indicating that an "exception
9301  * is not taken".  The two cases where this is applicable are:
9302  *    1) An exception is taken from EL3 but the SCR does not have the exception
9303  *    routed to EL3.
9304  *    2) An exception is taken from EL2 but the HCR does not have the exception
9305  *    routed to EL2.
9306  * In these two cases, the below table contain a target of EL1.  This value is
9307  * returned as it is expected that the consumer of the table data will check
9308  * for "target EL >= current EL" to ensure the exception is not taken.
9309  *
9310  *            SCR     HCR
9311  *         64  EA     AMO                 From
9312  *        BIT IRQ     IMO      Non-secure         Secure
9313  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
9314  */
9315 static const int8_t target_el_table[2][2][2][2][2][4] = {
9316     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9317        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
9318       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9319        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
9320      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9321        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
9322       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9323        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
9324     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
9325        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 2,  2, -1,  1 },},},
9326       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1,  1,  1 },},
9327        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 2,  2,  2,  1 },},},},
9328      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
9329        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
9330       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},
9331        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},},},},
9332 };
9333 
9334 /*
9335  * Determine the target EL for physical exceptions
9336  */
9337 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9338                                  uint32_t cur_el, bool secure)
9339 {
9340     CPUARMState *env = cs->env_ptr;
9341     bool rw;
9342     bool scr;
9343     bool hcr;
9344     int target_el;
9345     /* Is the highest EL AArch64? */
9346     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
9347     uint64_t hcr_el2;
9348 
9349     if (arm_feature(env, ARM_FEATURE_EL3)) {
9350         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
9351     } else {
9352         /* Either EL2 is the highest EL (and so the EL2 register width
9353          * is given by is64); or there is no EL2 or EL3, in which case
9354          * the value of 'rw' does not affect the table lookup anyway.
9355          */
9356         rw = is64;
9357     }
9358 
9359     hcr_el2 = arm_hcr_el2_eff(env);
9360     switch (excp_idx) {
9361     case EXCP_IRQ:
9362         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
9363         hcr = hcr_el2 & HCR_IMO;
9364         break;
9365     case EXCP_FIQ:
9366         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
9367         hcr = hcr_el2 & HCR_FMO;
9368         break;
9369     default:
9370         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
9371         hcr = hcr_el2 & HCR_AMO;
9372         break;
9373     };
9374 
9375     /*
9376      * For these purposes, TGE and AMO/IMO/FMO both force the
9377      * interrupt to EL2.  Fold TGE into the bit extracted above.
9378      */
9379     hcr |= (hcr_el2 & HCR_TGE) != 0;
9380 
9381     /* Perform a table-lookup for the target EL given the current state */
9382     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
9383 
9384     assert(target_el > 0);
9385 
9386     return target_el;
9387 }
9388 
9389 void arm_log_exception(CPUState *cs)
9390 {
9391     int idx = cs->exception_index;
9392 
9393     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9394         const char *exc = NULL;
9395         static const char * const excnames[] = {
9396             [EXCP_UDEF] = "Undefined Instruction",
9397             [EXCP_SWI] = "SVC",
9398             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9399             [EXCP_DATA_ABORT] = "Data Abort",
9400             [EXCP_IRQ] = "IRQ",
9401             [EXCP_FIQ] = "FIQ",
9402             [EXCP_BKPT] = "Breakpoint",
9403             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9404             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9405             [EXCP_HVC] = "Hypervisor Call",
9406             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9407             [EXCP_SMC] = "Secure Monitor Call",
9408             [EXCP_VIRQ] = "Virtual IRQ",
9409             [EXCP_VFIQ] = "Virtual FIQ",
9410             [EXCP_SEMIHOST] = "Semihosting call",
9411             [EXCP_NOCP] = "v7M NOCP UsageFault",
9412             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9413             [EXCP_STKOF] = "v8M STKOF UsageFault",
9414             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9415             [EXCP_LSERR] = "v8M LSERR UsageFault",
9416             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9417             [EXCP_DIVBYZERO] = "v7M DIVBYZERO UsageFault",
9418             [EXCP_VSERR] = "Virtual SERR",
9419         };
9420 
9421         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9422             exc = excnames[idx];
9423         }
9424         if (!exc) {
9425             exc = "unknown";
9426         }
9427         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s] on CPU %d\n",
9428                       idx, exc, cs->cpu_index);
9429     }
9430 }
9431 
9432 /*
9433  * Function used to synchronize QEMU's AArch64 register set with AArch32
9434  * register set.  This is necessary when switching between AArch32 and AArch64
9435  * execution state.
9436  */
9437 void aarch64_sync_32_to_64(CPUARMState *env)
9438 {
9439     int i;
9440     uint32_t mode = env->uncached_cpsr & CPSR_M;
9441 
9442     /* We can blanket copy R[0:7] to X[0:7] */
9443     for (i = 0; i < 8; i++) {
9444         env->xregs[i] = env->regs[i];
9445     }
9446 
9447     /*
9448      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9449      * Otherwise, they come from the banked user regs.
9450      */
9451     if (mode == ARM_CPU_MODE_FIQ) {
9452         for (i = 8; i < 13; i++) {
9453             env->xregs[i] = env->usr_regs[i - 8];
9454         }
9455     } else {
9456         for (i = 8; i < 13; i++) {
9457             env->xregs[i] = env->regs[i];
9458         }
9459     }
9460 
9461     /*
9462      * Registers x13-x23 are the various mode SP and FP registers. Registers
9463      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9464      * from the mode banked register.
9465      */
9466     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9467         env->xregs[13] = env->regs[13];
9468         env->xregs[14] = env->regs[14];
9469     } else {
9470         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9471         /* HYP is an exception in that it is copied from r14 */
9472         if (mode == ARM_CPU_MODE_HYP) {
9473             env->xregs[14] = env->regs[14];
9474         } else {
9475             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9476         }
9477     }
9478 
9479     if (mode == ARM_CPU_MODE_HYP) {
9480         env->xregs[15] = env->regs[13];
9481     } else {
9482         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9483     }
9484 
9485     if (mode == ARM_CPU_MODE_IRQ) {
9486         env->xregs[16] = env->regs[14];
9487         env->xregs[17] = env->regs[13];
9488     } else {
9489         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9490         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9491     }
9492 
9493     if (mode == ARM_CPU_MODE_SVC) {
9494         env->xregs[18] = env->regs[14];
9495         env->xregs[19] = env->regs[13];
9496     } else {
9497         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9498         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9499     }
9500 
9501     if (mode == ARM_CPU_MODE_ABT) {
9502         env->xregs[20] = env->regs[14];
9503         env->xregs[21] = env->regs[13];
9504     } else {
9505         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9506         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9507     }
9508 
9509     if (mode == ARM_CPU_MODE_UND) {
9510         env->xregs[22] = env->regs[14];
9511         env->xregs[23] = env->regs[13];
9512     } else {
9513         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9514         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9515     }
9516 
9517     /*
9518      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9519      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9520      * FIQ bank for r8-r14.
9521      */
9522     if (mode == ARM_CPU_MODE_FIQ) {
9523         for (i = 24; i < 31; i++) {
9524             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9525         }
9526     } else {
9527         for (i = 24; i < 29; i++) {
9528             env->xregs[i] = env->fiq_regs[i - 24];
9529         }
9530         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9531         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9532     }
9533 
9534     env->pc = env->regs[15];
9535 }
9536 
9537 /*
9538  * Function used to synchronize QEMU's AArch32 register set with AArch64
9539  * register set.  This is necessary when switching between AArch32 and AArch64
9540  * execution state.
9541  */
9542 void aarch64_sync_64_to_32(CPUARMState *env)
9543 {
9544     int i;
9545     uint32_t mode = env->uncached_cpsr & CPSR_M;
9546 
9547     /* We can blanket copy X[0:7] to R[0:7] */
9548     for (i = 0; i < 8; i++) {
9549         env->regs[i] = env->xregs[i];
9550     }
9551 
9552     /*
9553      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9554      * Otherwise, we copy x8-x12 into the banked user regs.
9555      */
9556     if (mode == ARM_CPU_MODE_FIQ) {
9557         for (i = 8; i < 13; i++) {
9558             env->usr_regs[i - 8] = env->xregs[i];
9559         }
9560     } else {
9561         for (i = 8; i < 13; i++) {
9562             env->regs[i] = env->xregs[i];
9563         }
9564     }
9565 
9566     /*
9567      * Registers r13 & r14 depend on the current mode.
9568      * If we are in a given mode, we copy the corresponding x registers to r13
9569      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9570      * for the mode.
9571      */
9572     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9573         env->regs[13] = env->xregs[13];
9574         env->regs[14] = env->xregs[14];
9575     } else {
9576         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9577 
9578         /*
9579          * HYP is an exception in that it does not have its own banked r14 but
9580          * shares the USR r14
9581          */
9582         if (mode == ARM_CPU_MODE_HYP) {
9583             env->regs[14] = env->xregs[14];
9584         } else {
9585             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9586         }
9587     }
9588 
9589     if (mode == ARM_CPU_MODE_HYP) {
9590         env->regs[13] = env->xregs[15];
9591     } else {
9592         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9593     }
9594 
9595     if (mode == ARM_CPU_MODE_IRQ) {
9596         env->regs[14] = env->xregs[16];
9597         env->regs[13] = env->xregs[17];
9598     } else {
9599         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9600         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9601     }
9602 
9603     if (mode == ARM_CPU_MODE_SVC) {
9604         env->regs[14] = env->xregs[18];
9605         env->regs[13] = env->xregs[19];
9606     } else {
9607         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9608         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9609     }
9610 
9611     if (mode == ARM_CPU_MODE_ABT) {
9612         env->regs[14] = env->xregs[20];
9613         env->regs[13] = env->xregs[21];
9614     } else {
9615         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9616         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9617     }
9618 
9619     if (mode == ARM_CPU_MODE_UND) {
9620         env->regs[14] = env->xregs[22];
9621         env->regs[13] = env->xregs[23];
9622     } else {
9623         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9624         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9625     }
9626 
9627     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9628      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9629      * FIQ bank for r8-r14.
9630      */
9631     if (mode == ARM_CPU_MODE_FIQ) {
9632         for (i = 24; i < 31; i++) {
9633             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9634         }
9635     } else {
9636         for (i = 24; i < 29; i++) {
9637             env->fiq_regs[i - 24] = env->xregs[i];
9638         }
9639         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9640         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9641     }
9642 
9643     env->regs[15] = env->pc;
9644 }
9645 
9646 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9647                                    uint32_t mask, uint32_t offset,
9648                                    uint32_t newpc)
9649 {
9650     int new_el;
9651 
9652     /* Change the CPU state so as to actually take the exception. */
9653     switch_mode(env, new_mode);
9654 
9655     /*
9656      * For exceptions taken to AArch32 we must clear the SS bit in both
9657      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9658      */
9659     env->pstate &= ~PSTATE_SS;
9660     env->spsr = cpsr_read(env);
9661     /* Clear IT bits.  */
9662     env->condexec_bits = 0;
9663     /* Switch to the new mode, and to the correct instruction set.  */
9664     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9665 
9666     /* This must be after mode switching. */
9667     new_el = arm_current_el(env);
9668 
9669     /* Set new mode endianness */
9670     env->uncached_cpsr &= ~CPSR_E;
9671     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9672         env->uncached_cpsr |= CPSR_E;
9673     }
9674     /* J and IL must always be cleared for exception entry */
9675     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9676     env->daif |= mask;
9677 
9678     if (cpu_isar_feature(aa32_ssbs, env_archcpu(env))) {
9679         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_32) {
9680             env->uncached_cpsr |= CPSR_SSBS;
9681         } else {
9682             env->uncached_cpsr &= ~CPSR_SSBS;
9683         }
9684     }
9685 
9686     if (new_mode == ARM_CPU_MODE_HYP) {
9687         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9688         env->elr_el[2] = env->regs[15];
9689     } else {
9690         /* CPSR.PAN is normally preserved preserved unless...  */
9691         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9692             switch (new_el) {
9693             case 3:
9694                 if (!arm_is_secure_below_el3(env)) {
9695                     /* ... the target is EL3, from non-secure state.  */
9696                     env->uncached_cpsr &= ~CPSR_PAN;
9697                     break;
9698                 }
9699                 /* ... the target is EL3, from secure state ... */
9700                 /* fall through */
9701             case 1:
9702                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9703                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9704                     env->uncached_cpsr |= CPSR_PAN;
9705                 }
9706                 break;
9707             }
9708         }
9709         /*
9710          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9711          * and we should just guard the thumb mode on V4
9712          */
9713         if (arm_feature(env, ARM_FEATURE_V4T)) {
9714             env->thumb =
9715                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9716         }
9717         env->regs[14] = env->regs[15] + offset;
9718     }
9719     env->regs[15] = newpc;
9720     arm_rebuild_hflags(env);
9721 }
9722 
9723 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9724 {
9725     /*
9726      * Handle exception entry to Hyp mode; this is sufficiently
9727      * different to entry to other AArch32 modes that we handle it
9728      * separately here.
9729      *
9730      * The vector table entry used is always the 0x14 Hyp mode entry point,
9731      * unless this is an UNDEF/SVC/HVC/abort taken from Hyp to Hyp.
9732      * The offset applied to the preferred return address is always zero
9733      * (see DDI0487C.a section G1.12.3).
9734      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9735      */
9736     uint32_t addr, mask;
9737     ARMCPU *cpu = ARM_CPU(cs);
9738     CPUARMState *env = &cpu->env;
9739 
9740     switch (cs->exception_index) {
9741     case EXCP_UDEF:
9742         addr = 0x04;
9743         break;
9744     case EXCP_SWI:
9745         addr = 0x08;
9746         break;
9747     case EXCP_BKPT:
9748         /* Fall through to prefetch abort.  */
9749     case EXCP_PREFETCH_ABORT:
9750         env->cp15.ifar_s = env->exception.vaddress;
9751         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9752                       (uint32_t)env->exception.vaddress);
9753         addr = 0x0c;
9754         break;
9755     case EXCP_DATA_ABORT:
9756         env->cp15.dfar_s = env->exception.vaddress;
9757         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9758                       (uint32_t)env->exception.vaddress);
9759         addr = 0x10;
9760         break;
9761     case EXCP_IRQ:
9762         addr = 0x18;
9763         break;
9764     case EXCP_FIQ:
9765         addr = 0x1c;
9766         break;
9767     case EXCP_HVC:
9768         addr = 0x08;
9769         break;
9770     case EXCP_HYP_TRAP:
9771         addr = 0x14;
9772         break;
9773     default:
9774         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9775     }
9776 
9777     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9778         if (!arm_feature(env, ARM_FEATURE_V8)) {
9779             /*
9780              * QEMU syndrome values are v8-style. v7 has the IL bit
9781              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9782              * If this is a v7 CPU, squash the IL bit in those cases.
9783              */
9784             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9785                 (cs->exception_index == EXCP_DATA_ABORT &&
9786                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9787                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9788                 env->exception.syndrome &= ~ARM_EL_IL;
9789             }
9790         }
9791         env->cp15.esr_el[2] = env->exception.syndrome;
9792     }
9793 
9794     if (arm_current_el(env) != 2 && addr < 0x14) {
9795         addr = 0x14;
9796     }
9797 
9798     mask = 0;
9799     if (!(env->cp15.scr_el3 & SCR_EA)) {
9800         mask |= CPSR_A;
9801     }
9802     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9803         mask |= CPSR_I;
9804     }
9805     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9806         mask |= CPSR_F;
9807     }
9808 
9809     addr += env->cp15.hvbar;
9810 
9811     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9812 }
9813 
9814 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9815 {
9816     ARMCPU *cpu = ARM_CPU(cs);
9817     CPUARMState *env = &cpu->env;
9818     uint32_t addr;
9819     uint32_t mask;
9820     int new_mode;
9821     uint32_t offset;
9822     uint32_t moe;
9823 
9824     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9825     switch (syn_get_ec(env->exception.syndrome)) {
9826     case EC_BREAKPOINT:
9827     case EC_BREAKPOINT_SAME_EL:
9828         moe = 1;
9829         break;
9830     case EC_WATCHPOINT:
9831     case EC_WATCHPOINT_SAME_EL:
9832         moe = 10;
9833         break;
9834     case EC_AA32_BKPT:
9835         moe = 3;
9836         break;
9837     case EC_VECTORCATCH:
9838         moe = 5;
9839         break;
9840     default:
9841         moe = 0;
9842         break;
9843     }
9844 
9845     if (moe) {
9846         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9847     }
9848 
9849     if (env->exception.target_el == 2) {
9850         arm_cpu_do_interrupt_aarch32_hyp(cs);
9851         return;
9852     }
9853 
9854     switch (cs->exception_index) {
9855     case EXCP_UDEF:
9856         new_mode = ARM_CPU_MODE_UND;
9857         addr = 0x04;
9858         mask = CPSR_I;
9859         if (env->thumb)
9860             offset = 2;
9861         else
9862             offset = 4;
9863         break;
9864     case EXCP_SWI:
9865         new_mode = ARM_CPU_MODE_SVC;
9866         addr = 0x08;
9867         mask = CPSR_I;
9868         /* The PC already points to the next instruction.  */
9869         offset = 0;
9870         break;
9871     case EXCP_BKPT:
9872         /* Fall through to prefetch abort.  */
9873     case EXCP_PREFETCH_ABORT:
9874         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9875         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9876         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9877                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9878         new_mode = ARM_CPU_MODE_ABT;
9879         addr = 0x0c;
9880         mask = CPSR_A | CPSR_I;
9881         offset = 4;
9882         break;
9883     case EXCP_DATA_ABORT:
9884         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9885         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9886         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9887                       env->exception.fsr,
9888                       (uint32_t)env->exception.vaddress);
9889         new_mode = ARM_CPU_MODE_ABT;
9890         addr = 0x10;
9891         mask = CPSR_A | CPSR_I;
9892         offset = 8;
9893         break;
9894     case EXCP_IRQ:
9895         new_mode = ARM_CPU_MODE_IRQ;
9896         addr = 0x18;
9897         /* Disable IRQ and imprecise data aborts.  */
9898         mask = CPSR_A | CPSR_I;
9899         offset = 4;
9900         if (env->cp15.scr_el3 & SCR_IRQ) {
9901             /* IRQ routed to monitor mode */
9902             new_mode = ARM_CPU_MODE_MON;
9903             mask |= CPSR_F;
9904         }
9905         break;
9906     case EXCP_FIQ:
9907         new_mode = ARM_CPU_MODE_FIQ;
9908         addr = 0x1c;
9909         /* Disable FIQ, IRQ and imprecise data aborts.  */
9910         mask = CPSR_A | CPSR_I | CPSR_F;
9911         if (env->cp15.scr_el3 & SCR_FIQ) {
9912             /* FIQ routed to monitor mode */
9913             new_mode = ARM_CPU_MODE_MON;
9914         }
9915         offset = 4;
9916         break;
9917     case EXCP_VIRQ:
9918         new_mode = ARM_CPU_MODE_IRQ;
9919         addr = 0x18;
9920         /* Disable IRQ and imprecise data aborts.  */
9921         mask = CPSR_A | CPSR_I;
9922         offset = 4;
9923         break;
9924     case EXCP_VFIQ:
9925         new_mode = ARM_CPU_MODE_FIQ;
9926         addr = 0x1c;
9927         /* Disable FIQ, IRQ and imprecise data aborts.  */
9928         mask = CPSR_A | CPSR_I | CPSR_F;
9929         offset = 4;
9930         break;
9931     case EXCP_VSERR:
9932         {
9933             /*
9934              * Note that this is reported as a data abort, but the DFAR
9935              * has an UNKNOWN value.  Construct the SError syndrome from
9936              * AET and ExT fields.
9937              */
9938             ARMMMUFaultInfo fi = { .type = ARMFault_AsyncExternal, };
9939 
9940             if (extended_addresses_enabled(env)) {
9941                 env->exception.fsr = arm_fi_to_lfsc(&fi);
9942             } else {
9943                 env->exception.fsr = arm_fi_to_sfsc(&fi);
9944             }
9945             env->exception.fsr |= env->cp15.vsesr_el2 & 0xd000;
9946             A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9947             qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x\n",
9948                           env->exception.fsr);
9949 
9950             new_mode = ARM_CPU_MODE_ABT;
9951             addr = 0x10;
9952             mask = CPSR_A | CPSR_I;
9953             offset = 8;
9954         }
9955         break;
9956     case EXCP_SMC:
9957         new_mode = ARM_CPU_MODE_MON;
9958         addr = 0x08;
9959         mask = CPSR_A | CPSR_I | CPSR_F;
9960         offset = 0;
9961         break;
9962     default:
9963         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9964         return; /* Never happens.  Keep compiler happy.  */
9965     }
9966 
9967     if (new_mode == ARM_CPU_MODE_MON) {
9968         addr += env->cp15.mvbar;
9969     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9970         /* High vectors. When enabled, base address cannot be remapped. */
9971         addr += 0xffff0000;
9972     } else {
9973         /* ARM v7 architectures provide a vector base address register to remap
9974          * the interrupt vector table.
9975          * This register is only followed in non-monitor mode, and is banked.
9976          * Note: only bits 31:5 are valid.
9977          */
9978         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9979     }
9980 
9981     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9982         env->cp15.scr_el3 &= ~SCR_NS;
9983     }
9984 
9985     take_aarch32_exception(env, new_mode, mask, offset, addr);
9986 }
9987 
9988 static int aarch64_regnum(CPUARMState *env, int aarch32_reg)
9989 {
9990     /*
9991      * Return the register number of the AArch64 view of the AArch32
9992      * register @aarch32_reg. The CPUARMState CPSR is assumed to still
9993      * be that of the AArch32 mode the exception came from.
9994      */
9995     int mode = env->uncached_cpsr & CPSR_M;
9996 
9997     switch (aarch32_reg) {
9998     case 0 ... 7:
9999         return aarch32_reg;
10000     case 8 ... 12:
10001         return mode == ARM_CPU_MODE_FIQ ? aarch32_reg + 16 : aarch32_reg;
10002     case 13:
10003         switch (mode) {
10004         case ARM_CPU_MODE_USR:
10005         case ARM_CPU_MODE_SYS:
10006             return 13;
10007         case ARM_CPU_MODE_HYP:
10008             return 15;
10009         case ARM_CPU_MODE_IRQ:
10010             return 17;
10011         case ARM_CPU_MODE_SVC:
10012             return 19;
10013         case ARM_CPU_MODE_ABT:
10014             return 21;
10015         case ARM_CPU_MODE_UND:
10016             return 23;
10017         case ARM_CPU_MODE_FIQ:
10018             return 29;
10019         default:
10020             g_assert_not_reached();
10021         }
10022     case 14:
10023         switch (mode) {
10024         case ARM_CPU_MODE_USR:
10025         case ARM_CPU_MODE_SYS:
10026         case ARM_CPU_MODE_HYP:
10027             return 14;
10028         case ARM_CPU_MODE_IRQ:
10029             return 16;
10030         case ARM_CPU_MODE_SVC:
10031             return 18;
10032         case ARM_CPU_MODE_ABT:
10033             return 20;
10034         case ARM_CPU_MODE_UND:
10035             return 22;
10036         case ARM_CPU_MODE_FIQ:
10037             return 30;
10038         default:
10039             g_assert_not_reached();
10040         }
10041     case 15:
10042         return 31;
10043     default:
10044         g_assert_not_reached();
10045     }
10046 }
10047 
10048 static uint32_t cpsr_read_for_spsr_elx(CPUARMState *env)
10049 {
10050     uint32_t ret = cpsr_read(env);
10051 
10052     /* Move DIT to the correct location for SPSR_ELx */
10053     if (ret & CPSR_DIT) {
10054         ret &= ~CPSR_DIT;
10055         ret |= PSTATE_DIT;
10056     }
10057     /* Merge PSTATE.SS into SPSR_ELx */
10058     ret |= env->pstate & PSTATE_SS;
10059 
10060     return ret;
10061 }
10062 
10063 /* Handle exception entry to a target EL which is using AArch64 */
10064 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
10065 {
10066     ARMCPU *cpu = ARM_CPU(cs);
10067     CPUARMState *env = &cpu->env;
10068     unsigned int new_el = env->exception.target_el;
10069     target_ulong addr = env->cp15.vbar_el[new_el];
10070     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
10071     unsigned int old_mode;
10072     unsigned int cur_el = arm_current_el(env);
10073     int rt;
10074 
10075     /*
10076      * Note that new_el can never be 0.  If cur_el is 0, then
10077      * el0_a64 is is_a64(), else el0_a64 is ignored.
10078      */
10079     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
10080 
10081     if (cur_el < new_el) {
10082         /* Entry vector offset depends on whether the implemented EL
10083          * immediately lower than the target level is using AArch32 or AArch64
10084          */
10085         bool is_aa64;
10086         uint64_t hcr;
10087 
10088         switch (new_el) {
10089         case 3:
10090             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
10091             break;
10092         case 2:
10093             hcr = arm_hcr_el2_eff(env);
10094             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
10095                 is_aa64 = (hcr & HCR_RW) != 0;
10096                 break;
10097             }
10098             /* fall through */
10099         case 1:
10100             is_aa64 = is_a64(env);
10101             break;
10102         default:
10103             g_assert_not_reached();
10104         }
10105 
10106         if (is_aa64) {
10107             addr += 0x400;
10108         } else {
10109             addr += 0x600;
10110         }
10111     } else if (pstate_read(env) & PSTATE_SP) {
10112         addr += 0x200;
10113     }
10114 
10115     switch (cs->exception_index) {
10116     case EXCP_PREFETCH_ABORT:
10117     case EXCP_DATA_ABORT:
10118         env->cp15.far_el[new_el] = env->exception.vaddress;
10119         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
10120                       env->cp15.far_el[new_el]);
10121         /* fall through */
10122     case EXCP_BKPT:
10123     case EXCP_UDEF:
10124     case EXCP_SWI:
10125     case EXCP_HVC:
10126     case EXCP_HYP_TRAP:
10127     case EXCP_SMC:
10128         switch (syn_get_ec(env->exception.syndrome)) {
10129         case EC_ADVSIMDFPACCESSTRAP:
10130             /*
10131              * QEMU internal FP/SIMD syndromes from AArch32 include the
10132              * TA and coproc fields which are only exposed if the exception
10133              * is taken to AArch32 Hyp mode. Mask them out to get a valid
10134              * AArch64 format syndrome.
10135              */
10136             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
10137             break;
10138         case EC_CP14RTTRAP:
10139         case EC_CP15RTTRAP:
10140         case EC_CP14DTTRAP:
10141             /*
10142              * For a trap on AArch32 MRC/MCR/LDC/STC the Rt field is currently
10143              * the raw register field from the insn; when taking this to
10144              * AArch64 we must convert it to the AArch64 view of the register
10145              * number. Notice that we read a 4-bit AArch32 register number and
10146              * write back a 5-bit AArch64 one.
10147              */
10148             rt = extract32(env->exception.syndrome, 5, 4);
10149             rt = aarch64_regnum(env, rt);
10150             env->exception.syndrome = deposit32(env->exception.syndrome,
10151                                                 5, 5, rt);
10152             break;
10153         case EC_CP15RRTTRAP:
10154         case EC_CP14RRTTRAP:
10155             /* Similarly for MRRC/MCRR traps for Rt and Rt2 fields */
10156             rt = extract32(env->exception.syndrome, 5, 4);
10157             rt = aarch64_regnum(env, rt);
10158             env->exception.syndrome = deposit32(env->exception.syndrome,
10159                                                 5, 5, rt);
10160             rt = extract32(env->exception.syndrome, 10, 4);
10161             rt = aarch64_regnum(env, rt);
10162             env->exception.syndrome = deposit32(env->exception.syndrome,
10163                                                 10, 5, rt);
10164             break;
10165         }
10166         env->cp15.esr_el[new_el] = env->exception.syndrome;
10167         break;
10168     case EXCP_IRQ:
10169     case EXCP_VIRQ:
10170         addr += 0x80;
10171         break;
10172     case EXCP_FIQ:
10173     case EXCP_VFIQ:
10174         addr += 0x100;
10175         break;
10176     case EXCP_VSERR:
10177         addr += 0x180;
10178         /* Construct the SError syndrome from IDS and ISS fields. */
10179         env->exception.syndrome = syn_serror(env->cp15.vsesr_el2 & 0x1ffffff);
10180         env->cp15.esr_el[new_el] = env->exception.syndrome;
10181         break;
10182     default:
10183         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10184     }
10185 
10186     if (is_a64(env)) {
10187         old_mode = pstate_read(env);
10188         aarch64_save_sp(env, arm_current_el(env));
10189         env->elr_el[new_el] = env->pc;
10190     } else {
10191         old_mode = cpsr_read_for_spsr_elx(env);
10192         env->elr_el[new_el] = env->regs[15];
10193 
10194         aarch64_sync_32_to_64(env);
10195 
10196         env->condexec_bits = 0;
10197     }
10198     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
10199 
10200     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
10201                   env->elr_el[new_el]);
10202 
10203     if (cpu_isar_feature(aa64_pan, cpu)) {
10204         /* The value of PSTATE.PAN is normally preserved, except when ... */
10205         new_mode |= old_mode & PSTATE_PAN;
10206         switch (new_el) {
10207         case 2:
10208             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
10209             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
10210                 != (HCR_E2H | HCR_TGE)) {
10211                 break;
10212             }
10213             /* fall through */
10214         case 1:
10215             /* ... the target is EL1 ... */
10216             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
10217             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
10218                 new_mode |= PSTATE_PAN;
10219             }
10220             break;
10221         }
10222     }
10223     if (cpu_isar_feature(aa64_mte, cpu)) {
10224         new_mode |= PSTATE_TCO;
10225     }
10226 
10227     if (cpu_isar_feature(aa64_ssbs, cpu)) {
10228         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_64) {
10229             new_mode |= PSTATE_SSBS;
10230         } else {
10231             new_mode &= ~PSTATE_SSBS;
10232         }
10233     }
10234 
10235     pstate_write(env, PSTATE_DAIF | new_mode);
10236     env->aarch64 = true;
10237     aarch64_restore_sp(env, new_el);
10238     helper_rebuild_hflags_a64(env, new_el);
10239 
10240     env->pc = addr;
10241 
10242     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10243                   new_el, env->pc, pstate_read(env));
10244 }
10245 
10246 /*
10247  * Do semihosting call and set the appropriate return value. All the
10248  * permission and validity checks have been done at translate time.
10249  *
10250  * We only see semihosting exceptions in TCG only as they are not
10251  * trapped to the hypervisor in KVM.
10252  */
10253 #ifdef CONFIG_TCG
10254 static void handle_semihosting(CPUState *cs)
10255 {
10256     ARMCPU *cpu = ARM_CPU(cs);
10257     CPUARMState *env = &cpu->env;
10258 
10259     if (is_a64(env)) {
10260         qemu_log_mask(CPU_LOG_INT,
10261                       "...handling as semihosting call 0x%" PRIx64 "\n",
10262                       env->xregs[0]);
10263         env->xregs[0] = do_common_semihosting(cs);
10264         env->pc += 4;
10265     } else {
10266         qemu_log_mask(CPU_LOG_INT,
10267                       "...handling as semihosting call 0x%x\n",
10268                       env->regs[0]);
10269         env->regs[0] = do_common_semihosting(cs);
10270         env->regs[15] += env->thumb ? 2 : 4;
10271     }
10272 }
10273 #endif
10274 
10275 /* Handle a CPU exception for A and R profile CPUs.
10276  * Do any appropriate logging, handle PSCI calls, and then hand off
10277  * to the AArch64-entry or AArch32-entry function depending on the
10278  * target exception level's register width.
10279  *
10280  * Note: this is used for both TCG (as the do_interrupt tcg op),
10281  *       and KVM to re-inject guest debug exceptions, and to
10282  *       inject a Synchronous-External-Abort.
10283  */
10284 void arm_cpu_do_interrupt(CPUState *cs)
10285 {
10286     ARMCPU *cpu = ARM_CPU(cs);
10287     CPUARMState *env = &cpu->env;
10288     unsigned int new_el = env->exception.target_el;
10289 
10290     assert(!arm_feature(env, ARM_FEATURE_M));
10291 
10292     arm_log_exception(cs);
10293     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10294                   new_el);
10295     if (qemu_loglevel_mask(CPU_LOG_INT)
10296         && !excp_is_internal(cs->exception_index)) {
10297         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10298                       syn_get_ec(env->exception.syndrome),
10299                       env->exception.syndrome);
10300     }
10301 
10302     if (arm_is_psci_call(cpu, cs->exception_index)) {
10303         arm_handle_psci_call(cpu);
10304         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10305         return;
10306     }
10307 
10308     /*
10309      * Semihosting semantics depend on the register width of the code
10310      * that caused the exception, not the target exception level, so
10311      * must be handled here.
10312      */
10313 #ifdef CONFIG_TCG
10314     if (cs->exception_index == EXCP_SEMIHOST) {
10315         handle_semihosting(cs);
10316         return;
10317     }
10318 #endif
10319 
10320     /* Hooks may change global state so BQL should be held, also the
10321      * BQL needs to be held for any modification of
10322      * cs->interrupt_request.
10323      */
10324     g_assert(qemu_mutex_iothread_locked());
10325 
10326     arm_call_pre_el_change_hook(cpu);
10327 
10328     assert(!excp_is_internal(cs->exception_index));
10329     if (arm_el_is_aa64(env, new_el)) {
10330         arm_cpu_do_interrupt_aarch64(cs);
10331     } else {
10332         arm_cpu_do_interrupt_aarch32(cs);
10333     }
10334 
10335     arm_call_el_change_hook(cpu);
10336 
10337     if (!kvm_enabled()) {
10338         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10339     }
10340 }
10341 #endif /* !CONFIG_USER_ONLY */
10342 
10343 uint64_t arm_sctlr(CPUARMState *env, int el)
10344 {
10345     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
10346     if (el == 0) {
10347         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
10348         el = (mmu_idx == ARMMMUIdx_E20_0 || mmu_idx == ARMMMUIdx_SE20_0)
10349              ? 2 : 1;
10350     }
10351     return env->cp15.sctlr_el[el];
10352 }
10353 
10354 /* Return the SCTLR value which controls this address translation regime */
10355 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10356 {
10357     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10358 }
10359 
10360 #ifndef CONFIG_USER_ONLY
10361 
10362 /* Return true if the specified stage of address translation is disabled */
10363 static inline bool regime_translation_disabled(CPUARMState *env,
10364                                                ARMMMUIdx mmu_idx)
10365 {
10366     uint64_t hcr_el2;
10367 
10368     if (arm_feature(env, ARM_FEATURE_M)) {
10369         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10370                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10371         case R_V7M_MPU_CTRL_ENABLE_MASK:
10372             /* Enabled, but not for HardFault and NMI */
10373             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10374         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10375             /* Enabled for all cases */
10376             return false;
10377         case 0:
10378         default:
10379             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10380              * we warned about that in armv7m_nvic.c when the guest set it.
10381              */
10382             return true;
10383         }
10384     }
10385 
10386     hcr_el2 = arm_hcr_el2_eff(env);
10387 
10388     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10389         /* HCR.DC means HCR.VM behaves as 1 */
10390         return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10391     }
10392 
10393     if (hcr_el2 & HCR_TGE) {
10394         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10395         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10396             return true;
10397         }
10398     }
10399 
10400     if ((hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
10401         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10402         return true;
10403     }
10404 
10405     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10406 }
10407 
10408 static inline bool regime_translation_big_endian(CPUARMState *env,
10409                                                  ARMMMUIdx mmu_idx)
10410 {
10411     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10412 }
10413 
10414 /* Return the TTBR associated with this translation regime */
10415 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10416                                    int ttbrn)
10417 {
10418     if (mmu_idx == ARMMMUIdx_Stage2) {
10419         return env->cp15.vttbr_el2;
10420     }
10421     if (mmu_idx == ARMMMUIdx_Stage2_S) {
10422         return env->cp15.vsttbr_el2;
10423     }
10424     if (ttbrn == 0) {
10425         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10426     } else {
10427         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10428     }
10429 }
10430 
10431 #endif /* !CONFIG_USER_ONLY */
10432 
10433 /* Convert a possible stage1+2 MMU index into the appropriate
10434  * stage 1 MMU index
10435  */
10436 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10437 {
10438     switch (mmu_idx) {
10439     case ARMMMUIdx_SE10_0:
10440         return ARMMMUIdx_Stage1_SE0;
10441     case ARMMMUIdx_SE10_1:
10442         return ARMMMUIdx_Stage1_SE1;
10443     case ARMMMUIdx_SE10_1_PAN:
10444         return ARMMMUIdx_Stage1_SE1_PAN;
10445     case ARMMMUIdx_E10_0:
10446         return ARMMMUIdx_Stage1_E0;
10447     case ARMMMUIdx_E10_1:
10448         return ARMMMUIdx_Stage1_E1;
10449     case ARMMMUIdx_E10_1_PAN:
10450         return ARMMMUIdx_Stage1_E1_PAN;
10451     default:
10452         return mmu_idx;
10453     }
10454 }
10455 
10456 /* Return true if the translation regime is using LPAE format page tables */
10457 static inline bool regime_using_lpae_format(CPUARMState *env,
10458                                             ARMMMUIdx mmu_idx)
10459 {
10460     int el = regime_el(env, mmu_idx);
10461     if (el == 2 || arm_el_is_aa64(env, el)) {
10462         return true;
10463     }
10464     if (arm_feature(env, ARM_FEATURE_LPAE)
10465         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10466         return true;
10467     }
10468     return false;
10469 }
10470 
10471 /* Returns true if the stage 1 translation regime is using LPAE format page
10472  * tables. Used when raising alignment exceptions, whose FSR changes depending
10473  * on whether the long or short descriptor format is in use. */
10474 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10475 {
10476     mmu_idx = stage_1_mmu_idx(mmu_idx);
10477 
10478     return regime_using_lpae_format(env, mmu_idx);
10479 }
10480 
10481 #ifndef CONFIG_USER_ONLY
10482 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10483 {
10484     switch (mmu_idx) {
10485     case ARMMMUIdx_SE10_0:
10486     case ARMMMUIdx_E20_0:
10487     case ARMMMUIdx_SE20_0:
10488     case ARMMMUIdx_Stage1_E0:
10489     case ARMMMUIdx_Stage1_SE0:
10490     case ARMMMUIdx_MUser:
10491     case ARMMMUIdx_MSUser:
10492     case ARMMMUIdx_MUserNegPri:
10493     case ARMMMUIdx_MSUserNegPri:
10494         return true;
10495     default:
10496         return false;
10497     case ARMMMUIdx_E10_0:
10498     case ARMMMUIdx_E10_1:
10499     case ARMMMUIdx_E10_1_PAN:
10500         g_assert_not_reached();
10501     }
10502 }
10503 
10504 /* Translate section/page access permissions to page
10505  * R/W protection flags
10506  *
10507  * @env:         CPUARMState
10508  * @mmu_idx:     MMU index indicating required translation regime
10509  * @ap:          The 3-bit access permissions (AP[2:0])
10510  * @domain_prot: The 2-bit domain access permissions
10511  */
10512 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10513                                 int ap, int domain_prot)
10514 {
10515     bool is_user = regime_is_user(env, mmu_idx);
10516 
10517     if (domain_prot == 3) {
10518         return PAGE_READ | PAGE_WRITE;
10519     }
10520 
10521     switch (ap) {
10522     case 0:
10523         if (arm_feature(env, ARM_FEATURE_V7)) {
10524             return 0;
10525         }
10526         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10527         case SCTLR_S:
10528             return is_user ? 0 : PAGE_READ;
10529         case SCTLR_R:
10530             return PAGE_READ;
10531         default:
10532             return 0;
10533         }
10534     case 1:
10535         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10536     case 2:
10537         if (is_user) {
10538             return PAGE_READ;
10539         } else {
10540             return PAGE_READ | PAGE_WRITE;
10541         }
10542     case 3:
10543         return PAGE_READ | PAGE_WRITE;
10544     case 4: /* Reserved.  */
10545         return 0;
10546     case 5:
10547         return is_user ? 0 : PAGE_READ;
10548     case 6:
10549         return PAGE_READ;
10550     case 7:
10551         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10552             return 0;
10553         }
10554         return PAGE_READ;
10555     default:
10556         g_assert_not_reached();
10557     }
10558 }
10559 
10560 /* Translate section/page access permissions to page
10561  * R/W protection flags.
10562  *
10563  * @ap:      The 2-bit simple AP (AP[2:1])
10564  * @is_user: TRUE if accessing from PL0
10565  */
10566 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10567 {
10568     switch (ap) {
10569     case 0:
10570         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10571     case 1:
10572         return PAGE_READ | PAGE_WRITE;
10573     case 2:
10574         return is_user ? 0 : PAGE_READ;
10575     case 3:
10576         return PAGE_READ;
10577     default:
10578         g_assert_not_reached();
10579     }
10580 }
10581 
10582 static inline int
10583 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10584 {
10585     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10586 }
10587 
10588 /* Translate S2 section/page access permissions to protection flags
10589  *
10590  * @env:     CPUARMState
10591  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10592  * @xn:      XN (execute-never) bits
10593  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
10594  */
10595 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
10596 {
10597     int prot = 0;
10598 
10599     if (s2ap & 1) {
10600         prot |= PAGE_READ;
10601     }
10602     if (s2ap & 2) {
10603         prot |= PAGE_WRITE;
10604     }
10605 
10606     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
10607         switch (xn) {
10608         case 0:
10609             prot |= PAGE_EXEC;
10610             break;
10611         case 1:
10612             if (s1_is_el0) {
10613                 prot |= PAGE_EXEC;
10614             }
10615             break;
10616         case 2:
10617             break;
10618         case 3:
10619             if (!s1_is_el0) {
10620                 prot |= PAGE_EXEC;
10621             }
10622             break;
10623         default:
10624             g_assert_not_reached();
10625         }
10626     } else {
10627         if (!extract32(xn, 1, 1)) {
10628             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10629                 prot |= PAGE_EXEC;
10630             }
10631         }
10632     }
10633     return prot;
10634 }
10635 
10636 /* Translate section/page access permissions to protection flags
10637  *
10638  * @env:     CPUARMState
10639  * @mmu_idx: MMU index indicating required translation regime
10640  * @is_aa64: TRUE if AArch64
10641  * @ap:      The 2-bit simple AP (AP[2:1])
10642  * @ns:      NS (non-secure) bit
10643  * @xn:      XN (execute-never) bit
10644  * @pxn:     PXN (privileged execute-never) bit
10645  */
10646 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10647                       int ap, int ns, int xn, int pxn)
10648 {
10649     bool is_user = regime_is_user(env, mmu_idx);
10650     int prot_rw, user_rw;
10651     bool have_wxn;
10652     int wxn = 0;
10653 
10654     assert(mmu_idx != ARMMMUIdx_Stage2);
10655     assert(mmu_idx != ARMMMUIdx_Stage2_S);
10656 
10657     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10658     if (is_user) {
10659         prot_rw = user_rw;
10660     } else {
10661         if (user_rw && regime_is_pan(env, mmu_idx)) {
10662             /* PAN forbids data accesses but doesn't affect insn fetch */
10663             prot_rw = 0;
10664         } else {
10665             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10666         }
10667     }
10668 
10669     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10670         return prot_rw;
10671     }
10672 
10673     /* TODO have_wxn should be replaced with
10674      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10675      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10676      * compatible processors have EL2, which is required for [U]WXN.
10677      */
10678     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10679 
10680     if (have_wxn) {
10681         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10682     }
10683 
10684     if (is_aa64) {
10685         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10686             xn = pxn || (user_rw & PAGE_WRITE);
10687         }
10688     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10689         switch (regime_el(env, mmu_idx)) {
10690         case 1:
10691         case 3:
10692             if (is_user) {
10693                 xn = xn || !(user_rw & PAGE_READ);
10694             } else {
10695                 int uwxn = 0;
10696                 if (have_wxn) {
10697                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10698                 }
10699                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10700                      (uwxn && (user_rw & PAGE_WRITE));
10701             }
10702             break;
10703         case 2:
10704             break;
10705         }
10706     } else {
10707         xn = wxn = 0;
10708     }
10709 
10710     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10711         return prot_rw;
10712     }
10713     return prot_rw | PAGE_EXEC;
10714 }
10715 
10716 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10717                                      uint32_t *table, uint32_t address)
10718 {
10719     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10720     TCR *tcr = regime_tcr(env, mmu_idx);
10721 
10722     if (address & tcr->mask) {
10723         if (tcr->raw_tcr & TTBCR_PD1) {
10724             /* Translation table walk disabled for TTBR1 */
10725             return false;
10726         }
10727         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10728     } else {
10729         if (tcr->raw_tcr & TTBCR_PD0) {
10730             /* Translation table walk disabled for TTBR0 */
10731             return false;
10732         }
10733         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10734     }
10735     *table |= (address >> 18) & 0x3ffc;
10736     return true;
10737 }
10738 
10739 static bool ptw_attrs_are_device(CPUARMState *env, ARMCacheAttrs cacheattrs)
10740 {
10741     /*
10742      * For an S1 page table walk, the stage 1 attributes are always
10743      * some form of "this is Normal memory". The combined S1+S2
10744      * attributes are therefore only Device if stage 2 specifies Device.
10745      * With HCR_EL2.FWB == 0 this is when descriptor bits [5:4] are 0b00,
10746      * ie when cacheattrs.attrs bits [3:2] are 0b00.
10747      * With HCR_EL2.FWB == 1 this is when descriptor bit [4] is 0, ie
10748      * when cacheattrs.attrs bit [2] is 0.
10749      */
10750     assert(cacheattrs.is_s2_format);
10751     if (arm_hcr_el2_eff(env) & HCR_FWB) {
10752         return (cacheattrs.attrs & 0x4) == 0;
10753     } else {
10754         return (cacheattrs.attrs & 0xc) == 0;
10755     }
10756 }
10757 
10758 /* Translate a S1 pagetable walk through S2 if needed.  */
10759 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10760                                hwaddr addr, bool *is_secure,
10761                                ARMMMUFaultInfo *fi)
10762 {
10763     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10764         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10765         target_ulong s2size;
10766         hwaddr s2pa;
10767         int s2prot;
10768         int ret;
10769         ARMMMUIdx s2_mmu_idx = *is_secure ? ARMMMUIdx_Stage2_S
10770                                           : ARMMMUIdx_Stage2;
10771         ARMCacheAttrs cacheattrs = {};
10772         MemTxAttrs txattrs = {};
10773 
10774         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, s2_mmu_idx, false,
10775                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10776                                  &cacheattrs);
10777         if (ret) {
10778             assert(fi->type != ARMFault_None);
10779             fi->s2addr = addr;
10780             fi->stage2 = true;
10781             fi->s1ptw = true;
10782             fi->s1ns = !*is_secure;
10783             return ~0;
10784         }
10785         if ((arm_hcr_el2_eff(env) & HCR_PTW) &&
10786             ptw_attrs_are_device(env, cacheattrs)) {
10787             /*
10788              * PTW set and S1 walk touched S2 Device memory:
10789              * generate Permission fault.
10790              */
10791             fi->type = ARMFault_Permission;
10792             fi->s2addr = addr;
10793             fi->stage2 = true;
10794             fi->s1ptw = true;
10795             fi->s1ns = !*is_secure;
10796             return ~0;
10797         }
10798 
10799         if (arm_is_secure_below_el3(env)) {
10800             /* Check if page table walk is to secure or non-secure PA space. */
10801             if (*is_secure) {
10802                 *is_secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
10803             } else {
10804                 *is_secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
10805             }
10806         } else {
10807             assert(!*is_secure);
10808         }
10809 
10810         addr = s2pa;
10811     }
10812     return addr;
10813 }
10814 
10815 /* All loads done in the course of a page table walk go through here. */
10816 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10817                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10818 {
10819     ARMCPU *cpu = ARM_CPU(cs);
10820     CPUARMState *env = &cpu->env;
10821     MemTxAttrs attrs = {};
10822     MemTxResult result = MEMTX_OK;
10823     AddressSpace *as;
10824     uint32_t data;
10825 
10826     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10827     attrs.secure = is_secure;
10828     as = arm_addressspace(cs, attrs);
10829     if (fi->s1ptw) {
10830         return 0;
10831     }
10832     if (regime_translation_big_endian(env, mmu_idx)) {
10833         data = address_space_ldl_be(as, addr, attrs, &result);
10834     } else {
10835         data = address_space_ldl_le(as, addr, attrs, &result);
10836     }
10837     if (result == MEMTX_OK) {
10838         return data;
10839     }
10840     fi->type = ARMFault_SyncExternalOnWalk;
10841     fi->ea = arm_extabort_type(result);
10842     return 0;
10843 }
10844 
10845 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10846                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10847 {
10848     ARMCPU *cpu = ARM_CPU(cs);
10849     CPUARMState *env = &cpu->env;
10850     MemTxAttrs attrs = {};
10851     MemTxResult result = MEMTX_OK;
10852     AddressSpace *as;
10853     uint64_t data;
10854 
10855     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10856     attrs.secure = is_secure;
10857     as = arm_addressspace(cs, attrs);
10858     if (fi->s1ptw) {
10859         return 0;
10860     }
10861     if (regime_translation_big_endian(env, mmu_idx)) {
10862         data = address_space_ldq_be(as, addr, attrs, &result);
10863     } else {
10864         data = address_space_ldq_le(as, addr, attrs, &result);
10865     }
10866     if (result == MEMTX_OK) {
10867         return data;
10868     }
10869     fi->type = ARMFault_SyncExternalOnWalk;
10870     fi->ea = arm_extabort_type(result);
10871     return 0;
10872 }
10873 
10874 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10875                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10876                              hwaddr *phys_ptr, int *prot,
10877                              target_ulong *page_size,
10878                              ARMMMUFaultInfo *fi)
10879 {
10880     CPUState *cs = env_cpu(env);
10881     int level = 1;
10882     uint32_t table;
10883     uint32_t desc;
10884     int type;
10885     int ap;
10886     int domain = 0;
10887     int domain_prot;
10888     hwaddr phys_addr;
10889     uint32_t dacr;
10890 
10891     /* Pagetable walk.  */
10892     /* Lookup l1 descriptor.  */
10893     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10894         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10895         fi->type = ARMFault_Translation;
10896         goto do_fault;
10897     }
10898     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10899                        mmu_idx, fi);
10900     if (fi->type != ARMFault_None) {
10901         goto do_fault;
10902     }
10903     type = (desc & 3);
10904     domain = (desc >> 5) & 0x0f;
10905     if (regime_el(env, mmu_idx) == 1) {
10906         dacr = env->cp15.dacr_ns;
10907     } else {
10908         dacr = env->cp15.dacr_s;
10909     }
10910     domain_prot = (dacr >> (domain * 2)) & 3;
10911     if (type == 0) {
10912         /* Section translation fault.  */
10913         fi->type = ARMFault_Translation;
10914         goto do_fault;
10915     }
10916     if (type != 2) {
10917         level = 2;
10918     }
10919     if (domain_prot == 0 || domain_prot == 2) {
10920         fi->type = ARMFault_Domain;
10921         goto do_fault;
10922     }
10923     if (type == 2) {
10924         /* 1Mb section.  */
10925         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10926         ap = (desc >> 10) & 3;
10927         *page_size = 1024 * 1024;
10928     } else {
10929         /* Lookup l2 entry.  */
10930         if (type == 1) {
10931             /* Coarse pagetable.  */
10932             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10933         } else {
10934             /* Fine pagetable.  */
10935             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10936         }
10937         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10938                            mmu_idx, fi);
10939         if (fi->type != ARMFault_None) {
10940             goto do_fault;
10941         }
10942         switch (desc & 3) {
10943         case 0: /* Page translation fault.  */
10944             fi->type = ARMFault_Translation;
10945             goto do_fault;
10946         case 1: /* 64k page.  */
10947             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10948             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10949             *page_size = 0x10000;
10950             break;
10951         case 2: /* 4k page.  */
10952             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10953             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10954             *page_size = 0x1000;
10955             break;
10956         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10957             if (type == 1) {
10958                 /* ARMv6/XScale extended small page format */
10959                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10960                     || arm_feature(env, ARM_FEATURE_V6)) {
10961                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10962                     *page_size = 0x1000;
10963                 } else {
10964                     /* UNPREDICTABLE in ARMv5; we choose to take a
10965                      * page translation fault.
10966                      */
10967                     fi->type = ARMFault_Translation;
10968                     goto do_fault;
10969                 }
10970             } else {
10971                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10972                 *page_size = 0x400;
10973             }
10974             ap = (desc >> 4) & 3;
10975             break;
10976         default:
10977             /* Never happens, but compiler isn't smart enough to tell.  */
10978             g_assert_not_reached();
10979         }
10980     }
10981     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10982     *prot |= *prot ? PAGE_EXEC : 0;
10983     if (!(*prot & (1 << access_type))) {
10984         /* Access permission fault.  */
10985         fi->type = ARMFault_Permission;
10986         goto do_fault;
10987     }
10988     *phys_ptr = phys_addr;
10989     return false;
10990 do_fault:
10991     fi->domain = domain;
10992     fi->level = level;
10993     return true;
10994 }
10995 
10996 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10997                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10998                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10999                              target_ulong *page_size, ARMMMUFaultInfo *fi)
11000 {
11001     CPUState *cs = env_cpu(env);
11002     ARMCPU *cpu = env_archcpu(env);
11003     int level = 1;
11004     uint32_t table;
11005     uint32_t desc;
11006     uint32_t xn;
11007     uint32_t pxn = 0;
11008     int type;
11009     int ap;
11010     int domain = 0;
11011     int domain_prot;
11012     hwaddr phys_addr;
11013     uint32_t dacr;
11014     bool ns;
11015 
11016     /* Pagetable walk.  */
11017     /* Lookup l1 descriptor.  */
11018     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
11019         /* Section translation fault if page walk is disabled by PD0 or PD1 */
11020         fi->type = ARMFault_Translation;
11021         goto do_fault;
11022     }
11023     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11024                        mmu_idx, fi);
11025     if (fi->type != ARMFault_None) {
11026         goto do_fault;
11027     }
11028     type = (desc & 3);
11029     if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
11030         /* Section translation fault, or attempt to use the encoding
11031          * which is Reserved on implementations without PXN.
11032          */
11033         fi->type = ARMFault_Translation;
11034         goto do_fault;
11035     }
11036     if ((type == 1) || !(desc & (1 << 18))) {
11037         /* Page or Section.  */
11038         domain = (desc >> 5) & 0x0f;
11039     }
11040     if (regime_el(env, mmu_idx) == 1) {
11041         dacr = env->cp15.dacr_ns;
11042     } else {
11043         dacr = env->cp15.dacr_s;
11044     }
11045     if (type == 1) {
11046         level = 2;
11047     }
11048     domain_prot = (dacr >> (domain * 2)) & 3;
11049     if (domain_prot == 0 || domain_prot == 2) {
11050         /* Section or Page domain fault */
11051         fi->type = ARMFault_Domain;
11052         goto do_fault;
11053     }
11054     if (type != 1) {
11055         if (desc & (1 << 18)) {
11056             /* Supersection.  */
11057             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
11058             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
11059             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
11060             *page_size = 0x1000000;
11061         } else {
11062             /* Section.  */
11063             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
11064             *page_size = 0x100000;
11065         }
11066         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
11067         xn = desc & (1 << 4);
11068         pxn = desc & 1;
11069         ns = extract32(desc, 19, 1);
11070     } else {
11071         if (cpu_isar_feature(aa32_pxn, cpu)) {
11072             pxn = (desc >> 2) & 1;
11073         }
11074         ns = extract32(desc, 3, 1);
11075         /* Lookup l2 entry.  */
11076         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
11077         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11078                            mmu_idx, fi);
11079         if (fi->type != ARMFault_None) {
11080             goto do_fault;
11081         }
11082         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
11083         switch (desc & 3) {
11084         case 0: /* Page translation fault.  */
11085             fi->type = ARMFault_Translation;
11086             goto do_fault;
11087         case 1: /* 64k page.  */
11088             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11089             xn = desc & (1 << 15);
11090             *page_size = 0x10000;
11091             break;
11092         case 2: case 3: /* 4k page.  */
11093             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11094             xn = desc & 1;
11095             *page_size = 0x1000;
11096             break;
11097         default:
11098             /* Never happens, but compiler isn't smart enough to tell.  */
11099             g_assert_not_reached();
11100         }
11101     }
11102     if (domain_prot == 3) {
11103         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11104     } else {
11105         if (pxn && !regime_is_user(env, mmu_idx)) {
11106             xn = 1;
11107         }
11108         if (xn && access_type == MMU_INST_FETCH) {
11109             fi->type = ARMFault_Permission;
11110             goto do_fault;
11111         }
11112 
11113         if (arm_feature(env, ARM_FEATURE_V6K) &&
11114                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
11115             /* The simplified model uses AP[0] as an access control bit.  */
11116             if ((ap & 1) == 0) {
11117                 /* Access flag fault.  */
11118                 fi->type = ARMFault_AccessFlag;
11119                 goto do_fault;
11120             }
11121             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
11122         } else {
11123             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11124         }
11125         if (*prot && !xn) {
11126             *prot |= PAGE_EXEC;
11127         }
11128         if (!(*prot & (1 << access_type))) {
11129             /* Access permission fault.  */
11130             fi->type = ARMFault_Permission;
11131             goto do_fault;
11132         }
11133     }
11134     if (ns) {
11135         /* The NS bit will (as required by the architecture) have no effect if
11136          * the CPU doesn't support TZ or this is a non-secure translation
11137          * regime, because the attribute will already be non-secure.
11138          */
11139         attrs->secure = false;
11140     }
11141     *phys_ptr = phys_addr;
11142     return false;
11143 do_fault:
11144     fi->domain = domain;
11145     fi->level = level;
11146     return true;
11147 }
11148 
11149 /*
11150  * check_s2_mmu_setup
11151  * @cpu:        ARMCPU
11152  * @is_aa64:    True if the translation regime is in AArch64 state
11153  * @startlevel: Suggested starting level
11154  * @inputsize:  Bitsize of IPAs
11155  * @stride:     Page-table stride (See the ARM ARM)
11156  *
11157  * Returns true if the suggested S2 translation parameters are OK and
11158  * false otherwise.
11159  */
11160 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
11161                                int inputsize, int stride, int outputsize)
11162 {
11163     const int grainsize = stride + 3;
11164     int startsizecheck;
11165 
11166     /*
11167      * Negative levels are usually not allowed...
11168      * Except for FEAT_LPA2, 4k page table, 52-bit address space, which
11169      * begins with level -1.  Note that previous feature tests will have
11170      * eliminated this combination if it is not enabled.
11171      */
11172     if (level < (inputsize == 52 && stride == 9 ? -1 : 0)) {
11173         return false;
11174     }
11175 
11176     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
11177     if (startsizecheck < 1 || startsizecheck > stride + 4) {
11178         return false;
11179     }
11180 
11181     if (is_aa64) {
11182         switch (stride) {
11183         case 13: /* 64KB Pages.  */
11184             if (level == 0 || (level == 1 && outputsize <= 42)) {
11185                 return false;
11186             }
11187             break;
11188         case 11: /* 16KB Pages.  */
11189             if (level == 0 || (level == 1 && outputsize <= 40)) {
11190                 return false;
11191             }
11192             break;
11193         case 9: /* 4KB Pages.  */
11194             if (level == 0 && outputsize <= 42) {
11195                 return false;
11196             }
11197             break;
11198         default:
11199             g_assert_not_reached();
11200         }
11201 
11202         /* Inputsize checks.  */
11203         if (inputsize > outputsize &&
11204             (arm_el_is_aa64(&cpu->env, 1) || inputsize > 40)) {
11205             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
11206             return false;
11207         }
11208     } else {
11209         /* AArch32 only supports 4KB pages. Assert on that.  */
11210         assert(stride == 9);
11211 
11212         if (level == 0) {
11213             return false;
11214         }
11215     }
11216     return true;
11217 }
11218 
11219 /* Translate from the 4-bit stage 2 representation of
11220  * memory attributes (without cache-allocation hints) to
11221  * the 8-bit representation of the stage 1 MAIR registers
11222  * (which includes allocation hints).
11223  *
11224  * ref: shared/translation/attrs/S2AttrDecode()
11225  *      .../S2ConvertAttrsHints()
11226  */
11227 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
11228 {
11229     uint8_t hiattr = extract32(s2attrs, 2, 2);
11230     uint8_t loattr = extract32(s2attrs, 0, 2);
11231     uint8_t hihint = 0, lohint = 0;
11232 
11233     if (hiattr != 0) { /* normal memory */
11234         if (arm_hcr_el2_eff(env) & HCR_CD) { /* cache disabled */
11235             hiattr = loattr = 1; /* non-cacheable */
11236         } else {
11237             if (hiattr != 1) { /* Write-through or write-back */
11238                 hihint = 3; /* RW allocate */
11239             }
11240             if (loattr != 1) { /* Write-through or write-back */
11241                 lohint = 3; /* RW allocate */
11242             }
11243         }
11244     }
11245 
11246     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11247 }
11248 #endif /* !CONFIG_USER_ONLY */
11249 
11250 /* This mapping is common between ID_AA64MMFR0.PARANGE and TCR_ELx.{I}PS. */
11251 static const uint8_t pamax_map[] = {
11252     [0] = 32,
11253     [1] = 36,
11254     [2] = 40,
11255     [3] = 42,
11256     [4] = 44,
11257     [5] = 48,
11258     [6] = 52,
11259 };
11260 
11261 /* The cpu-specific constant value of PAMax; also used by hw/arm/virt. */
11262 unsigned int arm_pamax(ARMCPU *cpu)
11263 {
11264     unsigned int parange =
11265         FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11266 
11267     /*
11268      * id_aa64mmfr0 is a read-only register so values outside of the
11269      * supported mappings can be considered an implementation error.
11270      */
11271     assert(parange < ARRAY_SIZE(pamax_map));
11272     return pamax_map[parange];
11273 }
11274 
11275 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
11276 {
11277     if (regime_has_2_ranges(mmu_idx)) {
11278         return extract64(tcr, 37, 2);
11279     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11280         return 0; /* VTCR_EL2 */
11281     } else {
11282         /* Replicate the single TBI bit so we always have 2 bits.  */
11283         return extract32(tcr, 20, 1) * 3;
11284     }
11285 }
11286 
11287 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
11288 {
11289     if (regime_has_2_ranges(mmu_idx)) {
11290         return extract64(tcr, 51, 2);
11291     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11292         return 0; /* VTCR_EL2 */
11293     } else {
11294         /* Replicate the single TBID bit so we always have 2 bits.  */
11295         return extract32(tcr, 29, 1) * 3;
11296     }
11297 }
11298 
11299 static int aa64_va_parameter_tcma(uint64_t tcr, ARMMMUIdx mmu_idx)
11300 {
11301     if (regime_has_2_ranges(mmu_idx)) {
11302         return extract64(tcr, 57, 2);
11303     } else {
11304         /* Replicate the single TCMA bit so we always have 2 bits.  */
11305         return extract32(tcr, 30, 1) * 3;
11306     }
11307 }
11308 
11309 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11310                                    ARMMMUIdx mmu_idx, bool data)
11311 {
11312     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11313     bool epd, hpd, using16k, using64k, tsz_oob, ds;
11314     int select, tsz, tbi, max_tsz, min_tsz, ps, sh;
11315     ARMCPU *cpu = env_archcpu(env);
11316 
11317     if (!regime_has_2_ranges(mmu_idx)) {
11318         select = 0;
11319         tsz = extract32(tcr, 0, 6);
11320         using64k = extract32(tcr, 14, 1);
11321         using16k = extract32(tcr, 15, 1);
11322         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11323             /* VTCR_EL2 */
11324             hpd = false;
11325         } else {
11326             hpd = extract32(tcr, 24, 1);
11327         }
11328         epd = false;
11329         sh = extract32(tcr, 12, 2);
11330         ps = extract32(tcr, 16, 3);
11331         ds = extract64(tcr, 32, 1);
11332     } else {
11333         /*
11334          * Bit 55 is always between the two regions, and is canonical for
11335          * determining if address tagging is enabled.
11336          */
11337         select = extract64(va, 55, 1);
11338         if (!select) {
11339             tsz = extract32(tcr, 0, 6);
11340             epd = extract32(tcr, 7, 1);
11341             sh = extract32(tcr, 12, 2);
11342             using64k = extract32(tcr, 14, 1);
11343             using16k = extract32(tcr, 15, 1);
11344             hpd = extract64(tcr, 41, 1);
11345         } else {
11346             int tg = extract32(tcr, 30, 2);
11347             using16k = tg == 1;
11348             using64k = tg == 3;
11349             tsz = extract32(tcr, 16, 6);
11350             epd = extract32(tcr, 23, 1);
11351             sh = extract32(tcr, 28, 2);
11352             hpd = extract64(tcr, 42, 1);
11353         }
11354         ps = extract64(tcr, 32, 3);
11355         ds = extract64(tcr, 59, 1);
11356     }
11357 
11358     if (cpu_isar_feature(aa64_st, cpu)) {
11359         max_tsz = 48 - using64k;
11360     } else {
11361         max_tsz = 39;
11362     }
11363 
11364     /*
11365      * DS is RES0 unless FEAT_LPA2 is supported for the given page size;
11366      * adjust the effective value of DS, as documented.
11367      */
11368     min_tsz = 16;
11369     if (using64k) {
11370         if (cpu_isar_feature(aa64_lva, cpu)) {
11371             min_tsz = 12;
11372         }
11373         ds = false;
11374     } else if (ds) {
11375         switch (mmu_idx) {
11376         case ARMMMUIdx_Stage2:
11377         case ARMMMUIdx_Stage2_S:
11378             if (using16k) {
11379                 ds = cpu_isar_feature(aa64_tgran16_2_lpa2, cpu);
11380             } else {
11381                 ds = cpu_isar_feature(aa64_tgran4_2_lpa2, cpu);
11382             }
11383             break;
11384         default:
11385             if (using16k) {
11386                 ds = cpu_isar_feature(aa64_tgran16_lpa2, cpu);
11387             } else {
11388                 ds = cpu_isar_feature(aa64_tgran4_lpa2, cpu);
11389             }
11390             break;
11391         }
11392         if (ds) {
11393             min_tsz = 12;
11394         }
11395     }
11396 
11397     if (tsz > max_tsz) {
11398         tsz = max_tsz;
11399         tsz_oob = true;
11400     } else if (tsz < min_tsz) {
11401         tsz = min_tsz;
11402         tsz_oob = true;
11403     } else {
11404         tsz_oob = false;
11405     }
11406 
11407     /* Present TBI as a composite with TBID.  */
11408     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11409     if (!data) {
11410         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11411     }
11412     tbi = (tbi >> select) & 1;
11413 
11414     return (ARMVAParameters) {
11415         .tsz = tsz,
11416         .ps = ps,
11417         .sh = sh,
11418         .select = select,
11419         .tbi = tbi,
11420         .epd = epd,
11421         .hpd = hpd,
11422         .using16k = using16k,
11423         .using64k = using64k,
11424         .tsz_oob = tsz_oob,
11425         .ds = ds,
11426     };
11427 }
11428 
11429 #ifndef CONFIG_USER_ONLY
11430 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11431                                           ARMMMUIdx mmu_idx)
11432 {
11433     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11434     uint32_t el = regime_el(env, mmu_idx);
11435     int select, tsz;
11436     bool epd, hpd;
11437 
11438     assert(mmu_idx != ARMMMUIdx_Stage2_S);
11439 
11440     if (mmu_idx == ARMMMUIdx_Stage2) {
11441         /* VTCR */
11442         bool sext = extract32(tcr, 4, 1);
11443         bool sign = extract32(tcr, 3, 1);
11444 
11445         /*
11446          * If the sign-extend bit is not the same as t0sz[3], the result
11447          * is unpredictable. Flag this as a guest error.
11448          */
11449         if (sign != sext) {
11450             qemu_log_mask(LOG_GUEST_ERROR,
11451                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11452         }
11453         tsz = sextract32(tcr, 0, 4) + 8;
11454         select = 0;
11455         hpd = false;
11456         epd = false;
11457     } else if (el == 2) {
11458         /* HTCR */
11459         tsz = extract32(tcr, 0, 3);
11460         select = 0;
11461         hpd = extract64(tcr, 24, 1);
11462         epd = false;
11463     } else {
11464         int t0sz = extract32(tcr, 0, 3);
11465         int t1sz = extract32(tcr, 16, 3);
11466 
11467         if (t1sz == 0) {
11468             select = va > (0xffffffffu >> t0sz);
11469         } else {
11470             /* Note that we will detect errors later.  */
11471             select = va >= ~(0xffffffffu >> t1sz);
11472         }
11473         if (!select) {
11474             tsz = t0sz;
11475             epd = extract32(tcr, 7, 1);
11476             hpd = extract64(tcr, 41, 1);
11477         } else {
11478             tsz = t1sz;
11479             epd = extract32(tcr, 23, 1);
11480             hpd = extract64(tcr, 42, 1);
11481         }
11482         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11483         hpd &= extract32(tcr, 6, 1);
11484     }
11485 
11486     return (ARMVAParameters) {
11487         .tsz = tsz,
11488         .select = select,
11489         .epd = epd,
11490         .hpd = hpd,
11491     };
11492 }
11493 
11494 /**
11495  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
11496  *
11497  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11498  * prot and page_size may not be filled in, and the populated fsr value provides
11499  * information on why the translation aborted, in the format of a long-format
11500  * DFSR/IFSR fault register, with the following caveats:
11501  *  * the WnR bit is never set (the caller must do this).
11502  *
11503  * @env: CPUARMState
11504  * @address: virtual address to get physical address for
11505  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
11506  * @mmu_idx: MMU index indicating required translation regime
11507  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
11508  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
11509  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
11510  * @phys_ptr: set to the physical address corresponding to the virtual address
11511  * @attrs: set to the memory transaction attributes to use
11512  * @prot: set to the permissions for the page containing phys_ptr
11513  * @page_size_ptr: set to the size of the page containing phys_ptr
11514  * @fi: set to fault info if the translation fails
11515  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11516  */
11517 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
11518                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11519                                bool s1_is_el0,
11520                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11521                                target_ulong *page_size_ptr,
11522                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11523 {
11524     ARMCPU *cpu = env_archcpu(env);
11525     CPUState *cs = CPU(cpu);
11526     /* Read an LPAE long-descriptor translation table. */
11527     ARMFaultType fault_type = ARMFault_Translation;
11528     uint32_t level;
11529     ARMVAParameters param;
11530     uint64_t ttbr;
11531     hwaddr descaddr, indexmask, indexmask_grainsize;
11532     uint32_t tableattrs;
11533     target_ulong page_size;
11534     uint32_t attrs;
11535     int32_t stride;
11536     int addrsize, inputsize, outputsize;
11537     TCR *tcr = regime_tcr(env, mmu_idx);
11538     int ap, ns, xn, pxn;
11539     uint32_t el = regime_el(env, mmu_idx);
11540     uint64_t descaddrmask;
11541     bool aarch64 = arm_el_is_aa64(env, el);
11542     bool guarded = false;
11543 
11544     /* TODO: This code does not support shareability levels. */
11545     if (aarch64) {
11546         int ps;
11547 
11548         param = aa64_va_parameters(env, address, mmu_idx,
11549                                    access_type != MMU_INST_FETCH);
11550         level = 0;
11551 
11552         /*
11553          * If TxSZ is programmed to a value larger than the maximum,
11554          * or smaller than the effective minimum, it is IMPLEMENTATION
11555          * DEFINED whether we behave as if the field were programmed
11556          * within bounds, or if a level 0 Translation fault is generated.
11557          *
11558          * With FEAT_LVA, fault on less than minimum becomes required,
11559          * so our choice is to always raise the fault.
11560          */
11561         if (param.tsz_oob) {
11562             fault_type = ARMFault_Translation;
11563             goto do_fault;
11564         }
11565 
11566         addrsize = 64 - 8 * param.tbi;
11567         inputsize = 64 - param.tsz;
11568 
11569         /*
11570          * Bound PS by PARANGE to find the effective output address size.
11571          * ID_AA64MMFR0 is a read-only register so values outside of the
11572          * supported mappings can be considered an implementation error.
11573          */
11574         ps = FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11575         ps = MIN(ps, param.ps);
11576         assert(ps < ARRAY_SIZE(pamax_map));
11577         outputsize = pamax_map[ps];
11578     } else {
11579         param = aa32_va_parameters(env, address, mmu_idx);
11580         level = 1;
11581         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
11582         inputsize = addrsize - param.tsz;
11583         outputsize = 40;
11584     }
11585 
11586     /*
11587      * We determined the region when collecting the parameters, but we
11588      * have not yet validated that the address is valid for the region.
11589      * Extract the top bits and verify that they all match select.
11590      *
11591      * For aa32, if inputsize == addrsize, then we have selected the
11592      * region by exclusion in aa32_va_parameters and there is no more
11593      * validation to do here.
11594      */
11595     if (inputsize < addrsize) {
11596         target_ulong top_bits = sextract64(address, inputsize,
11597                                            addrsize - inputsize);
11598         if (-top_bits != param.select) {
11599             /* The gap between the two regions is a Translation fault */
11600             fault_type = ARMFault_Translation;
11601             goto do_fault;
11602         }
11603     }
11604 
11605     if (param.using64k) {
11606         stride = 13;
11607     } else if (param.using16k) {
11608         stride = 11;
11609     } else {
11610         stride = 9;
11611     }
11612 
11613     /* Note that QEMU ignores shareability and cacheability attributes,
11614      * so we don't need to do anything with the SH, ORGN, IRGN fields
11615      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11616      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11617      * implement any ASID-like capability so we can ignore it (instead
11618      * we will always flush the TLB any time the ASID is changed).
11619      */
11620     ttbr = regime_ttbr(env, mmu_idx, param.select);
11621 
11622     /* Here we should have set up all the parameters for the translation:
11623      * inputsize, ttbr, epd, stride, tbi
11624      */
11625 
11626     if (param.epd) {
11627         /* Translation table walk disabled => Translation fault on TLB miss
11628          * Note: This is always 0 on 64-bit EL2 and EL3.
11629          */
11630         goto do_fault;
11631     }
11632 
11633     if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
11634         /* The starting level depends on the virtual address size (which can
11635          * be up to 48 bits) and the translation granule size. It indicates
11636          * the number of strides (stride bits at a time) needed to
11637          * consume the bits of the input address. In the pseudocode this is:
11638          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11639          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11640          * our 'stride + 3' and 'stride' is our 'stride'.
11641          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11642          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11643          * = 4 - (inputsize - 4) / stride;
11644          */
11645         level = 4 - (inputsize - 4) / stride;
11646     } else {
11647         /* For stage 2 translations the starting level is specified by the
11648          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11649          */
11650         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11651         uint32_t sl2 = extract64(tcr->raw_tcr, 33, 1);
11652         uint32_t startlevel;
11653         bool ok;
11654 
11655         /* SL2 is RES0 unless DS=1 & 4kb granule. */
11656         if (param.ds && stride == 9 && sl2) {
11657             if (sl0 != 0) {
11658                 level = 0;
11659                 fault_type = ARMFault_Translation;
11660                 goto do_fault;
11661             }
11662             startlevel = -1;
11663         } else if (!aarch64 || stride == 9) {
11664             /* AArch32 or 4KB pages */
11665             startlevel = 2 - sl0;
11666 
11667             if (cpu_isar_feature(aa64_st, cpu)) {
11668                 startlevel &= 3;
11669             }
11670         } else {
11671             /* 16KB or 64KB pages */
11672             startlevel = 3 - sl0;
11673         }
11674 
11675         /* Check that the starting level is valid. */
11676         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11677                                 inputsize, stride, outputsize);
11678         if (!ok) {
11679             fault_type = ARMFault_Translation;
11680             goto do_fault;
11681         }
11682         level = startlevel;
11683     }
11684 
11685     indexmask_grainsize = MAKE_64BIT_MASK(0, stride + 3);
11686     indexmask = MAKE_64BIT_MASK(0, inputsize - (stride * (4 - level)));
11687 
11688     /* Now we can extract the actual base address from the TTBR */
11689     descaddr = extract64(ttbr, 0, 48);
11690 
11691     /*
11692      * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [5:2] of TTBR.
11693      *
11694      * Otherwise, if the base address is out of range, raise AddressSizeFault.
11695      * In the pseudocode, this is !IsZero(baseregister<47:outputsize>),
11696      * but we've just cleared the bits above 47, so simplify the test.
11697      */
11698     if (outputsize > 48) {
11699         descaddr |= extract64(ttbr, 2, 4) << 48;
11700     } else if (descaddr >> outputsize) {
11701         level = 0;
11702         fault_type = ARMFault_AddressSize;
11703         goto do_fault;
11704     }
11705 
11706     /*
11707      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
11708      * and also to mask out CnP (bit 0) which could validly be non-zero.
11709      */
11710     descaddr &= ~indexmask;
11711 
11712     /*
11713      * For AArch32, the address field in the descriptor goes up to bit 39
11714      * for both v7 and v8.  However, for v8 the SBZ bits [47:40] must be 0
11715      * or an AddressSize fault is raised.  So for v8 we extract those SBZ
11716      * bits as part of the address, which will be checked via outputsize.
11717      * For AArch64, the address field goes up to bit 47, or 49 with FEAT_LPA2;
11718      * the highest bits of a 52-bit output are placed elsewhere.
11719      */
11720     if (param.ds) {
11721         descaddrmask = MAKE_64BIT_MASK(0, 50);
11722     } else if (arm_feature(env, ARM_FEATURE_V8)) {
11723         descaddrmask = MAKE_64BIT_MASK(0, 48);
11724     } else {
11725         descaddrmask = MAKE_64BIT_MASK(0, 40);
11726     }
11727     descaddrmask &= ~indexmask_grainsize;
11728 
11729     /* Secure accesses start with the page table in secure memory and
11730      * can be downgraded to non-secure at any step. Non-secure accesses
11731      * remain non-secure. We implement this by just ORing in the NSTable/NS
11732      * bits at each step.
11733      */
11734     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11735     for (;;) {
11736         uint64_t descriptor;
11737         bool nstable;
11738 
11739         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11740         descaddr &= ~7ULL;
11741         nstable = extract32(tableattrs, 4, 1);
11742         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11743         if (fi->type != ARMFault_None) {
11744             goto do_fault;
11745         }
11746 
11747         if (!(descriptor & 1) ||
11748             (!(descriptor & 2) && (level == 3))) {
11749             /* Invalid, or the Reserved level 3 encoding */
11750             goto do_fault;
11751         }
11752 
11753         descaddr = descriptor & descaddrmask;
11754 
11755         /*
11756          * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [15:12]
11757          * of descriptor.  For FEAT_LPA2 and effective DS, bits [51:50] of
11758          * descaddr are in [9:8].  Otherwise, if descaddr is out of range,
11759          * raise AddressSizeFault.
11760          */
11761         if (outputsize > 48) {
11762             if (param.ds) {
11763                 descaddr |= extract64(descriptor, 8, 2) << 50;
11764             } else {
11765                 descaddr |= extract64(descriptor, 12, 4) << 48;
11766             }
11767         } else if (descaddr >> outputsize) {
11768             fault_type = ARMFault_AddressSize;
11769             goto do_fault;
11770         }
11771 
11772         if ((descriptor & 2) && (level < 3)) {
11773             /* Table entry. The top five bits are attributes which may
11774              * propagate down through lower levels of the table (and
11775              * which are all arranged so that 0 means "no effect", so
11776              * we can gather them up by ORing in the bits at each level).
11777              */
11778             tableattrs |= extract64(descriptor, 59, 5);
11779             level++;
11780             indexmask = indexmask_grainsize;
11781             continue;
11782         }
11783         /*
11784          * Block entry at level 1 or 2, or page entry at level 3.
11785          * These are basically the same thing, although the number
11786          * of bits we pull in from the vaddr varies. Note that although
11787          * descaddrmask masks enough of the low bits of the descriptor
11788          * to give a correct page or table address, the address field
11789          * in a block descriptor is smaller; so we need to explicitly
11790          * clear the lower bits here before ORing in the low vaddr bits.
11791          */
11792         page_size = (1ULL << ((stride * (4 - level)) + 3));
11793         descaddr &= ~(page_size - 1);
11794         descaddr |= (address & (page_size - 1));
11795         /* Extract attributes from the descriptor */
11796         attrs = extract64(descriptor, 2, 10)
11797             | (extract64(descriptor, 52, 12) << 10);
11798 
11799         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11800             /* Stage 2 table descriptors do not include any attribute fields */
11801             break;
11802         }
11803         /* Merge in attributes from table descriptors */
11804         attrs |= nstable << 3; /* NS */
11805         guarded = extract64(descriptor, 50, 1);  /* GP */
11806         if (param.hpd) {
11807             /* HPD disables all the table attributes except NSTable.  */
11808             break;
11809         }
11810         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11811         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11812          * means "force PL1 access only", which means forcing AP[1] to 0.
11813          */
11814         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11815         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11816         break;
11817     }
11818     /* Here descaddr is the final physical address, and attributes
11819      * are all in attrs.
11820      */
11821     fault_type = ARMFault_AccessFlag;
11822     if ((attrs & (1 << 8)) == 0) {
11823         /* Access flag */
11824         goto do_fault;
11825     }
11826 
11827     ap = extract32(attrs, 4, 2);
11828 
11829     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11830         ns = mmu_idx == ARMMMUIdx_Stage2;
11831         xn = extract32(attrs, 11, 2);
11832         *prot = get_S2prot(env, ap, xn, s1_is_el0);
11833     } else {
11834         ns = extract32(attrs, 3, 1);
11835         xn = extract32(attrs, 12, 1);
11836         pxn = extract32(attrs, 11, 1);
11837         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11838     }
11839 
11840     fault_type = ARMFault_Permission;
11841     if (!(*prot & (1 << access_type))) {
11842         goto do_fault;
11843     }
11844 
11845     if (ns) {
11846         /* The NS bit will (as required by the architecture) have no effect if
11847          * the CPU doesn't support TZ or this is a non-secure translation
11848          * regime, because the attribute will already be non-secure.
11849          */
11850         txattrs->secure = false;
11851     }
11852     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11853     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11854         arm_tlb_bti_gp(txattrs) = true;
11855     }
11856 
11857     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11858         cacheattrs->is_s2_format = true;
11859         cacheattrs->attrs = extract32(attrs, 0, 4);
11860     } else {
11861         /* Index into MAIR registers for cache attributes */
11862         uint8_t attrindx = extract32(attrs, 0, 3);
11863         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11864         assert(attrindx <= 7);
11865         cacheattrs->is_s2_format = false;
11866         cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11867     }
11868 
11869     /*
11870      * For FEAT_LPA2 and effective DS, the SH field in the attributes
11871      * was re-purposed for output address bits.  The SH attribute in
11872      * that case comes from TCR_ELx, which we extracted earlier.
11873      */
11874     if (param.ds) {
11875         cacheattrs->shareability = param.sh;
11876     } else {
11877         cacheattrs->shareability = extract32(attrs, 6, 2);
11878     }
11879 
11880     *phys_ptr = descaddr;
11881     *page_size_ptr = page_size;
11882     return false;
11883 
11884 do_fault:
11885     fi->type = fault_type;
11886     fi->level = level;
11887     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11888     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2 ||
11889                                mmu_idx == ARMMMUIdx_Stage2_S);
11890     fi->s1ns = mmu_idx == ARMMMUIdx_Stage2;
11891     return true;
11892 }
11893 
11894 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11895                                                 ARMMMUIdx mmu_idx,
11896                                                 int32_t address, int *prot)
11897 {
11898     if (!arm_feature(env, ARM_FEATURE_M)) {
11899         *prot = PAGE_READ | PAGE_WRITE;
11900         switch (address) {
11901         case 0xF0000000 ... 0xFFFFFFFF:
11902             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11903                 /* hivecs execing is ok */
11904                 *prot |= PAGE_EXEC;
11905             }
11906             break;
11907         case 0x00000000 ... 0x7FFFFFFF:
11908             *prot |= PAGE_EXEC;
11909             break;
11910         }
11911     } else {
11912         /* Default system address map for M profile cores.
11913          * The architecture specifies which regions are execute-never;
11914          * at the MPU level no other checks are defined.
11915          */
11916         switch (address) {
11917         case 0x00000000 ... 0x1fffffff: /* ROM */
11918         case 0x20000000 ... 0x3fffffff: /* SRAM */
11919         case 0x60000000 ... 0x7fffffff: /* RAM */
11920         case 0x80000000 ... 0x9fffffff: /* RAM */
11921             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11922             break;
11923         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11924         case 0xa0000000 ... 0xbfffffff: /* Device */
11925         case 0xc0000000 ... 0xdfffffff: /* Device */
11926         case 0xe0000000 ... 0xffffffff: /* System */
11927             *prot = PAGE_READ | PAGE_WRITE;
11928             break;
11929         default:
11930             g_assert_not_reached();
11931         }
11932     }
11933 }
11934 
11935 static bool pmsav7_use_background_region(ARMCPU *cpu,
11936                                          ARMMMUIdx mmu_idx, bool is_user)
11937 {
11938     /* Return true if we should use the default memory map as a
11939      * "background" region if there are no hits against any MPU regions.
11940      */
11941     CPUARMState *env = &cpu->env;
11942 
11943     if (is_user) {
11944         return false;
11945     }
11946 
11947     if (arm_feature(env, ARM_FEATURE_M)) {
11948         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11949             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11950     } else {
11951         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11952     }
11953 }
11954 
11955 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11956 {
11957     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11958     return arm_feature(env, ARM_FEATURE_M) &&
11959         extract32(address, 20, 12) == 0xe00;
11960 }
11961 
11962 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11963 {
11964     /* True if address is in the M profile system region
11965      * 0xe0000000 - 0xffffffff
11966      */
11967     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11968 }
11969 
11970 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11971                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11972                                  hwaddr *phys_ptr, int *prot,
11973                                  target_ulong *page_size,
11974                                  ARMMMUFaultInfo *fi)
11975 {
11976     ARMCPU *cpu = env_archcpu(env);
11977     int n;
11978     bool is_user = regime_is_user(env, mmu_idx);
11979 
11980     *phys_ptr = address;
11981     *page_size = TARGET_PAGE_SIZE;
11982     *prot = 0;
11983 
11984     if (regime_translation_disabled(env, mmu_idx) ||
11985         m_is_ppb_region(env, address)) {
11986         /* MPU disabled or M profile PPB access: use default memory map.
11987          * The other case which uses the default memory map in the
11988          * v7M ARM ARM pseudocode is exception vector reads from the vector
11989          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11990          * which always does a direct read using address_space_ldl(), rather
11991          * than going via this function, so we don't need to check that here.
11992          */
11993         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11994     } else { /* MPU enabled */
11995         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11996             /* region search */
11997             uint32_t base = env->pmsav7.drbar[n];
11998             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11999             uint32_t rmask;
12000             bool srdis = false;
12001 
12002             if (!(env->pmsav7.drsr[n] & 0x1)) {
12003                 continue;
12004             }
12005 
12006             if (!rsize) {
12007                 qemu_log_mask(LOG_GUEST_ERROR,
12008                               "DRSR[%d]: Rsize field cannot be 0\n", n);
12009                 continue;
12010             }
12011             rsize++;
12012             rmask = (1ull << rsize) - 1;
12013 
12014             if (base & rmask) {
12015                 qemu_log_mask(LOG_GUEST_ERROR,
12016                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
12017                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
12018                               n, base, rmask);
12019                 continue;
12020             }
12021 
12022             if (address < base || address > base + rmask) {
12023                 /*
12024                  * Address not in this region. We must check whether the
12025                  * region covers addresses in the same page as our address.
12026                  * In that case we must not report a size that covers the
12027                  * whole page for a subsequent hit against a different MPU
12028                  * region or the background region, because it would result in
12029                  * incorrect TLB hits for subsequent accesses to addresses that
12030                  * are in this MPU region.
12031                  */
12032                 if (ranges_overlap(base, rmask,
12033                                    address & TARGET_PAGE_MASK,
12034                                    TARGET_PAGE_SIZE)) {
12035                     *page_size = 1;
12036                 }
12037                 continue;
12038             }
12039 
12040             /* Region matched */
12041 
12042             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
12043                 int i, snd;
12044                 uint32_t srdis_mask;
12045 
12046                 rsize -= 3; /* sub region size (power of 2) */
12047                 snd = ((address - base) >> rsize) & 0x7;
12048                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
12049 
12050                 srdis_mask = srdis ? 0x3 : 0x0;
12051                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
12052                     /* This will check in groups of 2, 4 and then 8, whether
12053                      * the subregion bits are consistent. rsize is incremented
12054                      * back up to give the region size, considering consistent
12055                      * adjacent subregions as one region. Stop testing if rsize
12056                      * is already big enough for an entire QEMU page.
12057                      */
12058                     int snd_rounded = snd & ~(i - 1);
12059                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
12060                                                      snd_rounded + 8, i);
12061                     if (srdis_mask ^ srdis_multi) {
12062                         break;
12063                     }
12064                     srdis_mask = (srdis_mask << i) | srdis_mask;
12065                     rsize++;
12066                 }
12067             }
12068             if (srdis) {
12069                 continue;
12070             }
12071             if (rsize < TARGET_PAGE_BITS) {
12072                 *page_size = 1 << rsize;
12073             }
12074             break;
12075         }
12076 
12077         if (n == -1) { /* no hits */
12078             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12079                 /* background fault */
12080                 fi->type = ARMFault_Background;
12081                 return true;
12082             }
12083             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12084         } else { /* a MPU hit! */
12085             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
12086             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
12087 
12088             if (m_is_system_region(env, address)) {
12089                 /* System space is always execute never */
12090                 xn = 1;
12091             }
12092 
12093             if (is_user) { /* User mode AP bit decoding */
12094                 switch (ap) {
12095                 case 0:
12096                 case 1:
12097                 case 5:
12098                     break; /* no access */
12099                 case 3:
12100                     *prot |= PAGE_WRITE;
12101                     /* fall through */
12102                 case 2:
12103                 case 6:
12104                     *prot |= PAGE_READ | PAGE_EXEC;
12105                     break;
12106                 case 7:
12107                     /* for v7M, same as 6; for R profile a reserved value */
12108                     if (arm_feature(env, ARM_FEATURE_M)) {
12109                         *prot |= PAGE_READ | PAGE_EXEC;
12110                         break;
12111                     }
12112                     /* fall through */
12113                 default:
12114                     qemu_log_mask(LOG_GUEST_ERROR,
12115                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12116                                   PRIx32 "\n", n, ap);
12117                 }
12118             } else { /* Priv. mode AP bits decoding */
12119                 switch (ap) {
12120                 case 0:
12121                     break; /* no access */
12122                 case 1:
12123                 case 2:
12124                 case 3:
12125                     *prot |= PAGE_WRITE;
12126                     /* fall through */
12127                 case 5:
12128                 case 6:
12129                     *prot |= PAGE_READ | PAGE_EXEC;
12130                     break;
12131                 case 7:
12132                     /* for v7M, same as 6; for R profile a reserved value */
12133                     if (arm_feature(env, ARM_FEATURE_M)) {
12134                         *prot |= PAGE_READ | PAGE_EXEC;
12135                         break;
12136                     }
12137                     /* fall through */
12138                 default:
12139                     qemu_log_mask(LOG_GUEST_ERROR,
12140                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12141                                   PRIx32 "\n", n, ap);
12142                 }
12143             }
12144 
12145             /* execute never */
12146             if (xn) {
12147                 *prot &= ~PAGE_EXEC;
12148             }
12149         }
12150     }
12151 
12152     fi->type = ARMFault_Permission;
12153     fi->level = 1;
12154     return !(*prot & (1 << access_type));
12155 }
12156 
12157 static bool v8m_is_sau_exempt(CPUARMState *env,
12158                               uint32_t address, MMUAccessType access_type)
12159 {
12160     /* The architecture specifies that certain address ranges are
12161      * exempt from v8M SAU/IDAU checks.
12162      */
12163     return
12164         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
12165         (address >= 0xe0000000 && address <= 0xe0002fff) ||
12166         (address >= 0xe000e000 && address <= 0xe000efff) ||
12167         (address >= 0xe002e000 && address <= 0xe002efff) ||
12168         (address >= 0xe0040000 && address <= 0xe0041fff) ||
12169         (address >= 0xe00ff000 && address <= 0xe00fffff);
12170 }
12171 
12172 void v8m_security_lookup(CPUARMState *env, uint32_t address,
12173                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
12174                                 V8M_SAttributes *sattrs)
12175 {
12176     /* Look up the security attributes for this address. Compare the
12177      * pseudocode SecurityCheck() function.
12178      * We assume the caller has zero-initialized *sattrs.
12179      */
12180     ARMCPU *cpu = env_archcpu(env);
12181     int r;
12182     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
12183     int idau_region = IREGION_NOTVALID;
12184     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12185     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12186 
12187     if (cpu->idau) {
12188         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
12189         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
12190 
12191         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
12192                    &idau_nsc);
12193     }
12194 
12195     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
12196         /* 0xf0000000..0xffffffff is always S for insn fetches */
12197         return;
12198     }
12199 
12200     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
12201         sattrs->ns = !regime_is_secure(env, mmu_idx);
12202         return;
12203     }
12204 
12205     if (idau_region != IREGION_NOTVALID) {
12206         sattrs->irvalid = true;
12207         sattrs->iregion = idau_region;
12208     }
12209 
12210     switch (env->sau.ctrl & 3) {
12211     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
12212         break;
12213     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
12214         sattrs->ns = true;
12215         break;
12216     default: /* SAU.ENABLE == 1 */
12217         for (r = 0; r < cpu->sau_sregion; r++) {
12218             if (env->sau.rlar[r] & 1) {
12219                 uint32_t base = env->sau.rbar[r] & ~0x1f;
12220                 uint32_t limit = env->sau.rlar[r] | 0x1f;
12221 
12222                 if (base <= address && limit >= address) {
12223                     if (base > addr_page_base || limit < addr_page_limit) {
12224                         sattrs->subpage = true;
12225                     }
12226                     if (sattrs->srvalid) {
12227                         /* If we hit in more than one region then we must report
12228                          * as Secure, not NS-Callable, with no valid region
12229                          * number info.
12230                          */
12231                         sattrs->ns = false;
12232                         sattrs->nsc = false;
12233                         sattrs->sregion = 0;
12234                         sattrs->srvalid = false;
12235                         break;
12236                     } else {
12237                         if (env->sau.rlar[r] & 2) {
12238                             sattrs->nsc = true;
12239                         } else {
12240                             sattrs->ns = true;
12241                         }
12242                         sattrs->srvalid = true;
12243                         sattrs->sregion = r;
12244                     }
12245                 } else {
12246                     /*
12247                      * Address not in this region. We must check whether the
12248                      * region covers addresses in the same page as our address.
12249                      * In that case we must not report a size that covers the
12250                      * whole page for a subsequent hit against a different MPU
12251                      * region or the background region, because it would result
12252                      * in incorrect TLB hits for subsequent accesses to
12253                      * addresses that are in this MPU region.
12254                      */
12255                     if (limit >= base &&
12256                         ranges_overlap(base, limit - base + 1,
12257                                        addr_page_base,
12258                                        TARGET_PAGE_SIZE)) {
12259                         sattrs->subpage = true;
12260                     }
12261                 }
12262             }
12263         }
12264         break;
12265     }
12266 
12267     /*
12268      * The IDAU will override the SAU lookup results if it specifies
12269      * higher security than the SAU does.
12270      */
12271     if (!idau_ns) {
12272         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
12273             sattrs->ns = false;
12274             sattrs->nsc = idau_nsc;
12275         }
12276     }
12277 }
12278 
12279 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
12280                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
12281                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
12282                               int *prot, bool *is_subpage,
12283                               ARMMMUFaultInfo *fi, uint32_t *mregion)
12284 {
12285     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
12286      * that a full phys-to-virt translation does).
12287      * mregion is (if not NULL) set to the region number which matched,
12288      * or -1 if no region number is returned (MPU off, address did not
12289      * hit a region, address hit in multiple regions).
12290      * We set is_subpage to true if the region hit doesn't cover the
12291      * entire TARGET_PAGE the address is within.
12292      */
12293     ARMCPU *cpu = env_archcpu(env);
12294     bool is_user = regime_is_user(env, mmu_idx);
12295     uint32_t secure = regime_is_secure(env, mmu_idx);
12296     int n;
12297     int matchregion = -1;
12298     bool hit = false;
12299     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12300     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12301 
12302     *is_subpage = false;
12303     *phys_ptr = address;
12304     *prot = 0;
12305     if (mregion) {
12306         *mregion = -1;
12307     }
12308 
12309     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
12310      * was an exception vector read from the vector table (which is always
12311      * done using the default system address map), because those accesses
12312      * are done in arm_v7m_load_vector(), which always does a direct
12313      * read using address_space_ldl(), rather than going via this function.
12314      */
12315     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
12316         hit = true;
12317     } else if (m_is_ppb_region(env, address)) {
12318         hit = true;
12319     } else {
12320         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12321             hit = true;
12322         }
12323 
12324         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12325             /* region search */
12326             /* Note that the base address is bits [31:5] from the register
12327              * with bits [4:0] all zeroes, but the limit address is bits
12328              * [31:5] from the register with bits [4:0] all ones.
12329              */
12330             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
12331             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
12332 
12333             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
12334                 /* Region disabled */
12335                 continue;
12336             }
12337 
12338             if (address < base || address > limit) {
12339                 /*
12340                  * Address not in this region. We must check whether the
12341                  * region covers addresses in the same page as our address.
12342                  * In that case we must not report a size that covers the
12343                  * whole page for a subsequent hit against a different MPU
12344                  * region or the background region, because it would result in
12345                  * incorrect TLB hits for subsequent accesses to addresses that
12346                  * are in this MPU region.
12347                  */
12348                 if (limit >= base &&
12349                     ranges_overlap(base, limit - base + 1,
12350                                    addr_page_base,
12351                                    TARGET_PAGE_SIZE)) {
12352                     *is_subpage = true;
12353                 }
12354                 continue;
12355             }
12356 
12357             if (base > addr_page_base || limit < addr_page_limit) {
12358                 *is_subpage = true;
12359             }
12360 
12361             if (matchregion != -1) {
12362                 /* Multiple regions match -- always a failure (unlike
12363                  * PMSAv7 where highest-numbered-region wins)
12364                  */
12365                 fi->type = ARMFault_Permission;
12366                 fi->level = 1;
12367                 return true;
12368             }
12369 
12370             matchregion = n;
12371             hit = true;
12372         }
12373     }
12374 
12375     if (!hit) {
12376         /* background fault */
12377         fi->type = ARMFault_Background;
12378         return true;
12379     }
12380 
12381     if (matchregion == -1) {
12382         /* hit using the background region */
12383         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12384     } else {
12385         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
12386         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
12387         bool pxn = false;
12388 
12389         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
12390             pxn = extract32(env->pmsav8.rlar[secure][matchregion], 4, 1);
12391         }
12392 
12393         if (m_is_system_region(env, address)) {
12394             /* System space is always execute never */
12395             xn = 1;
12396         }
12397 
12398         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
12399         if (*prot && !xn && !(pxn && !is_user)) {
12400             *prot |= PAGE_EXEC;
12401         }
12402         /* We don't need to look the attribute up in the MAIR0/MAIR1
12403          * registers because that only tells us about cacheability.
12404          */
12405         if (mregion) {
12406             *mregion = matchregion;
12407         }
12408     }
12409 
12410     fi->type = ARMFault_Permission;
12411     fi->level = 1;
12412     return !(*prot & (1 << access_type));
12413 }
12414 
12415 
12416 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12417                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12418                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12419                                  int *prot, target_ulong *page_size,
12420                                  ARMMMUFaultInfo *fi)
12421 {
12422     uint32_t secure = regime_is_secure(env, mmu_idx);
12423     V8M_SAttributes sattrs = {};
12424     bool ret;
12425     bool mpu_is_subpage;
12426 
12427     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12428         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12429         if (access_type == MMU_INST_FETCH) {
12430             /* Instruction fetches always use the MMU bank and the
12431              * transaction attribute determined by the fetch address,
12432              * regardless of CPU state. This is painful for QEMU
12433              * to handle, because it would mean we need to encode
12434              * into the mmu_idx not just the (user, negpri) information
12435              * for the current security state but also that for the
12436              * other security state, which would balloon the number
12437              * of mmu_idx values needed alarmingly.
12438              * Fortunately we can avoid this because it's not actually
12439              * possible to arbitrarily execute code from memory with
12440              * the wrong security attribute: it will always generate
12441              * an exception of some kind or another, apart from the
12442              * special case of an NS CPU executing an SG instruction
12443              * in S&NSC memory. So we always just fail the translation
12444              * here and sort things out in the exception handler
12445              * (including possibly emulating an SG instruction).
12446              */
12447             if (sattrs.ns != !secure) {
12448                 if (sattrs.nsc) {
12449                     fi->type = ARMFault_QEMU_NSCExec;
12450                 } else {
12451                     fi->type = ARMFault_QEMU_SFault;
12452                 }
12453                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12454                 *phys_ptr = address;
12455                 *prot = 0;
12456                 return true;
12457             }
12458         } else {
12459             /* For data accesses we always use the MMU bank indicated
12460              * by the current CPU state, but the security attributes
12461              * might downgrade a secure access to nonsecure.
12462              */
12463             if (sattrs.ns) {
12464                 txattrs->secure = false;
12465             } else if (!secure) {
12466                 /* NS access to S memory must fault.
12467                  * Architecturally we should first check whether the
12468                  * MPU information for this address indicates that we
12469                  * are doing an unaligned access to Device memory, which
12470                  * should generate a UsageFault instead. QEMU does not
12471                  * currently check for that kind of unaligned access though.
12472                  * If we added it we would need to do so as a special case
12473                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12474                  */
12475                 fi->type = ARMFault_QEMU_SFault;
12476                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12477                 *phys_ptr = address;
12478                 *prot = 0;
12479                 return true;
12480             }
12481         }
12482     }
12483 
12484     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12485                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12486     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12487     return ret;
12488 }
12489 
12490 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12491                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12492                                  hwaddr *phys_ptr, int *prot,
12493                                  ARMMMUFaultInfo *fi)
12494 {
12495     int n;
12496     uint32_t mask;
12497     uint32_t base;
12498     bool is_user = regime_is_user(env, mmu_idx);
12499 
12500     if (regime_translation_disabled(env, mmu_idx)) {
12501         /* MPU disabled.  */
12502         *phys_ptr = address;
12503         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12504         return false;
12505     }
12506 
12507     *phys_ptr = address;
12508     for (n = 7; n >= 0; n--) {
12509         base = env->cp15.c6_region[n];
12510         if ((base & 1) == 0) {
12511             continue;
12512         }
12513         mask = 1 << ((base >> 1) & 0x1f);
12514         /* Keep this shift separate from the above to avoid an
12515            (undefined) << 32.  */
12516         mask = (mask << 1) - 1;
12517         if (((base ^ address) & ~mask) == 0) {
12518             break;
12519         }
12520     }
12521     if (n < 0) {
12522         fi->type = ARMFault_Background;
12523         return true;
12524     }
12525 
12526     if (access_type == MMU_INST_FETCH) {
12527         mask = env->cp15.pmsav5_insn_ap;
12528     } else {
12529         mask = env->cp15.pmsav5_data_ap;
12530     }
12531     mask = (mask >> (n * 4)) & 0xf;
12532     switch (mask) {
12533     case 0:
12534         fi->type = ARMFault_Permission;
12535         fi->level = 1;
12536         return true;
12537     case 1:
12538         if (is_user) {
12539             fi->type = ARMFault_Permission;
12540             fi->level = 1;
12541             return true;
12542         }
12543         *prot = PAGE_READ | PAGE_WRITE;
12544         break;
12545     case 2:
12546         *prot = PAGE_READ;
12547         if (!is_user) {
12548             *prot |= PAGE_WRITE;
12549         }
12550         break;
12551     case 3:
12552         *prot = PAGE_READ | PAGE_WRITE;
12553         break;
12554     case 5:
12555         if (is_user) {
12556             fi->type = ARMFault_Permission;
12557             fi->level = 1;
12558             return true;
12559         }
12560         *prot = PAGE_READ;
12561         break;
12562     case 6:
12563         *prot = PAGE_READ;
12564         break;
12565     default:
12566         /* Bad permission.  */
12567         fi->type = ARMFault_Permission;
12568         fi->level = 1;
12569         return true;
12570     }
12571     *prot |= PAGE_EXEC;
12572     return false;
12573 }
12574 
12575 /* Combine either inner or outer cacheability attributes for normal
12576  * memory, according to table D4-42 and pseudocode procedure
12577  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12578  *
12579  * NB: only stage 1 includes allocation hints (RW bits), leading to
12580  * some asymmetry.
12581  */
12582 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12583 {
12584     if (s1 == 4 || s2 == 4) {
12585         /* non-cacheable has precedence */
12586         return 4;
12587     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12588         /* stage 1 write-through takes precedence */
12589         return s1;
12590     } else if (extract32(s2, 2, 2) == 2) {
12591         /* stage 2 write-through takes precedence, but the allocation hint
12592          * is still taken from stage 1
12593          */
12594         return (2 << 2) | extract32(s1, 0, 2);
12595     } else { /* write-back */
12596         return s1;
12597     }
12598 }
12599 
12600 /*
12601  * Combine the memory type and cacheability attributes of
12602  * s1 and s2 for the HCR_EL2.FWB == 0 case, returning the
12603  * combined attributes in MAIR_EL1 format.
12604  */
12605 static uint8_t combined_attrs_nofwb(CPUARMState *env,
12606                                     ARMCacheAttrs s1, ARMCacheAttrs s2)
12607 {
12608     uint8_t s1lo, s2lo, s1hi, s2hi, s2_mair_attrs, ret_attrs;
12609 
12610     s2_mair_attrs = convert_stage2_attrs(env, s2.attrs);
12611 
12612     s1lo = extract32(s1.attrs, 0, 4);
12613     s2lo = extract32(s2_mair_attrs, 0, 4);
12614     s1hi = extract32(s1.attrs, 4, 4);
12615     s2hi = extract32(s2_mair_attrs, 4, 4);
12616 
12617     /* Combine memory type and cacheability attributes */
12618     if (s1hi == 0 || s2hi == 0) {
12619         /* Device has precedence over normal */
12620         if (s1lo == 0 || s2lo == 0) {
12621             /* nGnRnE has precedence over anything */
12622             ret_attrs = 0;
12623         } else if (s1lo == 4 || s2lo == 4) {
12624             /* non-Reordering has precedence over Reordering */
12625             ret_attrs = 4;  /* nGnRE */
12626         } else if (s1lo == 8 || s2lo == 8) {
12627             /* non-Gathering has precedence over Gathering */
12628             ret_attrs = 8;  /* nGRE */
12629         } else {
12630             ret_attrs = 0xc; /* GRE */
12631         }
12632     } else { /* Normal memory */
12633         /* Outer/inner cacheability combine independently */
12634         ret_attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12635                   | combine_cacheattr_nibble(s1lo, s2lo);
12636     }
12637     return ret_attrs;
12638 }
12639 
12640 static uint8_t force_cacheattr_nibble_wb(uint8_t attr)
12641 {
12642     /*
12643      * Given the 4 bits specifying the outer or inner cacheability
12644      * in MAIR format, return a value specifying Normal Write-Back,
12645      * with the allocation and transient hints taken from the input
12646      * if the input specified some kind of cacheable attribute.
12647      */
12648     if (attr == 0 || attr == 4) {
12649         /*
12650          * 0 == an UNPREDICTABLE encoding
12651          * 4 == Non-cacheable
12652          * Either way, force Write-Back RW allocate non-transient
12653          */
12654         return 0xf;
12655     }
12656     /* Change WriteThrough to WriteBack, keep allocation and transient hints */
12657     return attr | 4;
12658 }
12659 
12660 /*
12661  * Combine the memory type and cacheability attributes of
12662  * s1 and s2 for the HCR_EL2.FWB == 1 case, returning the
12663  * combined attributes in MAIR_EL1 format.
12664  */
12665 static uint8_t combined_attrs_fwb(CPUARMState *env,
12666                                   ARMCacheAttrs s1, ARMCacheAttrs s2)
12667 {
12668     switch (s2.attrs) {
12669     case 7:
12670         /* Use stage 1 attributes */
12671         return s1.attrs;
12672     case 6:
12673         /*
12674          * Force Normal Write-Back. Note that if S1 is Normal cacheable
12675          * then we take the allocation hints from it; otherwise it is
12676          * RW allocate, non-transient.
12677          */
12678         if ((s1.attrs & 0xf0) == 0) {
12679             /* S1 is Device */
12680             return 0xff;
12681         }
12682         /* Need to check the Inner and Outer nibbles separately */
12683         return force_cacheattr_nibble_wb(s1.attrs & 0xf) |
12684             force_cacheattr_nibble_wb(s1.attrs >> 4) << 4;
12685     case 5:
12686         /* If S1 attrs are Device, use them; otherwise Normal Non-cacheable */
12687         if ((s1.attrs & 0xf0) == 0) {
12688             return s1.attrs;
12689         }
12690         return 0x44;
12691     case 0 ... 3:
12692         /* Force Device, of subtype specified by S2 */
12693         return s2.attrs << 2;
12694     default:
12695         /*
12696          * RESERVED values (including RES0 descriptor bit [5] being nonzero);
12697          * arbitrarily force Device.
12698          */
12699         return 0;
12700     }
12701 }
12702 
12703 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12704  * and CombineS1S2Desc()
12705  *
12706  * @env:     CPUARMState
12707  * @s1:      Attributes from stage 1 walk
12708  * @s2:      Attributes from stage 2 walk
12709  */
12710 static ARMCacheAttrs combine_cacheattrs(CPUARMState *env,
12711                                         ARMCacheAttrs s1, ARMCacheAttrs s2)
12712 {
12713     ARMCacheAttrs ret;
12714     bool tagged = false;
12715 
12716     assert(s2.is_s2_format && !s1.is_s2_format);
12717     ret.is_s2_format = false;
12718 
12719     if (s1.attrs == 0xf0) {
12720         tagged = true;
12721         s1.attrs = 0xff;
12722     }
12723 
12724     /* Combine shareability attributes (table D4-43) */
12725     if (s1.shareability == 2 || s2.shareability == 2) {
12726         /* if either are outer-shareable, the result is outer-shareable */
12727         ret.shareability = 2;
12728     } else if (s1.shareability == 3 || s2.shareability == 3) {
12729         /* if either are inner-shareable, the result is inner-shareable */
12730         ret.shareability = 3;
12731     } else {
12732         /* both non-shareable */
12733         ret.shareability = 0;
12734     }
12735 
12736     /* Combine memory type and cacheability attributes */
12737     if (arm_hcr_el2_eff(env) & HCR_FWB) {
12738         ret.attrs = combined_attrs_fwb(env, s1, s2);
12739     } else {
12740         ret.attrs = combined_attrs_nofwb(env, s1, s2);
12741     }
12742 
12743     /*
12744      * Any location for which the resultant memory type is any
12745      * type of Device memory is always treated as Outer Shareable.
12746      * Any location for which the resultant memory type is Normal
12747      * Inner Non-cacheable, Outer Non-cacheable is always treated
12748      * as Outer Shareable.
12749      * TODO: FEAT_XS adds another value (0x40) also meaning iNCoNC
12750      */
12751     if ((ret.attrs & 0xf0) == 0 || ret.attrs == 0x44) {
12752         ret.shareability = 2;
12753     }
12754 
12755     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
12756     if (tagged && ret.attrs == 0xff) {
12757         ret.attrs = 0xf0;
12758     }
12759 
12760     return ret;
12761 }
12762 
12763 
12764 /* get_phys_addr - get the physical address for this virtual address
12765  *
12766  * Find the physical address corresponding to the given virtual address,
12767  * by doing a translation table walk on MMU based systems or using the
12768  * MPU state on MPU based systems.
12769  *
12770  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12771  * prot and page_size may not be filled in, and the populated fsr value provides
12772  * information on why the translation aborted, in the format of a
12773  * DFSR/IFSR fault register, with the following caveats:
12774  *  * we honour the short vs long DFSR format differences.
12775  *  * the WnR bit is never set (the caller must do this).
12776  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12777  *    value.
12778  *
12779  * @env: CPUARMState
12780  * @address: virtual address to get physical address for
12781  * @access_type: 0 for read, 1 for write, 2 for execute
12782  * @mmu_idx: MMU index indicating required translation regime
12783  * @phys_ptr: set to the physical address corresponding to the virtual address
12784  * @attrs: set to the memory transaction attributes to use
12785  * @prot: set to the permissions for the page containing phys_ptr
12786  * @page_size: set to the size of the page containing phys_ptr
12787  * @fi: set to fault info if the translation fails
12788  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12789  */
12790 bool get_phys_addr(CPUARMState *env, target_ulong address,
12791                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12792                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12793                    target_ulong *page_size,
12794                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12795 {
12796     ARMMMUIdx s1_mmu_idx = stage_1_mmu_idx(mmu_idx);
12797 
12798     if (mmu_idx != s1_mmu_idx) {
12799         /* Call ourselves recursively to do the stage 1 and then stage 2
12800          * translations if mmu_idx is a two-stage regime.
12801          */
12802         if (arm_feature(env, ARM_FEATURE_EL2)) {
12803             hwaddr ipa;
12804             int s2_prot;
12805             int ret;
12806             bool ipa_secure;
12807             ARMCacheAttrs cacheattrs2 = {};
12808             ARMMMUIdx s2_mmu_idx;
12809             bool is_el0;
12810 
12811             ret = get_phys_addr(env, address, access_type, s1_mmu_idx, &ipa,
12812                                 attrs, prot, page_size, fi, cacheattrs);
12813 
12814             /* If S1 fails or S2 is disabled, return early.  */
12815             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
12816                 *phys_ptr = ipa;
12817                 return ret;
12818             }
12819 
12820             ipa_secure = attrs->secure;
12821             if (arm_is_secure_below_el3(env)) {
12822                 if (ipa_secure) {
12823                     attrs->secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
12824                 } else {
12825                     attrs->secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
12826                 }
12827             } else {
12828                 assert(!ipa_secure);
12829             }
12830 
12831             s2_mmu_idx = attrs->secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
12832             is_el0 = mmu_idx == ARMMMUIdx_E10_0 || mmu_idx == ARMMMUIdx_SE10_0;
12833 
12834             /* S1 is done. Now do S2 translation.  */
12835             ret = get_phys_addr_lpae(env, ipa, access_type, s2_mmu_idx, is_el0,
12836                                      phys_ptr, attrs, &s2_prot,
12837                                      page_size, fi, &cacheattrs2);
12838             fi->s2addr = ipa;
12839             /* Combine the S1 and S2 perms.  */
12840             *prot &= s2_prot;
12841 
12842             /* If S2 fails, return early.  */
12843             if (ret) {
12844                 return ret;
12845             }
12846 
12847             /* Combine the S1 and S2 cache attributes. */
12848             if (arm_hcr_el2_eff(env) & HCR_DC) {
12849                 /*
12850                  * HCR.DC forces the first stage attributes to
12851                  *  Normal Non-Shareable,
12852                  *  Inner Write-Back Read-Allocate Write-Allocate,
12853                  *  Outer Write-Back Read-Allocate Write-Allocate.
12854                  * Do not overwrite Tagged within attrs.
12855                  */
12856                 if (cacheattrs->attrs != 0xf0) {
12857                     cacheattrs->attrs = 0xff;
12858                 }
12859                 cacheattrs->shareability = 0;
12860             }
12861             *cacheattrs = combine_cacheattrs(env, *cacheattrs, cacheattrs2);
12862 
12863             /* Check if IPA translates to secure or non-secure PA space. */
12864             if (arm_is_secure_below_el3(env)) {
12865                 if (ipa_secure) {
12866                     attrs->secure =
12867                         !(env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW));
12868                 } else {
12869                     attrs->secure =
12870                         !((env->cp15.vtcr_el2.raw_tcr & (VTCR_NSA | VTCR_NSW))
12871                         || (env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW)));
12872                 }
12873             }
12874             return 0;
12875         } else {
12876             /*
12877              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12878              */
12879             mmu_idx = stage_1_mmu_idx(mmu_idx);
12880         }
12881     }
12882 
12883     /* The page table entries may downgrade secure to non-secure, but
12884      * cannot upgrade an non-secure translation regime's attributes
12885      * to secure.
12886      */
12887     attrs->secure = regime_is_secure(env, mmu_idx);
12888     attrs->user = regime_is_user(env, mmu_idx);
12889 
12890     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12891      * In v7 and earlier it affects all stage 1 translations.
12892      */
12893     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
12894         && !arm_feature(env, ARM_FEATURE_V8)) {
12895         if (regime_el(env, mmu_idx) == 3) {
12896             address += env->cp15.fcseidr_s;
12897         } else {
12898             address += env->cp15.fcseidr_ns;
12899         }
12900     }
12901 
12902     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12903         bool ret;
12904         *page_size = TARGET_PAGE_SIZE;
12905 
12906         if (arm_feature(env, ARM_FEATURE_V8)) {
12907             /* PMSAv8 */
12908             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12909                                        phys_ptr, attrs, prot, page_size, fi);
12910         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12911             /* PMSAv7 */
12912             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12913                                        phys_ptr, prot, page_size, fi);
12914         } else {
12915             /* Pre-v7 MPU */
12916             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12917                                        phys_ptr, prot, fi);
12918         }
12919         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12920                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12921                       access_type == MMU_DATA_LOAD ? "reading" :
12922                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12923                       (uint32_t)address, mmu_idx,
12924                       ret ? "Miss" : "Hit",
12925                       *prot & PAGE_READ ? 'r' : '-',
12926                       *prot & PAGE_WRITE ? 'w' : '-',
12927                       *prot & PAGE_EXEC ? 'x' : '-');
12928 
12929         return ret;
12930     }
12931 
12932     /* Definitely a real MMU, not an MPU */
12933 
12934     if (regime_translation_disabled(env, mmu_idx)) {
12935         uint64_t hcr;
12936         uint8_t memattr;
12937 
12938         /*
12939          * MMU disabled.  S1 addresses within aa64 translation regimes are
12940          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
12941          */
12942         if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
12943             int r_el = regime_el(env, mmu_idx);
12944             if (arm_el_is_aa64(env, r_el)) {
12945                 int pamax = arm_pamax(env_archcpu(env));
12946                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
12947                 int addrtop, tbi;
12948 
12949                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
12950                 if (access_type == MMU_INST_FETCH) {
12951                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
12952                 }
12953                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
12954                 addrtop = (tbi ? 55 : 63);
12955 
12956                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
12957                     fi->type = ARMFault_AddressSize;
12958                     fi->level = 0;
12959                     fi->stage2 = false;
12960                     return 1;
12961                 }
12962 
12963                 /*
12964                  * When TBI is disabled, we've just validated that all of the
12965                  * bits above PAMax are zero, so logically we only need to
12966                  * clear the top byte for TBI.  But it's clearer to follow
12967                  * the pseudocode set of addrdesc.paddress.
12968                  */
12969                 address = extract64(address, 0, 52);
12970             }
12971         }
12972         *phys_ptr = address;
12973         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12974         *page_size = TARGET_PAGE_SIZE;
12975 
12976         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
12977         hcr = arm_hcr_el2_eff(env);
12978         cacheattrs->shareability = 0;
12979         cacheattrs->is_s2_format = false;
12980         if (hcr & HCR_DC) {
12981             if (hcr & HCR_DCT) {
12982                 memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
12983             } else {
12984                 memattr = 0xff;  /* Normal, WB, RWA */
12985             }
12986         } else if (access_type == MMU_INST_FETCH) {
12987             if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
12988                 memattr = 0xee;  /* Normal, WT, RA, NT */
12989             } else {
12990                 memattr = 0x44;  /* Normal, NC, No */
12991             }
12992             cacheattrs->shareability = 2; /* outer sharable */
12993         } else {
12994             memattr = 0x00;      /* Device, nGnRnE */
12995         }
12996         cacheattrs->attrs = memattr;
12997         return 0;
12998     }
12999 
13000     if (regime_using_lpae_format(env, mmu_idx)) {
13001         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
13002                                   phys_ptr, attrs, prot, page_size,
13003                                   fi, cacheattrs);
13004     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
13005         return get_phys_addr_v6(env, address, access_type, mmu_idx,
13006                                 phys_ptr, attrs, prot, page_size, fi);
13007     } else {
13008         return get_phys_addr_v5(env, address, access_type, mmu_idx,
13009                                     phys_ptr, prot, page_size, fi);
13010     }
13011 }
13012 
13013 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
13014                                          MemTxAttrs *attrs)
13015 {
13016     ARMCPU *cpu = ARM_CPU(cs);
13017     CPUARMState *env = &cpu->env;
13018     hwaddr phys_addr;
13019     target_ulong page_size;
13020     int prot;
13021     bool ret;
13022     ARMMMUFaultInfo fi = {};
13023     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
13024     ARMCacheAttrs cacheattrs = {};
13025 
13026     *attrs = (MemTxAttrs) {};
13027 
13028     ret = get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &phys_addr,
13029                         attrs, &prot, &page_size, &fi, &cacheattrs);
13030 
13031     if (ret) {
13032         return -1;
13033     }
13034     return phys_addr;
13035 }
13036 
13037 #endif
13038 
13039 /* Note that signed overflow is undefined in C.  The following routines are
13040    careful to use unsigned types where modulo arithmetic is required.
13041    Failure to do so _will_ break on newer gcc.  */
13042 
13043 /* Signed saturating arithmetic.  */
13044 
13045 /* Perform 16-bit signed saturating addition.  */
13046 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
13047 {
13048     uint16_t res;
13049 
13050     res = a + b;
13051     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
13052         if (a & 0x8000)
13053             res = 0x8000;
13054         else
13055             res = 0x7fff;
13056     }
13057     return res;
13058 }
13059 
13060 /* Perform 8-bit signed saturating addition.  */
13061 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
13062 {
13063     uint8_t res;
13064 
13065     res = a + b;
13066     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
13067         if (a & 0x80)
13068             res = 0x80;
13069         else
13070             res = 0x7f;
13071     }
13072     return res;
13073 }
13074 
13075 /* Perform 16-bit signed saturating subtraction.  */
13076 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
13077 {
13078     uint16_t res;
13079 
13080     res = a - b;
13081     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
13082         if (a & 0x8000)
13083             res = 0x8000;
13084         else
13085             res = 0x7fff;
13086     }
13087     return res;
13088 }
13089 
13090 /* Perform 8-bit signed saturating subtraction.  */
13091 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
13092 {
13093     uint8_t res;
13094 
13095     res = a - b;
13096     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
13097         if (a & 0x80)
13098             res = 0x80;
13099         else
13100             res = 0x7f;
13101     }
13102     return res;
13103 }
13104 
13105 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
13106 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
13107 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
13108 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
13109 #define PFX q
13110 
13111 #include "op_addsub.h"
13112 
13113 /* Unsigned saturating arithmetic.  */
13114 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
13115 {
13116     uint16_t res;
13117     res = a + b;
13118     if (res < a)
13119         res = 0xffff;
13120     return res;
13121 }
13122 
13123 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
13124 {
13125     if (a > b)
13126         return a - b;
13127     else
13128         return 0;
13129 }
13130 
13131 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
13132 {
13133     uint8_t res;
13134     res = a + b;
13135     if (res < a)
13136         res = 0xff;
13137     return res;
13138 }
13139 
13140 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
13141 {
13142     if (a > b)
13143         return a - b;
13144     else
13145         return 0;
13146 }
13147 
13148 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
13149 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
13150 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
13151 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
13152 #define PFX uq
13153 
13154 #include "op_addsub.h"
13155 
13156 /* Signed modulo arithmetic.  */
13157 #define SARITH16(a, b, n, op) do { \
13158     int32_t sum; \
13159     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
13160     RESULT(sum, n, 16); \
13161     if (sum >= 0) \
13162         ge |= 3 << (n * 2); \
13163     } while(0)
13164 
13165 #define SARITH8(a, b, n, op) do { \
13166     int32_t sum; \
13167     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
13168     RESULT(sum, n, 8); \
13169     if (sum >= 0) \
13170         ge |= 1 << n; \
13171     } while(0)
13172 
13173 
13174 #define ADD16(a, b, n) SARITH16(a, b, n, +)
13175 #define SUB16(a, b, n) SARITH16(a, b, n, -)
13176 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
13177 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
13178 #define PFX s
13179 #define ARITH_GE
13180 
13181 #include "op_addsub.h"
13182 
13183 /* Unsigned modulo arithmetic.  */
13184 #define ADD16(a, b, n) do { \
13185     uint32_t sum; \
13186     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
13187     RESULT(sum, n, 16); \
13188     if ((sum >> 16) == 1) \
13189         ge |= 3 << (n * 2); \
13190     } while(0)
13191 
13192 #define ADD8(a, b, n) do { \
13193     uint32_t sum; \
13194     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
13195     RESULT(sum, n, 8); \
13196     if ((sum >> 8) == 1) \
13197         ge |= 1 << n; \
13198     } while(0)
13199 
13200 #define SUB16(a, b, n) do { \
13201     uint32_t sum; \
13202     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
13203     RESULT(sum, n, 16); \
13204     if ((sum >> 16) == 0) \
13205         ge |= 3 << (n * 2); \
13206     } while(0)
13207 
13208 #define SUB8(a, b, n) do { \
13209     uint32_t sum; \
13210     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
13211     RESULT(sum, n, 8); \
13212     if ((sum >> 8) == 0) \
13213         ge |= 1 << n; \
13214     } while(0)
13215 
13216 #define PFX u
13217 #define ARITH_GE
13218 
13219 #include "op_addsub.h"
13220 
13221 /* Halved signed arithmetic.  */
13222 #define ADD16(a, b, n) \
13223   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
13224 #define SUB16(a, b, n) \
13225   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
13226 #define ADD8(a, b, n) \
13227   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
13228 #define SUB8(a, b, n) \
13229   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
13230 #define PFX sh
13231 
13232 #include "op_addsub.h"
13233 
13234 /* Halved unsigned arithmetic.  */
13235 #define ADD16(a, b, n) \
13236   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13237 #define SUB16(a, b, n) \
13238   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13239 #define ADD8(a, b, n) \
13240   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13241 #define SUB8(a, b, n) \
13242   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13243 #define PFX uh
13244 
13245 #include "op_addsub.h"
13246 
13247 static inline uint8_t do_usad(uint8_t a, uint8_t b)
13248 {
13249     if (a > b)
13250         return a - b;
13251     else
13252         return b - a;
13253 }
13254 
13255 /* Unsigned sum of absolute byte differences.  */
13256 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
13257 {
13258     uint32_t sum;
13259     sum = do_usad(a, b);
13260     sum += do_usad(a >> 8, b >> 8);
13261     sum += do_usad(a >> 16, b >> 16);
13262     sum += do_usad(a >> 24, b >> 24);
13263     return sum;
13264 }
13265 
13266 /* For ARMv6 SEL instruction.  */
13267 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
13268 {
13269     uint32_t mask;
13270 
13271     mask = 0;
13272     if (flags & 1)
13273         mask |= 0xff;
13274     if (flags & 2)
13275         mask |= 0xff00;
13276     if (flags & 4)
13277         mask |= 0xff0000;
13278     if (flags & 8)
13279         mask |= 0xff000000;
13280     return (a & mask) | (b & ~mask);
13281 }
13282 
13283 /* CRC helpers.
13284  * The upper bytes of val (above the number specified by 'bytes') must have
13285  * been zeroed out by the caller.
13286  */
13287 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
13288 {
13289     uint8_t buf[4];
13290 
13291     stl_le_p(buf, val);
13292 
13293     /* zlib crc32 converts the accumulator and output to one's complement.  */
13294     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
13295 }
13296 
13297 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
13298 {
13299     uint8_t buf[4];
13300 
13301     stl_le_p(buf, val);
13302 
13303     /* Linux crc32c converts the output to one's complement.  */
13304     return crc32c(acc, buf, bytes) ^ 0xffffffff;
13305 }
13306 
13307 /* Return the exception level to which FP-disabled exceptions should
13308  * be taken, or 0 if FP is enabled.
13309  */
13310 int fp_exception_el(CPUARMState *env, int cur_el)
13311 {
13312 #ifndef CONFIG_USER_ONLY
13313     uint64_t hcr_el2;
13314 
13315     /* CPACR and the CPTR registers don't exist before v6, so FP is
13316      * always accessible
13317      */
13318     if (!arm_feature(env, ARM_FEATURE_V6)) {
13319         return 0;
13320     }
13321 
13322     if (arm_feature(env, ARM_FEATURE_M)) {
13323         /* CPACR can cause a NOCP UsageFault taken to current security state */
13324         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
13325             return 1;
13326         }
13327 
13328         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
13329             if (!extract32(env->v7m.nsacr, 10, 1)) {
13330                 /* FP insns cause a NOCP UsageFault taken to Secure */
13331                 return 3;
13332             }
13333         }
13334 
13335         return 0;
13336     }
13337 
13338     hcr_el2 = arm_hcr_el2_eff(env);
13339 
13340     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
13341      * 0, 2 : trap EL0 and EL1/PL1 accesses
13342      * 1    : trap only EL0 accesses
13343      * 3    : trap no accesses
13344      * This register is ignored if E2H+TGE are both set.
13345      */
13346     if ((hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13347         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
13348 
13349         switch (fpen) {
13350         case 0:
13351         case 2:
13352             if (cur_el == 0 || cur_el == 1) {
13353                 /* Trap to PL1, which might be EL1 or EL3 */
13354                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
13355                     return 3;
13356                 }
13357                 return 1;
13358             }
13359             if (cur_el == 3 && !is_a64(env)) {
13360                 /* Secure PL1 running at EL3 */
13361                 return 3;
13362             }
13363             break;
13364         case 1:
13365             if (cur_el == 0) {
13366                 return 1;
13367             }
13368             break;
13369         case 3:
13370             break;
13371         }
13372     }
13373 
13374     /*
13375      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
13376      * to control non-secure access to the FPU. It doesn't have any
13377      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
13378      */
13379     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
13380          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
13381         if (!extract32(env->cp15.nsacr, 10, 1)) {
13382             /* FP insns act as UNDEF */
13383             return cur_el == 2 ? 2 : 1;
13384         }
13385     }
13386 
13387     /*
13388      * CPTR_EL2 is present in v7VE or v8, and changes format
13389      * with HCR_EL2.E2H (regardless of TGE).
13390      */
13391     if (cur_el <= 2) {
13392         if (hcr_el2 & HCR_E2H) {
13393             /* Check CPTR_EL2.FPEN.  */
13394             switch (extract32(env->cp15.cptr_el[2], 20, 2)) {
13395             case 1:
13396                 if (cur_el != 0 || !(hcr_el2 & HCR_TGE)) {
13397                     break;
13398                 }
13399                 /* fall through */
13400             case 0:
13401             case 2:
13402                 return 2;
13403             }
13404         } else if (arm_is_el2_enabled(env)) {
13405             if (env->cp15.cptr_el[2] & CPTR_TFP) {
13406                 return 2;
13407             }
13408         }
13409     }
13410 
13411     /* CPTR_EL3 : present in v8 */
13412     if (env->cp15.cptr_el[3] & CPTR_TFP) {
13413         /* Trap all FP ops to EL3 */
13414         return 3;
13415     }
13416 #endif
13417     return 0;
13418 }
13419 
13420 /* Return the exception level we're running at if this is our mmu_idx */
13421 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
13422 {
13423     if (mmu_idx & ARM_MMU_IDX_M) {
13424         return mmu_idx & ARM_MMU_IDX_M_PRIV;
13425     }
13426 
13427     switch (mmu_idx) {
13428     case ARMMMUIdx_E10_0:
13429     case ARMMMUIdx_E20_0:
13430     case ARMMMUIdx_SE10_0:
13431     case ARMMMUIdx_SE20_0:
13432         return 0;
13433     case ARMMMUIdx_E10_1:
13434     case ARMMMUIdx_E10_1_PAN:
13435     case ARMMMUIdx_SE10_1:
13436     case ARMMMUIdx_SE10_1_PAN:
13437         return 1;
13438     case ARMMMUIdx_E2:
13439     case ARMMMUIdx_E20_2:
13440     case ARMMMUIdx_E20_2_PAN:
13441     case ARMMMUIdx_SE2:
13442     case ARMMMUIdx_SE20_2:
13443     case ARMMMUIdx_SE20_2_PAN:
13444         return 2;
13445     case ARMMMUIdx_SE3:
13446         return 3;
13447     default:
13448         g_assert_not_reached();
13449     }
13450 }
13451 
13452 #ifndef CONFIG_TCG
13453 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
13454 {
13455     g_assert_not_reached();
13456 }
13457 #endif
13458 
13459 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
13460 {
13461     ARMMMUIdx idx;
13462     uint64_t hcr;
13463 
13464     if (arm_feature(env, ARM_FEATURE_M)) {
13465         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
13466     }
13467 
13468     /* See ARM pseudo-function ELIsInHost.  */
13469     switch (el) {
13470     case 0:
13471         hcr = arm_hcr_el2_eff(env);
13472         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
13473             idx = ARMMMUIdx_E20_0;
13474         } else {
13475             idx = ARMMMUIdx_E10_0;
13476         }
13477         break;
13478     case 1:
13479         if (env->pstate & PSTATE_PAN) {
13480             idx = ARMMMUIdx_E10_1_PAN;
13481         } else {
13482             idx = ARMMMUIdx_E10_1;
13483         }
13484         break;
13485     case 2:
13486         /* Note that TGE does not apply at EL2.  */
13487         if (arm_hcr_el2_eff(env) & HCR_E2H) {
13488             if (env->pstate & PSTATE_PAN) {
13489                 idx = ARMMMUIdx_E20_2_PAN;
13490             } else {
13491                 idx = ARMMMUIdx_E20_2;
13492             }
13493         } else {
13494             idx = ARMMMUIdx_E2;
13495         }
13496         break;
13497     case 3:
13498         return ARMMMUIdx_SE3;
13499     default:
13500         g_assert_not_reached();
13501     }
13502 
13503     if (arm_is_secure_below_el3(env)) {
13504         idx &= ~ARM_MMU_IDX_A_NS;
13505     }
13506 
13507     return idx;
13508 }
13509 
13510 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
13511 {
13512     return arm_mmu_idx_el(env, arm_current_el(env));
13513 }
13514 
13515 #ifndef CONFIG_USER_ONLY
13516 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
13517 {
13518     return stage_1_mmu_idx(arm_mmu_idx(env));
13519 }
13520 #endif
13521 
13522 static CPUARMTBFlags rebuild_hflags_common(CPUARMState *env, int fp_el,
13523                                            ARMMMUIdx mmu_idx,
13524                                            CPUARMTBFlags flags)
13525 {
13526     DP_TBFLAG_ANY(flags, FPEXC_EL, fp_el);
13527     DP_TBFLAG_ANY(flags, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
13528 
13529     if (arm_singlestep_active(env)) {
13530         DP_TBFLAG_ANY(flags, SS_ACTIVE, 1);
13531     }
13532     return flags;
13533 }
13534 
13535 static CPUARMTBFlags rebuild_hflags_common_32(CPUARMState *env, int fp_el,
13536                                               ARMMMUIdx mmu_idx,
13537                                               CPUARMTBFlags flags)
13538 {
13539     bool sctlr_b = arm_sctlr_b(env);
13540 
13541     if (sctlr_b) {
13542         DP_TBFLAG_A32(flags, SCTLR__B, 1);
13543     }
13544     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
13545         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13546     }
13547     DP_TBFLAG_A32(flags, NS, !access_secure_reg(env));
13548 
13549     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13550 }
13551 
13552 static CPUARMTBFlags rebuild_hflags_m32(CPUARMState *env, int fp_el,
13553                                         ARMMMUIdx mmu_idx)
13554 {
13555     CPUARMTBFlags flags = {};
13556     uint32_t ccr = env->v7m.ccr[env->v7m.secure];
13557 
13558     /* Without HaveMainExt, CCR.UNALIGN_TRP is RES1. */
13559     if (ccr & R_V7M_CCR_UNALIGN_TRP_MASK) {
13560         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13561     }
13562 
13563     if (arm_v7m_is_handler_mode(env)) {
13564         DP_TBFLAG_M32(flags, HANDLER, 1);
13565     }
13566 
13567     /*
13568      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
13569      * is suppressing them because the requested execution priority
13570      * is less than 0.
13571      */
13572     if (arm_feature(env, ARM_FEATURE_V8) &&
13573         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
13574           (ccr & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13575         DP_TBFLAG_M32(flags, STACKCHECK, 1);
13576     }
13577 
13578     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13579 }
13580 
13581 static CPUARMTBFlags rebuild_hflags_aprofile(CPUARMState *env)
13582 {
13583     CPUARMTBFlags flags = {};
13584 
13585     DP_TBFLAG_ANY(flags, DEBUG_TARGET_EL, arm_debug_target_el(env));
13586     return flags;
13587 }
13588 
13589 static CPUARMTBFlags rebuild_hflags_a32(CPUARMState *env, int fp_el,
13590                                         ARMMMUIdx mmu_idx)
13591 {
13592     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13593     int el = arm_current_el(env);
13594 
13595     if (arm_sctlr(env, el) & SCTLR_A) {
13596         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13597     }
13598 
13599     if (arm_el_is_aa64(env, 1)) {
13600         DP_TBFLAG_A32(flags, VFPEN, 1);
13601     }
13602 
13603     if (el < 2 && env->cp15.hstr_el2 &&
13604         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13605         DP_TBFLAG_A32(flags, HSTR_ACTIVE, 1);
13606     }
13607 
13608     if (env->uncached_cpsr & CPSR_IL) {
13609         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13610     }
13611 
13612     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13613 }
13614 
13615 static CPUARMTBFlags rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
13616                                         ARMMMUIdx mmu_idx)
13617 {
13618     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13619     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13620     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
13621     uint64_t sctlr;
13622     int tbii, tbid;
13623 
13624     DP_TBFLAG_ANY(flags, AARCH64_STATE, 1);
13625 
13626     /* Get control bits for tagged addresses.  */
13627     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
13628     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
13629 
13630     DP_TBFLAG_A64(flags, TBII, tbii);
13631     DP_TBFLAG_A64(flags, TBID, tbid);
13632 
13633     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
13634         int sve_el = sve_exception_el(env, el);
13635         uint32_t zcr_len;
13636 
13637         /*
13638          * If SVE is disabled, but FP is enabled,
13639          * then the effective len is 0.
13640          */
13641         if (sve_el != 0 && fp_el == 0) {
13642             zcr_len = 0;
13643         } else {
13644             zcr_len = sve_zcr_len_for_el(env, el);
13645         }
13646         DP_TBFLAG_A64(flags, SVEEXC_EL, sve_el);
13647         DP_TBFLAG_A64(flags, ZCR_LEN, zcr_len);
13648     }
13649 
13650     sctlr = regime_sctlr(env, stage1);
13651 
13652     if (sctlr & SCTLR_A) {
13653         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13654     }
13655 
13656     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
13657         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13658     }
13659 
13660     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
13661         /*
13662          * In order to save space in flags, we record only whether
13663          * pauth is "inactive", meaning all insns are implemented as
13664          * a nop, or "active" when some action must be performed.
13665          * The decision of which action to take is left to a helper.
13666          */
13667         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13668             DP_TBFLAG_A64(flags, PAUTH_ACTIVE, 1);
13669         }
13670     }
13671 
13672     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13673         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13674         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13675             DP_TBFLAG_A64(flags, BT, 1);
13676         }
13677     }
13678 
13679     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
13680     if (!(env->pstate & PSTATE_UAO)) {
13681         switch (mmu_idx) {
13682         case ARMMMUIdx_E10_1:
13683         case ARMMMUIdx_E10_1_PAN:
13684         case ARMMMUIdx_SE10_1:
13685         case ARMMMUIdx_SE10_1_PAN:
13686             /* TODO: ARMv8.3-NV */
13687             DP_TBFLAG_A64(flags, UNPRIV, 1);
13688             break;
13689         case ARMMMUIdx_E20_2:
13690         case ARMMMUIdx_E20_2_PAN:
13691         case ARMMMUIdx_SE20_2:
13692         case ARMMMUIdx_SE20_2_PAN:
13693             /*
13694              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
13695              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
13696              */
13697             if (env->cp15.hcr_el2 & HCR_TGE) {
13698                 DP_TBFLAG_A64(flags, UNPRIV, 1);
13699             }
13700             break;
13701         default:
13702             break;
13703         }
13704     }
13705 
13706     if (env->pstate & PSTATE_IL) {
13707         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13708     }
13709 
13710     if (cpu_isar_feature(aa64_mte, env_archcpu(env))) {
13711         /*
13712          * Set MTE_ACTIVE if any access may be Checked, and leave clear
13713          * if all accesses must be Unchecked:
13714          * 1) If no TBI, then there are no tags in the address to check,
13715          * 2) If Tag Check Override, then all accesses are Unchecked,
13716          * 3) If Tag Check Fail == 0, then Checked access have no effect,
13717          * 4) If no Allocation Tag Access, then all accesses are Unchecked.
13718          */
13719         if (allocation_tag_access_enabled(env, el, sctlr)) {
13720             DP_TBFLAG_A64(flags, ATA, 1);
13721             if (tbid
13722                 && !(env->pstate & PSTATE_TCO)
13723                 && (sctlr & (el == 0 ? SCTLR_TCF0 : SCTLR_TCF))) {
13724                 DP_TBFLAG_A64(flags, MTE_ACTIVE, 1);
13725             }
13726         }
13727         /* And again for unprivileged accesses, if required.  */
13728         if (EX_TBFLAG_A64(flags, UNPRIV)
13729             && tbid
13730             && !(env->pstate & PSTATE_TCO)
13731             && (sctlr & SCTLR_TCF0)
13732             && allocation_tag_access_enabled(env, 0, sctlr)) {
13733             DP_TBFLAG_A64(flags, MTE0_ACTIVE, 1);
13734         }
13735         /* Cache TCMA as well as TBI. */
13736         DP_TBFLAG_A64(flags, TCMA, aa64_va_parameter_tcma(tcr, mmu_idx));
13737     }
13738 
13739     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13740 }
13741 
13742 static CPUARMTBFlags rebuild_hflags_internal(CPUARMState *env)
13743 {
13744     int el = arm_current_el(env);
13745     int fp_el = fp_exception_el(env, el);
13746     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13747 
13748     if (is_a64(env)) {
13749         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13750     } else if (arm_feature(env, ARM_FEATURE_M)) {
13751         return rebuild_hflags_m32(env, fp_el, mmu_idx);
13752     } else {
13753         return rebuild_hflags_a32(env, fp_el, mmu_idx);
13754     }
13755 }
13756 
13757 void arm_rebuild_hflags(CPUARMState *env)
13758 {
13759     env->hflags = rebuild_hflags_internal(env);
13760 }
13761 
13762 /*
13763  * If we have triggered a EL state change we can't rely on the
13764  * translator having passed it to us, we need to recompute.
13765  */
13766 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
13767 {
13768     int el = arm_current_el(env);
13769     int fp_el = fp_exception_el(env, el);
13770     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13771 
13772     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13773 }
13774 
13775 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
13776 {
13777     int fp_el = fp_exception_el(env, el);
13778     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13779 
13780     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13781 }
13782 
13783 /*
13784  * If we have triggered a EL state change we can't rely on the
13785  * translator having passed it to us, we need to recompute.
13786  */
13787 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
13788 {
13789     int el = arm_current_el(env);
13790     int fp_el = fp_exception_el(env, el);
13791     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13792     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13793 }
13794 
13795 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
13796 {
13797     int fp_el = fp_exception_el(env, el);
13798     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13799 
13800     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13801 }
13802 
13803 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
13804 {
13805     int fp_el = fp_exception_el(env, el);
13806     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13807 
13808     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13809 }
13810 
13811 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
13812 {
13813 #ifdef CONFIG_DEBUG_TCG
13814     CPUARMTBFlags c = env->hflags;
13815     CPUARMTBFlags r = rebuild_hflags_internal(env);
13816 
13817     if (unlikely(c.flags != r.flags || c.flags2 != r.flags2)) {
13818         fprintf(stderr, "TCG hflags mismatch "
13819                         "(current:(0x%08x,0x" TARGET_FMT_lx ")"
13820                         " rebuilt:(0x%08x,0x" TARGET_FMT_lx ")\n",
13821                 c.flags, c.flags2, r.flags, r.flags2);
13822         abort();
13823     }
13824 #endif
13825 }
13826 
13827 static bool mve_no_pred(CPUARMState *env)
13828 {
13829     /*
13830      * Return true if there is definitely no predication of MVE
13831      * instructions by VPR or LTPSIZE. (Returning false even if there
13832      * isn't any predication is OK; generated code will just be
13833      * a little worse.)
13834      * If the CPU does not implement MVE then this TB flag is always 0.
13835      *
13836      * NOTE: if you change this logic, the "recalculate s->mve_no_pred"
13837      * logic in gen_update_fp_context() needs to be updated to match.
13838      *
13839      * We do not include the effect of the ECI bits here -- they are
13840      * tracked in other TB flags. This simplifies the logic for
13841      * "when did we emit code that changes the MVE_NO_PRED TB flag
13842      * and thus need to end the TB?".
13843      */
13844     if (cpu_isar_feature(aa32_mve, env_archcpu(env))) {
13845         return false;
13846     }
13847     if (env->v7m.vpr) {
13848         return false;
13849     }
13850     if (env->v7m.ltpsize < 4) {
13851         return false;
13852     }
13853     return true;
13854 }
13855 
13856 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13857                           target_ulong *cs_base, uint32_t *pflags)
13858 {
13859     CPUARMTBFlags flags;
13860 
13861     assert_hflags_rebuild_correctly(env);
13862     flags = env->hflags;
13863 
13864     if (EX_TBFLAG_ANY(flags, AARCH64_STATE)) {
13865         *pc = env->pc;
13866         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13867             DP_TBFLAG_A64(flags, BTYPE, env->btype);
13868         }
13869     } else {
13870         *pc = env->regs[15];
13871 
13872         if (arm_feature(env, ARM_FEATURE_M)) {
13873             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13874                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
13875                 != env->v7m.secure) {
13876                 DP_TBFLAG_M32(flags, FPCCR_S_WRONG, 1);
13877             }
13878 
13879             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13880                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13881                  (env->v7m.secure &&
13882                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13883                 /*
13884                  * ASPEN is set, but FPCA/SFPA indicate that there is no
13885                  * active FP context; we must create a new FP context before
13886                  * executing any FP insn.
13887                  */
13888                 DP_TBFLAG_M32(flags, NEW_FP_CTXT_NEEDED, 1);
13889             }
13890 
13891             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13892             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13893                 DP_TBFLAG_M32(flags, LSPACT, 1);
13894             }
13895 
13896             if (mve_no_pred(env)) {
13897                 DP_TBFLAG_M32(flags, MVE_NO_PRED, 1);
13898             }
13899         } else {
13900             /*
13901              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
13902              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
13903              */
13904             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13905                 DP_TBFLAG_A32(flags, XSCALE_CPAR, env->cp15.c15_cpar);
13906             } else {
13907                 DP_TBFLAG_A32(flags, VECLEN, env->vfp.vec_len);
13908                 DP_TBFLAG_A32(flags, VECSTRIDE, env->vfp.vec_stride);
13909             }
13910             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
13911                 DP_TBFLAG_A32(flags, VFPEN, 1);
13912             }
13913         }
13914 
13915         DP_TBFLAG_AM32(flags, THUMB, env->thumb);
13916         DP_TBFLAG_AM32(flags, CONDEXEC, env->condexec_bits);
13917     }
13918 
13919     /*
13920      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13921      * states defined in the ARM ARM for software singlestep:
13922      *  SS_ACTIVE   PSTATE.SS   State
13923      *     0            x       Inactive (the TB flag for SS is always 0)
13924      *     1            0       Active-pending
13925      *     1            1       Active-not-pending
13926      * SS_ACTIVE is set in hflags; PSTATE__SS is computed every TB.
13927      */
13928     if (EX_TBFLAG_ANY(flags, SS_ACTIVE) && (env->pstate & PSTATE_SS)) {
13929         DP_TBFLAG_ANY(flags, PSTATE__SS, 1);
13930     }
13931 
13932     *pflags = flags.flags;
13933     *cs_base = flags.flags2;
13934 }
13935 
13936 #ifdef TARGET_AARCH64
13937 /*
13938  * The manual says that when SVE is enabled and VQ is widened the
13939  * implementation is allowed to zero the previously inaccessible
13940  * portion of the registers.  The corollary to that is that when
13941  * SVE is enabled and VQ is narrowed we are also allowed to zero
13942  * the now inaccessible portion of the registers.
13943  *
13944  * The intent of this is that no predicate bit beyond VQ is ever set.
13945  * Which means that some operations on predicate registers themselves
13946  * may operate on full uint64_t or even unrolled across the maximum
13947  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13948  * may well be cheaper than conditionals to restrict the operation
13949  * to the relevant portion of a uint16_t[16].
13950  */
13951 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13952 {
13953     int i, j;
13954     uint64_t pmask;
13955 
13956     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13957     assert(vq <= env_archcpu(env)->sve_max_vq);
13958 
13959     /* Zap the high bits of the zregs.  */
13960     for (i = 0; i < 32; i++) {
13961         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13962     }
13963 
13964     /* Zap the high bits of the pregs and ffr.  */
13965     pmask = 0;
13966     if (vq & 3) {
13967         pmask = ~(-1ULL << (16 * (vq & 3)));
13968     }
13969     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13970         for (i = 0; i < 17; ++i) {
13971             env->vfp.pregs[i].p[j] &= pmask;
13972         }
13973         pmask = 0;
13974     }
13975 }
13976 
13977 /*
13978  * Notice a change in SVE vector size when changing EL.
13979  */
13980 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13981                            int new_el, bool el0_a64)
13982 {
13983     ARMCPU *cpu = env_archcpu(env);
13984     int old_len, new_len;
13985     bool old_a64, new_a64;
13986 
13987     /* Nothing to do if no SVE.  */
13988     if (!cpu_isar_feature(aa64_sve, cpu)) {
13989         return;
13990     }
13991 
13992     /* Nothing to do if FP is disabled in either EL.  */
13993     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13994         return;
13995     }
13996 
13997     /*
13998      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13999      * at ELx, or not available because the EL is in AArch32 state, then
14000      * for all purposes other than a direct read, the ZCR_ELx.LEN field
14001      * has an effective value of 0".
14002      *
14003      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
14004      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
14005      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
14006      * we already have the correct register contents when encountering the
14007      * vq0->vq0 transition between EL0->EL1.
14008      */
14009     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
14010     old_len = (old_a64 && !sve_exception_el(env, old_el)
14011                ? sve_zcr_len_for_el(env, old_el) : 0);
14012     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
14013     new_len = (new_a64 && !sve_exception_el(env, new_el)
14014                ? sve_zcr_len_for_el(env, new_el) : 0);
14015 
14016     /* When changing vector length, clear inaccessible state.  */
14017     if (new_len < old_len) {
14018         aarch64_sve_narrow_vq(env, new_len + 1);
14019     }
14020 }
14021 #endif
14022