xref: /openbmc/qemu/target/arm/helper.c (revision e95c74c5e5522f6270092b788c3a96dfd8a93671)
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     } else {
1774         valid_mask &= ~(SCR_RW | SCR_ST);
1775         if (cpu_isar_feature(aa32_ras, cpu)) {
1776             valid_mask |= SCR_TERR;
1777         }
1778     }
1779 
1780     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1781         valid_mask &= ~SCR_HCE;
1782 
1783         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1784          * supported if EL2 exists. The bit is UNK/SBZP when
1785          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1786          * when EL2 is unavailable.
1787          * On ARMv8, this bit is always available.
1788          */
1789         if (arm_feature(env, ARM_FEATURE_V7) &&
1790             !arm_feature(env, ARM_FEATURE_V8)) {
1791             valid_mask &= ~SCR_SMD;
1792         }
1793     }
1794 
1795     /* Clear all-context RES0 bits.  */
1796     value &= valid_mask;
1797     raw_write(env, ri, value);
1798 }
1799 
1800 static void scr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1801 {
1802     /*
1803      * scr_write will set the RES1 bits on an AArch64-only CPU.
1804      * The reset value will be 0x30 on an AArch64-only CPU and 0 otherwise.
1805      */
1806     scr_write(env, ri, 0);
1807 }
1808 
1809 static CPAccessResult access_aa64_tid2(CPUARMState *env,
1810                                        const ARMCPRegInfo *ri,
1811                                        bool isread)
1812 {
1813     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
1814         return CP_ACCESS_TRAP_EL2;
1815     }
1816 
1817     return CP_ACCESS_OK;
1818 }
1819 
1820 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1821 {
1822     ARMCPU *cpu = env_archcpu(env);
1823 
1824     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
1825      * bank
1826      */
1827     uint32_t index = A32_BANKED_REG_GET(env, csselr,
1828                                         ri->secure & ARM_CP_SECSTATE_S);
1829 
1830     return cpu->ccsidr[index];
1831 }
1832 
1833 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1834                          uint64_t value)
1835 {
1836     raw_write(env, ri, value & 0xf);
1837 }
1838 
1839 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1840 {
1841     CPUState *cs = env_cpu(env);
1842     bool el1 = arm_current_el(env) == 1;
1843     uint64_t hcr_el2 = el1 ? arm_hcr_el2_eff(env) : 0;
1844     uint64_t ret = 0;
1845 
1846     if (hcr_el2 & HCR_IMO) {
1847         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
1848             ret |= CPSR_I;
1849         }
1850     } else {
1851         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
1852             ret |= CPSR_I;
1853         }
1854     }
1855 
1856     if (hcr_el2 & HCR_FMO) {
1857         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
1858             ret |= CPSR_F;
1859         }
1860     } else {
1861         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
1862             ret |= CPSR_F;
1863         }
1864     }
1865 
1866     if (hcr_el2 & HCR_AMO) {
1867         if (cs->interrupt_request & CPU_INTERRUPT_VSERR) {
1868             ret |= CPSR_A;
1869         }
1870     }
1871 
1872     return ret;
1873 }
1874 
1875 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1876                                        bool isread)
1877 {
1878     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
1879         return CP_ACCESS_TRAP_EL2;
1880     }
1881 
1882     return CP_ACCESS_OK;
1883 }
1884 
1885 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
1886                                        bool isread)
1887 {
1888     if (arm_feature(env, ARM_FEATURE_V8)) {
1889         return access_aa64_tid1(env, ri, isread);
1890     }
1891 
1892     return CP_ACCESS_OK;
1893 }
1894 
1895 static const ARMCPRegInfo v7_cp_reginfo[] = {
1896     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
1897     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
1898       .access = PL1_W, .type = ARM_CP_NOP },
1899     /* Performance monitors are implementation defined in v7,
1900      * but with an ARM recommended set of registers, which we
1901      * follow.
1902      *
1903      * Performance registers fall into three categories:
1904      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
1905      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
1906      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
1907      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
1908      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
1909      */
1910     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
1911       .access = PL0_RW, .type = ARM_CP_ALIAS,
1912       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1913       .writefn = pmcntenset_write,
1914       .accessfn = pmreg_access,
1915       .raw_writefn = raw_write },
1916     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
1917       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
1918       .access = PL0_RW, .accessfn = pmreg_access,
1919       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
1920       .writefn = pmcntenset_write, .raw_writefn = raw_write },
1921     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
1922       .access = PL0_RW,
1923       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
1924       .accessfn = pmreg_access,
1925       .writefn = pmcntenclr_write,
1926       .type = ARM_CP_ALIAS },
1927     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
1928       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
1929       .access = PL0_RW, .accessfn = pmreg_access,
1930       .type = ARM_CP_ALIAS,
1931       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
1932       .writefn = pmcntenclr_write },
1933     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
1934       .access = PL0_RW, .type = ARM_CP_IO,
1935       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
1936       .accessfn = pmreg_access,
1937       .writefn = pmovsr_write,
1938       .raw_writefn = raw_write },
1939     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
1940       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
1941       .access = PL0_RW, .accessfn = pmreg_access,
1942       .type = ARM_CP_ALIAS | ARM_CP_IO,
1943       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
1944       .writefn = pmovsr_write,
1945       .raw_writefn = raw_write },
1946     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
1947       .access = PL0_W, .accessfn = pmreg_access_swinc,
1948       .type = ARM_CP_NO_RAW | ARM_CP_IO,
1949       .writefn = pmswinc_write },
1950     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
1951       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
1952       .access = PL0_W, .accessfn = pmreg_access_swinc,
1953       .type = ARM_CP_NO_RAW | ARM_CP_IO,
1954       .writefn = pmswinc_write },
1955     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
1956       .access = PL0_RW, .type = ARM_CP_ALIAS,
1957       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
1958       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
1959       .raw_writefn = raw_write},
1960     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
1961       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
1962       .access = PL0_RW, .accessfn = pmreg_access_selr,
1963       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
1964       .writefn = pmselr_write, .raw_writefn = raw_write, },
1965     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
1966       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
1967       .readfn = pmccntr_read, .writefn = pmccntr_write32,
1968       .accessfn = pmreg_access_ccntr },
1969     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
1970       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
1971       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
1972       .type = ARM_CP_IO,
1973       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
1974       .readfn = pmccntr_read, .writefn = pmccntr_write,
1975       .raw_readfn = raw_read, .raw_writefn = raw_write, },
1976     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
1977       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
1978       .access = PL0_RW, .accessfn = pmreg_access,
1979       .type = ARM_CP_ALIAS | ARM_CP_IO,
1980       .resetvalue = 0, },
1981     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
1982       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
1983       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
1984       .access = PL0_RW, .accessfn = pmreg_access,
1985       .type = ARM_CP_IO,
1986       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
1987       .resetvalue = 0, },
1988     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
1989       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1990       .accessfn = pmreg_access,
1991       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1992     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
1993       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
1994       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1995       .accessfn = pmreg_access,
1996       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
1997     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
1998       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
1999       .accessfn = pmreg_access_xevcntr,
2000       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2001     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2002       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2003       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2004       .accessfn = pmreg_access_xevcntr,
2005       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2006     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2007       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2008       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2009       .resetvalue = 0,
2010       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2011     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2012       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2013       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2014       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2015       .resetvalue = 0,
2016       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2017     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2018       .access = PL1_RW, .accessfn = access_tpm,
2019       .type = ARM_CP_ALIAS | ARM_CP_IO,
2020       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2021       .resetvalue = 0,
2022       .writefn = pmintenset_write, .raw_writefn = raw_write },
2023     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2024       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2025       .access = PL1_RW, .accessfn = access_tpm,
2026       .type = ARM_CP_IO,
2027       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2028       .writefn = pmintenset_write, .raw_writefn = raw_write,
2029       .resetvalue = 0x0 },
2030     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2031       .access = PL1_RW, .accessfn = access_tpm,
2032       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2033       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2034       .writefn = pmintenclr_write, },
2035     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2036       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2037       .access = PL1_RW, .accessfn = access_tpm,
2038       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2039       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2040       .writefn = pmintenclr_write },
2041     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2042       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2043       .access = PL1_R,
2044       .accessfn = access_aa64_tid2,
2045       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2046     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2047       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2048       .access = PL1_RW,
2049       .accessfn = access_aa64_tid2,
2050       .writefn = csselr_write, .resetvalue = 0,
2051       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2052                              offsetof(CPUARMState, cp15.csselr_ns) } },
2053     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2054      * just RAZ for all cores:
2055      */
2056     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2057       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2058       .access = PL1_R, .type = ARM_CP_CONST,
2059       .accessfn = access_aa64_tid1,
2060       .resetvalue = 0 },
2061     /* Auxiliary fault status registers: these also are IMPDEF, and we
2062      * choose to RAZ/WI for all cores.
2063      */
2064     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2065       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2066       .access = PL1_RW, .accessfn = access_tvm_trvm,
2067       .type = ARM_CP_CONST, .resetvalue = 0 },
2068     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2069       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2070       .access = PL1_RW, .accessfn = access_tvm_trvm,
2071       .type = ARM_CP_CONST, .resetvalue = 0 },
2072     /* MAIR can just read-as-written because we don't implement caches
2073      * and so don't need to care about memory attributes.
2074      */
2075     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2076       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2077       .access = PL1_RW, .accessfn = access_tvm_trvm,
2078       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2079       .resetvalue = 0 },
2080     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2081       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2082       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2083       .resetvalue = 0 },
2084     /* For non-long-descriptor page tables these are PRRR and NMRR;
2085      * regardless they still act as reads-as-written for QEMU.
2086      */
2087      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2088       * allows them to assign the correct fieldoffset based on the endianness
2089       * handled in the field definitions.
2090       */
2091     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2092       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2093       .access = PL1_RW, .accessfn = access_tvm_trvm,
2094       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2095                              offsetof(CPUARMState, cp15.mair0_ns) },
2096       .resetfn = arm_cp_reset_ignore },
2097     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2098       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2099       .access = PL1_RW, .accessfn = access_tvm_trvm,
2100       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2101                              offsetof(CPUARMState, cp15.mair1_ns) },
2102       .resetfn = arm_cp_reset_ignore },
2103     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2104       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2105       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2106     /* 32 bit ITLB invalidates */
2107     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2108       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2109       .writefn = tlbiall_write },
2110     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2111       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2112       .writefn = tlbimva_write },
2113     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2114       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2115       .writefn = tlbiasid_write },
2116     /* 32 bit DTLB invalidates */
2117     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2118       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2119       .writefn = tlbiall_write },
2120     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2121       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2122       .writefn = tlbimva_write },
2123     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2124       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2125       .writefn = tlbiasid_write },
2126     /* 32 bit TLB invalidates */
2127     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2128       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2129       .writefn = tlbiall_write },
2130     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2131       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2132       .writefn = tlbimva_write },
2133     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2134       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2135       .writefn = tlbiasid_write },
2136     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2137       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2138       .writefn = tlbimvaa_write },
2139 };
2140 
2141 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2142     /* 32 bit TLB invalidates, Inner Shareable */
2143     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2144       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2145       .writefn = tlbiall_is_write },
2146     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2147       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2148       .writefn = tlbimva_is_write },
2149     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2150       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2151       .writefn = tlbiasid_is_write },
2152     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2153       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2154       .writefn = tlbimvaa_is_write },
2155 };
2156 
2157 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2158     /* PMOVSSET is not implemented in v7 before v7ve */
2159     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2160       .access = PL0_RW, .accessfn = pmreg_access,
2161       .type = ARM_CP_ALIAS | ARM_CP_IO,
2162       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2163       .writefn = pmovsset_write,
2164       .raw_writefn = raw_write },
2165     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2166       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2167       .access = PL0_RW, .accessfn = pmreg_access,
2168       .type = ARM_CP_ALIAS | ARM_CP_IO,
2169       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2170       .writefn = pmovsset_write,
2171       .raw_writefn = raw_write },
2172 };
2173 
2174 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2175                         uint64_t value)
2176 {
2177     value &= 1;
2178     env->teecr = value;
2179 }
2180 
2181 static CPAccessResult teecr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2182                                    bool isread)
2183 {
2184     /*
2185      * HSTR.TTEE only exists in v7A, not v8A, but v8A doesn't have T2EE
2186      * at all, so we don't need to check whether we're v8A.
2187      */
2188     if (arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
2189         (env->cp15.hstr_el2 & HSTR_TTEE)) {
2190         return CP_ACCESS_TRAP_EL2;
2191     }
2192     return CP_ACCESS_OK;
2193 }
2194 
2195 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2196                                     bool isread)
2197 {
2198     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2199         return CP_ACCESS_TRAP;
2200     }
2201     return teecr_access(env, ri, isread);
2202 }
2203 
2204 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2205     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2206       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2207       .resetvalue = 0,
2208       .writefn = teecr_write, .accessfn = teecr_access },
2209     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2210       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2211       .accessfn = teehbr_access, .resetvalue = 0 },
2212 };
2213 
2214 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2215     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2216       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2217       .access = PL0_RW,
2218       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2219     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2220       .access = PL0_RW,
2221       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2222                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2223       .resetfn = arm_cp_reset_ignore },
2224     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2225       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2226       .access = PL0_R|PL1_W,
2227       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2228       .resetvalue = 0},
2229     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2230       .access = PL0_R|PL1_W,
2231       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2232                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2233       .resetfn = arm_cp_reset_ignore },
2234     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2235       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2236       .access = PL1_RW,
2237       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2238     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2239       .access = PL1_RW,
2240       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2241                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2242       .resetvalue = 0 },
2243 };
2244 
2245 #ifndef CONFIG_USER_ONLY
2246 
2247 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2248                                        bool isread)
2249 {
2250     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2251      * Writable only at the highest implemented exception level.
2252      */
2253     int el = arm_current_el(env);
2254     uint64_t hcr;
2255     uint32_t cntkctl;
2256 
2257     switch (el) {
2258     case 0:
2259         hcr = arm_hcr_el2_eff(env);
2260         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2261             cntkctl = env->cp15.cnthctl_el2;
2262         } else {
2263             cntkctl = env->cp15.c14_cntkctl;
2264         }
2265         if (!extract32(cntkctl, 0, 2)) {
2266             return CP_ACCESS_TRAP;
2267         }
2268         break;
2269     case 1:
2270         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2271             arm_is_secure_below_el3(env)) {
2272             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2273             return CP_ACCESS_TRAP_UNCATEGORIZED;
2274         }
2275         break;
2276     case 2:
2277     case 3:
2278         break;
2279     }
2280 
2281     if (!isread && el < arm_highest_el(env)) {
2282         return CP_ACCESS_TRAP_UNCATEGORIZED;
2283     }
2284 
2285     return CP_ACCESS_OK;
2286 }
2287 
2288 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2289                                         bool isread)
2290 {
2291     unsigned int cur_el = arm_current_el(env);
2292     bool has_el2 = arm_is_el2_enabled(env);
2293     uint64_t hcr = arm_hcr_el2_eff(env);
2294 
2295     switch (cur_el) {
2296     case 0:
2297         /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2298         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2299             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2300                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2301         }
2302 
2303         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2304         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2305             return CP_ACCESS_TRAP;
2306         }
2307 
2308         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2309         if (hcr & HCR_E2H) {
2310             if (timeridx == GTIMER_PHYS &&
2311                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2312                 return CP_ACCESS_TRAP_EL2;
2313             }
2314         } else {
2315             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2316             if (has_el2 && timeridx == GTIMER_PHYS &&
2317                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2318                 return CP_ACCESS_TRAP_EL2;
2319             }
2320         }
2321         break;
2322 
2323     case 1:
2324         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2325         if (has_el2 && timeridx == GTIMER_PHYS &&
2326             (hcr & HCR_E2H
2327              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2328              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2329             return CP_ACCESS_TRAP_EL2;
2330         }
2331         break;
2332     }
2333     return CP_ACCESS_OK;
2334 }
2335 
2336 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2337                                       bool isread)
2338 {
2339     unsigned int cur_el = arm_current_el(env);
2340     bool has_el2 = arm_is_el2_enabled(env);
2341     uint64_t hcr = arm_hcr_el2_eff(env);
2342 
2343     switch (cur_el) {
2344     case 0:
2345         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2346             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2347             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2348                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2349         }
2350 
2351         /*
2352          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2353          * EL0 if EL0[PV]TEN is zero.
2354          */
2355         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2356             return CP_ACCESS_TRAP;
2357         }
2358         /* fall through */
2359 
2360     case 1:
2361         if (has_el2 && timeridx == GTIMER_PHYS) {
2362             if (hcr & HCR_E2H) {
2363                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2364                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2365                     return CP_ACCESS_TRAP_EL2;
2366                 }
2367             } else {
2368                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2369                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2370                     return CP_ACCESS_TRAP_EL2;
2371                 }
2372             }
2373         }
2374         break;
2375     }
2376     return CP_ACCESS_OK;
2377 }
2378 
2379 static CPAccessResult gt_pct_access(CPUARMState *env,
2380                                     const ARMCPRegInfo *ri,
2381                                     bool isread)
2382 {
2383     return gt_counter_access(env, GTIMER_PHYS, isread);
2384 }
2385 
2386 static CPAccessResult gt_vct_access(CPUARMState *env,
2387                                     const ARMCPRegInfo *ri,
2388                                     bool isread)
2389 {
2390     return gt_counter_access(env, GTIMER_VIRT, isread);
2391 }
2392 
2393 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2394                                        bool isread)
2395 {
2396     return gt_timer_access(env, GTIMER_PHYS, isread);
2397 }
2398 
2399 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2400                                        bool isread)
2401 {
2402     return gt_timer_access(env, GTIMER_VIRT, isread);
2403 }
2404 
2405 static CPAccessResult gt_stimer_access(CPUARMState *env,
2406                                        const ARMCPRegInfo *ri,
2407                                        bool isread)
2408 {
2409     /* The AArch64 register view of the secure physical timer is
2410      * always accessible from EL3, and configurably accessible from
2411      * Secure EL1.
2412      */
2413     switch (arm_current_el(env)) {
2414     case 1:
2415         if (!arm_is_secure(env)) {
2416             return CP_ACCESS_TRAP;
2417         }
2418         if (!(env->cp15.scr_el3 & SCR_ST)) {
2419             return CP_ACCESS_TRAP_EL3;
2420         }
2421         return CP_ACCESS_OK;
2422     case 0:
2423     case 2:
2424         return CP_ACCESS_TRAP;
2425     case 3:
2426         return CP_ACCESS_OK;
2427     default:
2428         g_assert_not_reached();
2429     }
2430 }
2431 
2432 static uint64_t gt_get_countervalue(CPUARMState *env)
2433 {
2434     ARMCPU *cpu = env_archcpu(env);
2435 
2436     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2437 }
2438 
2439 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2440 {
2441     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2442 
2443     if (gt->ctl & 1) {
2444         /* Timer enabled: calculate and set current ISTATUS, irq, and
2445          * reset timer to when ISTATUS next has to change
2446          */
2447         uint64_t offset = timeridx == GTIMER_VIRT ?
2448                                       cpu->env.cp15.cntvoff_el2 : 0;
2449         uint64_t count = gt_get_countervalue(&cpu->env);
2450         /* Note that this must be unsigned 64 bit arithmetic: */
2451         int istatus = count - offset >= gt->cval;
2452         uint64_t nexttick;
2453         int irqstate;
2454 
2455         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2456 
2457         irqstate = (istatus && !(gt->ctl & 2));
2458         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2459 
2460         if (istatus) {
2461             /* Next transition is when count rolls back over to zero */
2462             nexttick = UINT64_MAX;
2463         } else {
2464             /* Next transition is when we hit cval */
2465             nexttick = gt->cval + offset;
2466         }
2467         /* Note that the desired next expiry time might be beyond the
2468          * signed-64-bit range of a QEMUTimer -- in this case we just
2469          * set the timer for as far in the future as possible. When the
2470          * timer expires we will reset the timer for any remaining period.
2471          */
2472         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2473             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2474         } else {
2475             timer_mod(cpu->gt_timer[timeridx], nexttick);
2476         }
2477         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2478     } else {
2479         /* Timer disabled: ISTATUS and timer output always clear */
2480         gt->ctl &= ~4;
2481         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2482         timer_del(cpu->gt_timer[timeridx]);
2483         trace_arm_gt_recalc_disabled(timeridx);
2484     }
2485 }
2486 
2487 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2488                            int timeridx)
2489 {
2490     ARMCPU *cpu = env_archcpu(env);
2491 
2492     timer_del(cpu->gt_timer[timeridx]);
2493 }
2494 
2495 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2496 {
2497     return gt_get_countervalue(env);
2498 }
2499 
2500 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2501 {
2502     uint64_t hcr;
2503 
2504     switch (arm_current_el(env)) {
2505     case 2:
2506         hcr = arm_hcr_el2_eff(env);
2507         if (hcr & HCR_E2H) {
2508             return 0;
2509         }
2510         break;
2511     case 0:
2512         hcr = arm_hcr_el2_eff(env);
2513         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2514             return 0;
2515         }
2516         break;
2517     }
2518 
2519     return env->cp15.cntvoff_el2;
2520 }
2521 
2522 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2523 {
2524     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2525 }
2526 
2527 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2528                           int timeridx,
2529                           uint64_t value)
2530 {
2531     trace_arm_gt_cval_write(timeridx, value);
2532     env->cp15.c14_timer[timeridx].cval = value;
2533     gt_recalc_timer(env_archcpu(env), timeridx);
2534 }
2535 
2536 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2537                              int timeridx)
2538 {
2539     uint64_t offset = 0;
2540 
2541     switch (timeridx) {
2542     case GTIMER_VIRT:
2543     case GTIMER_HYPVIRT:
2544         offset = gt_virt_cnt_offset(env);
2545         break;
2546     }
2547 
2548     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2549                       (gt_get_countervalue(env) - offset));
2550 }
2551 
2552 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2553                           int timeridx,
2554                           uint64_t value)
2555 {
2556     uint64_t offset = 0;
2557 
2558     switch (timeridx) {
2559     case GTIMER_VIRT:
2560     case GTIMER_HYPVIRT:
2561         offset = gt_virt_cnt_offset(env);
2562         break;
2563     }
2564 
2565     trace_arm_gt_tval_write(timeridx, value);
2566     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2567                                          sextract64(value, 0, 32);
2568     gt_recalc_timer(env_archcpu(env), timeridx);
2569 }
2570 
2571 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2572                          int timeridx,
2573                          uint64_t value)
2574 {
2575     ARMCPU *cpu = env_archcpu(env);
2576     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2577 
2578     trace_arm_gt_ctl_write(timeridx, value);
2579     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2580     if ((oldval ^ value) & 1) {
2581         /* Enable toggled */
2582         gt_recalc_timer(cpu, timeridx);
2583     } else if ((oldval ^ value) & 2) {
2584         /* IMASK toggled: don't need to recalculate,
2585          * just set the interrupt line based on ISTATUS
2586          */
2587         int irqstate = (oldval & 4) && !(value & 2);
2588 
2589         trace_arm_gt_imask_toggle(timeridx, irqstate);
2590         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2591     }
2592 }
2593 
2594 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2595 {
2596     gt_timer_reset(env, ri, GTIMER_PHYS);
2597 }
2598 
2599 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2600                                uint64_t value)
2601 {
2602     gt_cval_write(env, ri, GTIMER_PHYS, value);
2603 }
2604 
2605 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2606 {
2607     return gt_tval_read(env, ri, GTIMER_PHYS);
2608 }
2609 
2610 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2611                                uint64_t value)
2612 {
2613     gt_tval_write(env, ri, GTIMER_PHYS, value);
2614 }
2615 
2616 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2617                               uint64_t value)
2618 {
2619     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2620 }
2621 
2622 static int gt_phys_redir_timeridx(CPUARMState *env)
2623 {
2624     switch (arm_mmu_idx(env)) {
2625     case ARMMMUIdx_E20_0:
2626     case ARMMMUIdx_E20_2:
2627     case ARMMMUIdx_E20_2_PAN:
2628     case ARMMMUIdx_SE20_0:
2629     case ARMMMUIdx_SE20_2:
2630     case ARMMMUIdx_SE20_2_PAN:
2631         return GTIMER_HYP;
2632     default:
2633         return GTIMER_PHYS;
2634     }
2635 }
2636 
2637 static int gt_virt_redir_timeridx(CPUARMState *env)
2638 {
2639     switch (arm_mmu_idx(env)) {
2640     case ARMMMUIdx_E20_0:
2641     case ARMMMUIdx_E20_2:
2642     case ARMMMUIdx_E20_2_PAN:
2643     case ARMMMUIdx_SE20_0:
2644     case ARMMMUIdx_SE20_2:
2645     case ARMMMUIdx_SE20_2_PAN:
2646         return GTIMER_HYPVIRT;
2647     default:
2648         return GTIMER_VIRT;
2649     }
2650 }
2651 
2652 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2653                                         const ARMCPRegInfo *ri)
2654 {
2655     int timeridx = gt_phys_redir_timeridx(env);
2656     return env->cp15.c14_timer[timeridx].cval;
2657 }
2658 
2659 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2660                                      uint64_t value)
2661 {
2662     int timeridx = gt_phys_redir_timeridx(env);
2663     gt_cval_write(env, ri, timeridx, value);
2664 }
2665 
2666 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2667                                         const ARMCPRegInfo *ri)
2668 {
2669     int timeridx = gt_phys_redir_timeridx(env);
2670     return gt_tval_read(env, ri, timeridx);
2671 }
2672 
2673 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2674                                      uint64_t value)
2675 {
2676     int timeridx = gt_phys_redir_timeridx(env);
2677     gt_tval_write(env, ri, timeridx, value);
2678 }
2679 
2680 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2681                                        const ARMCPRegInfo *ri)
2682 {
2683     int timeridx = gt_phys_redir_timeridx(env);
2684     return env->cp15.c14_timer[timeridx].ctl;
2685 }
2686 
2687 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2688                                     uint64_t value)
2689 {
2690     int timeridx = gt_phys_redir_timeridx(env);
2691     gt_ctl_write(env, ri, timeridx, value);
2692 }
2693 
2694 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2695 {
2696     gt_timer_reset(env, ri, GTIMER_VIRT);
2697 }
2698 
2699 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2700                                uint64_t value)
2701 {
2702     gt_cval_write(env, ri, GTIMER_VIRT, value);
2703 }
2704 
2705 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2706 {
2707     return gt_tval_read(env, ri, GTIMER_VIRT);
2708 }
2709 
2710 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2711                                uint64_t value)
2712 {
2713     gt_tval_write(env, ri, GTIMER_VIRT, value);
2714 }
2715 
2716 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2717                               uint64_t value)
2718 {
2719     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2720 }
2721 
2722 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2723                               uint64_t value)
2724 {
2725     ARMCPU *cpu = env_archcpu(env);
2726 
2727     trace_arm_gt_cntvoff_write(value);
2728     raw_write(env, ri, value);
2729     gt_recalc_timer(cpu, GTIMER_VIRT);
2730 }
2731 
2732 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
2733                                         const ARMCPRegInfo *ri)
2734 {
2735     int timeridx = gt_virt_redir_timeridx(env);
2736     return env->cp15.c14_timer[timeridx].cval;
2737 }
2738 
2739 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2740                                      uint64_t value)
2741 {
2742     int timeridx = gt_virt_redir_timeridx(env);
2743     gt_cval_write(env, ri, timeridx, value);
2744 }
2745 
2746 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
2747                                         const ARMCPRegInfo *ri)
2748 {
2749     int timeridx = gt_virt_redir_timeridx(env);
2750     return gt_tval_read(env, ri, timeridx);
2751 }
2752 
2753 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2754                                      uint64_t value)
2755 {
2756     int timeridx = gt_virt_redir_timeridx(env);
2757     gt_tval_write(env, ri, timeridx, value);
2758 }
2759 
2760 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
2761                                        const ARMCPRegInfo *ri)
2762 {
2763     int timeridx = gt_virt_redir_timeridx(env);
2764     return env->cp15.c14_timer[timeridx].ctl;
2765 }
2766 
2767 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2768                                     uint64_t value)
2769 {
2770     int timeridx = gt_virt_redir_timeridx(env);
2771     gt_ctl_write(env, ri, timeridx, value);
2772 }
2773 
2774 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2775 {
2776     gt_timer_reset(env, ri, GTIMER_HYP);
2777 }
2778 
2779 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2780                               uint64_t value)
2781 {
2782     gt_cval_write(env, ri, GTIMER_HYP, value);
2783 }
2784 
2785 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2786 {
2787     return gt_tval_read(env, ri, GTIMER_HYP);
2788 }
2789 
2790 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2791                               uint64_t value)
2792 {
2793     gt_tval_write(env, ri, GTIMER_HYP, value);
2794 }
2795 
2796 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2797                               uint64_t value)
2798 {
2799     gt_ctl_write(env, ri, GTIMER_HYP, value);
2800 }
2801 
2802 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2803 {
2804     gt_timer_reset(env, ri, GTIMER_SEC);
2805 }
2806 
2807 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2808                               uint64_t value)
2809 {
2810     gt_cval_write(env, ri, GTIMER_SEC, value);
2811 }
2812 
2813 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2814 {
2815     return gt_tval_read(env, ri, GTIMER_SEC);
2816 }
2817 
2818 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2819                               uint64_t value)
2820 {
2821     gt_tval_write(env, ri, GTIMER_SEC, value);
2822 }
2823 
2824 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2825                               uint64_t value)
2826 {
2827     gt_ctl_write(env, ri, GTIMER_SEC, value);
2828 }
2829 
2830 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2831 {
2832     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
2833 }
2834 
2835 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2836                              uint64_t value)
2837 {
2838     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
2839 }
2840 
2841 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2842 {
2843     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
2844 }
2845 
2846 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2847                              uint64_t value)
2848 {
2849     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
2850 }
2851 
2852 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2853                             uint64_t value)
2854 {
2855     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
2856 }
2857 
2858 void arm_gt_ptimer_cb(void *opaque)
2859 {
2860     ARMCPU *cpu = opaque;
2861 
2862     gt_recalc_timer(cpu, GTIMER_PHYS);
2863 }
2864 
2865 void arm_gt_vtimer_cb(void *opaque)
2866 {
2867     ARMCPU *cpu = opaque;
2868 
2869     gt_recalc_timer(cpu, GTIMER_VIRT);
2870 }
2871 
2872 void arm_gt_htimer_cb(void *opaque)
2873 {
2874     ARMCPU *cpu = opaque;
2875 
2876     gt_recalc_timer(cpu, GTIMER_HYP);
2877 }
2878 
2879 void arm_gt_stimer_cb(void *opaque)
2880 {
2881     ARMCPU *cpu = opaque;
2882 
2883     gt_recalc_timer(cpu, GTIMER_SEC);
2884 }
2885 
2886 void arm_gt_hvtimer_cb(void *opaque)
2887 {
2888     ARMCPU *cpu = opaque;
2889 
2890     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
2891 }
2892 
2893 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
2894 {
2895     ARMCPU *cpu = env_archcpu(env);
2896 
2897     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
2898 }
2899 
2900 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
2901     /* Note that CNTFRQ is purely reads-as-written for the benefit
2902      * of software; writing it doesn't actually change the timer frequency.
2903      * Our reset value matches the fixed frequency we implement the timer at.
2904      */
2905     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
2906       .type = ARM_CP_ALIAS,
2907       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2908       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
2909     },
2910     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
2911       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
2912       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
2913       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
2914       .resetfn = arm_gt_cntfrq_reset,
2915     },
2916     /* overall control: mostly access permissions */
2917     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
2918       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
2919       .access = PL1_RW,
2920       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
2921       .resetvalue = 0,
2922     },
2923     /* per-timer control */
2924     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2925       .secure = ARM_CP_SECSTATE_NS,
2926       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2927       .accessfn = gt_ptimer_access,
2928       .fieldoffset = offsetoflow32(CPUARMState,
2929                                    cp15.c14_timer[GTIMER_PHYS].ctl),
2930       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
2931       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
2932     },
2933     { .name = "CNTP_CTL_S",
2934       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
2935       .secure = ARM_CP_SECSTATE_S,
2936       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2937       .accessfn = gt_ptimer_access,
2938       .fieldoffset = offsetoflow32(CPUARMState,
2939                                    cp15.c14_timer[GTIMER_SEC].ctl),
2940       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
2941     },
2942     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
2943       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
2944       .type = ARM_CP_IO, .access = PL0_RW,
2945       .accessfn = gt_ptimer_access,
2946       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
2947       .resetvalue = 0,
2948       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
2949       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
2950     },
2951     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
2952       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
2953       .accessfn = gt_vtimer_access,
2954       .fieldoffset = offsetoflow32(CPUARMState,
2955                                    cp15.c14_timer[GTIMER_VIRT].ctl),
2956       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
2957       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
2958     },
2959     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
2960       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
2961       .type = ARM_CP_IO, .access = PL0_RW,
2962       .accessfn = gt_vtimer_access,
2963       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
2964       .resetvalue = 0,
2965       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
2966       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
2967     },
2968     /* TimerValue views: a 32 bit downcounting view of the underlying state */
2969     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2970       .secure = ARM_CP_SECSTATE_NS,
2971       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2972       .accessfn = gt_ptimer_access,
2973       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
2974     },
2975     { .name = "CNTP_TVAL_S",
2976       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
2977       .secure = ARM_CP_SECSTATE_S,
2978       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2979       .accessfn = gt_ptimer_access,
2980       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
2981     },
2982     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2983       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
2984       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2985       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
2986       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
2987     },
2988     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
2989       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2990       .accessfn = gt_vtimer_access,
2991       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
2992     },
2993     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
2994       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
2995       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
2996       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
2997       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
2998     },
2999     /* The counter itself */
3000     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
3001       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3002       .accessfn = gt_pct_access,
3003       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
3004     },
3005     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
3006       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
3007       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3008       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
3009     },
3010     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3011       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3012       .accessfn = gt_vct_access,
3013       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3014     },
3015     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3016       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3017       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3018       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3019     },
3020     /* Comparison value, indicating when the timer goes off */
3021     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3022       .secure = ARM_CP_SECSTATE_NS,
3023       .access = PL0_RW,
3024       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3025       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3026       .accessfn = gt_ptimer_access,
3027       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3028       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3029     },
3030     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3031       .secure = ARM_CP_SECSTATE_S,
3032       .access = PL0_RW,
3033       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3034       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3035       .accessfn = gt_ptimer_access,
3036       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3037     },
3038     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3039       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3040       .access = PL0_RW,
3041       .type = ARM_CP_IO,
3042       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3043       .resetvalue = 0, .accessfn = gt_ptimer_access,
3044       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3045       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3046     },
3047     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3048       .access = PL0_RW,
3049       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3050       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3051       .accessfn = gt_vtimer_access,
3052       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3053       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3054     },
3055     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3056       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3057       .access = PL0_RW,
3058       .type = ARM_CP_IO,
3059       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3060       .resetvalue = 0, .accessfn = gt_vtimer_access,
3061       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3062       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3063     },
3064     /* Secure timer -- this is actually restricted to only EL3
3065      * and configurably Secure-EL1 via the accessfn.
3066      */
3067     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3068       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3069       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3070       .accessfn = gt_stimer_access,
3071       .readfn = gt_sec_tval_read,
3072       .writefn = gt_sec_tval_write,
3073       .resetfn = gt_sec_timer_reset,
3074     },
3075     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3076       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3077       .type = ARM_CP_IO, .access = PL1_RW,
3078       .accessfn = gt_stimer_access,
3079       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3080       .resetvalue = 0,
3081       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3082     },
3083     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3084       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3085       .type = ARM_CP_IO, .access = PL1_RW,
3086       .accessfn = gt_stimer_access,
3087       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3088       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3089     },
3090 };
3091 
3092 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3093                                  bool isread)
3094 {
3095     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3096         return CP_ACCESS_TRAP;
3097     }
3098     return CP_ACCESS_OK;
3099 }
3100 
3101 #else
3102 
3103 /* In user-mode most of the generic timer registers are inaccessible
3104  * however modern kernels (4.12+) allow access to cntvct_el0
3105  */
3106 
3107 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3108 {
3109     ARMCPU *cpu = env_archcpu(env);
3110 
3111     /* Currently we have no support for QEMUTimer in linux-user so we
3112      * can't call gt_get_countervalue(env), instead we directly
3113      * call the lower level functions.
3114      */
3115     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3116 }
3117 
3118 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3119     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3120       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3121       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3122       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3123       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3124     },
3125     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3126       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3127       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3128       .readfn = gt_virt_cnt_read,
3129     },
3130 };
3131 
3132 #endif
3133 
3134 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3135 {
3136     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3137         raw_write(env, ri, value);
3138     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3139         raw_write(env, ri, value & 0xfffff6ff);
3140     } else {
3141         raw_write(env, ri, value & 0xfffff1ff);
3142     }
3143 }
3144 
3145 #ifndef CONFIG_USER_ONLY
3146 /* get_phys_addr() isn't present for user-mode-only targets */
3147 
3148 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3149                                  bool isread)
3150 {
3151     if (ri->opc2 & 4) {
3152         /* The ATS12NSO* operations must trap to EL3 or EL2 if executed in
3153          * Secure EL1 (which can only happen if EL3 is AArch64).
3154          * They are simply UNDEF if executed from NS EL1.
3155          * They function normally from EL2 or EL3.
3156          */
3157         if (arm_current_el(env) == 1) {
3158             if (arm_is_secure_below_el3(env)) {
3159                 if (env->cp15.scr_el3 & SCR_EEL2) {
3160                     return CP_ACCESS_TRAP_UNCATEGORIZED_EL2;
3161                 }
3162                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3163             }
3164             return CP_ACCESS_TRAP_UNCATEGORIZED;
3165         }
3166     }
3167     return CP_ACCESS_OK;
3168 }
3169 
3170 #ifdef CONFIG_TCG
3171 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3172                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3173 {
3174     hwaddr phys_addr;
3175     target_ulong page_size;
3176     int prot;
3177     bool ret;
3178     uint64_t par64;
3179     bool format64 = false;
3180     MemTxAttrs attrs = {};
3181     ARMMMUFaultInfo fi = {};
3182     ARMCacheAttrs cacheattrs = {};
3183 
3184     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3185                         &prot, &page_size, &fi, &cacheattrs);
3186 
3187     if (ret) {
3188         /*
3189          * Some kinds of translation fault must cause exceptions rather
3190          * than being reported in the PAR.
3191          */
3192         int current_el = arm_current_el(env);
3193         int target_el;
3194         uint32_t syn, fsr, fsc;
3195         bool take_exc = false;
3196 
3197         if (fi.s1ptw && current_el == 1
3198             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3199             /*
3200              * Synchronous stage 2 fault on an access made as part of the
3201              * translation table walk for AT S1E0* or AT S1E1* insn
3202              * executed from NS EL1. If this is a synchronous external abort
3203              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3204              * to EL3. Otherwise the fault is taken as an exception to EL2,
3205              * and HPFAR_EL2 holds the faulting IPA.
3206              */
3207             if (fi.type == ARMFault_SyncExternalOnWalk &&
3208                 (env->cp15.scr_el3 & SCR_EA)) {
3209                 target_el = 3;
3210             } else {
3211                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3212                 if (arm_is_secure_below_el3(env) && fi.s1ns) {
3213                     env->cp15.hpfar_el2 |= HPFAR_NS;
3214                 }
3215                 target_el = 2;
3216             }
3217             take_exc = true;
3218         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3219             /*
3220              * Synchronous external aborts during a translation table walk
3221              * are taken as Data Abort exceptions.
3222              */
3223             if (fi.stage2) {
3224                 if (current_el == 3) {
3225                     target_el = 3;
3226                 } else {
3227                     target_el = 2;
3228                 }
3229             } else {
3230                 target_el = exception_target_el(env);
3231             }
3232             take_exc = true;
3233         }
3234 
3235         if (take_exc) {
3236             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3237             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3238                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3239                 fsr = arm_fi_to_lfsc(&fi);
3240                 fsc = extract32(fsr, 0, 6);
3241             } else {
3242                 fsr = arm_fi_to_sfsc(&fi);
3243                 fsc = 0x3f;
3244             }
3245             /*
3246              * Report exception with ESR indicating a fault due to a
3247              * translation table walk for a cache maintenance instruction.
3248              */
3249             syn = syn_data_abort_no_iss(current_el == target_el, 0,
3250                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3251             env->exception.vaddress = value;
3252             env->exception.fsr = fsr;
3253             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3254         }
3255     }
3256 
3257     if (is_a64(env)) {
3258         format64 = true;
3259     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3260         /*
3261          * ATS1Cxx:
3262          * * TTBCR.EAE determines whether the result is returned using the
3263          *   32-bit or the 64-bit PAR format
3264          * * Instructions executed in Hyp mode always use the 64bit format
3265          *
3266          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3267          * * The Non-secure TTBCR.EAE bit is set to 1
3268          * * The implementation includes EL2, and the value of HCR.VM is 1
3269          *
3270          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3271          *
3272          * ATS1Hx always uses the 64bit format.
3273          */
3274         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3275 
3276         if (arm_feature(env, ARM_FEATURE_EL2)) {
3277             if (mmu_idx == ARMMMUIdx_E10_0 ||
3278                 mmu_idx == ARMMMUIdx_E10_1 ||
3279                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3280                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3281             } else {
3282                 format64 |= arm_current_el(env) == 2;
3283             }
3284         }
3285     }
3286 
3287     if (format64) {
3288         /* Create a 64-bit PAR */
3289         par64 = (1 << 11); /* LPAE bit always set */
3290         if (!ret) {
3291             par64 |= phys_addr & ~0xfffULL;
3292             if (!attrs.secure) {
3293                 par64 |= (1 << 9); /* NS */
3294             }
3295             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3296             par64 |= cacheattrs.shareability << 7; /* SH */
3297         } else {
3298             uint32_t fsr = arm_fi_to_lfsc(&fi);
3299 
3300             par64 |= 1; /* F */
3301             par64 |= (fsr & 0x3f) << 1; /* FS */
3302             if (fi.stage2) {
3303                 par64 |= (1 << 9); /* S */
3304             }
3305             if (fi.s1ptw) {
3306                 par64 |= (1 << 8); /* PTW */
3307             }
3308         }
3309     } else {
3310         /* fsr is a DFSR/IFSR value for the short descriptor
3311          * translation table format (with WnR always clear).
3312          * Convert it to a 32-bit PAR.
3313          */
3314         if (!ret) {
3315             /* We do not set any attribute bits in the PAR */
3316             if (page_size == (1 << 24)
3317                 && arm_feature(env, ARM_FEATURE_V7)) {
3318                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3319             } else {
3320                 par64 = phys_addr & 0xfffff000;
3321             }
3322             if (!attrs.secure) {
3323                 par64 |= (1 << 9); /* NS */
3324             }
3325         } else {
3326             uint32_t fsr = arm_fi_to_sfsc(&fi);
3327 
3328             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3329                     ((fsr & 0xf) << 1) | 1;
3330         }
3331     }
3332     return par64;
3333 }
3334 #endif /* CONFIG_TCG */
3335 
3336 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3337 {
3338 #ifdef CONFIG_TCG
3339     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3340     uint64_t par64;
3341     ARMMMUIdx mmu_idx;
3342     int el = arm_current_el(env);
3343     bool secure = arm_is_secure_below_el3(env);
3344 
3345     switch (ri->opc2 & 6) {
3346     case 0:
3347         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3348         switch (el) {
3349         case 3:
3350             mmu_idx = ARMMMUIdx_SE3;
3351             break;
3352         case 2:
3353             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3354             /* fall through */
3355         case 1:
3356             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3357                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3358                            : ARMMMUIdx_Stage1_E1_PAN);
3359             } else {
3360                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3361             }
3362             break;
3363         default:
3364             g_assert_not_reached();
3365         }
3366         break;
3367     case 2:
3368         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3369         switch (el) {
3370         case 3:
3371             mmu_idx = ARMMMUIdx_SE10_0;
3372             break;
3373         case 2:
3374             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3375             mmu_idx = ARMMMUIdx_Stage1_E0;
3376             break;
3377         case 1:
3378             mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3379             break;
3380         default:
3381             g_assert_not_reached();
3382         }
3383         break;
3384     case 4:
3385         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3386         mmu_idx = ARMMMUIdx_E10_1;
3387         break;
3388     case 6:
3389         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3390         mmu_idx = ARMMMUIdx_E10_0;
3391         break;
3392     default:
3393         g_assert_not_reached();
3394     }
3395 
3396     par64 = do_ats_write(env, value, access_type, mmu_idx);
3397 
3398     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3399 #else
3400     /* Handled by hardware accelerator. */
3401     g_assert_not_reached();
3402 #endif /* CONFIG_TCG */
3403 }
3404 
3405 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3406                         uint64_t value)
3407 {
3408 #ifdef CONFIG_TCG
3409     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3410     uint64_t par64;
3411 
3412     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3413 
3414     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3415 #else
3416     /* Handled by hardware accelerator. */
3417     g_assert_not_reached();
3418 #endif /* CONFIG_TCG */
3419 }
3420 
3421 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3422                                      bool isread)
3423 {
3424     if (arm_current_el(env) == 3 &&
3425         !(env->cp15.scr_el3 & (SCR_NS | SCR_EEL2))) {
3426         return CP_ACCESS_TRAP;
3427     }
3428     return CP_ACCESS_OK;
3429 }
3430 
3431 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3432                         uint64_t value)
3433 {
3434 #ifdef CONFIG_TCG
3435     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3436     ARMMMUIdx mmu_idx;
3437     int secure = arm_is_secure_below_el3(env);
3438 
3439     switch (ri->opc2 & 6) {
3440     case 0:
3441         switch (ri->opc1) {
3442         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3443             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3444                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3445                            : ARMMMUIdx_Stage1_E1_PAN);
3446             } else {
3447                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3448             }
3449             break;
3450         case 4: /* AT S1E2R, AT S1E2W */
3451             mmu_idx = secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2;
3452             break;
3453         case 6: /* AT S1E3R, AT S1E3W */
3454             mmu_idx = ARMMMUIdx_SE3;
3455             break;
3456         default:
3457             g_assert_not_reached();
3458         }
3459         break;
3460     case 2: /* AT S1E0R, AT S1E0W */
3461         mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3462         break;
3463     case 4: /* AT S12E1R, AT S12E1W */
3464         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3465         break;
3466     case 6: /* AT S12E0R, AT S12E0W */
3467         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3468         break;
3469     default:
3470         g_assert_not_reached();
3471     }
3472 
3473     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3474 #else
3475     /* Handled by hardware accelerator. */
3476     g_assert_not_reached();
3477 #endif /* CONFIG_TCG */
3478 }
3479 #endif
3480 
3481 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3482     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3483       .access = PL1_RW, .resetvalue = 0,
3484       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3485                              offsetoflow32(CPUARMState, cp15.par_ns) },
3486       .writefn = par_write },
3487 #ifndef CONFIG_USER_ONLY
3488     /* This underdecoding is safe because the reginfo is NO_RAW. */
3489     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3490       .access = PL1_W, .accessfn = ats_access,
3491       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3492 #endif
3493 };
3494 
3495 /* Return basic MPU access permission bits.  */
3496 static uint32_t simple_mpu_ap_bits(uint32_t val)
3497 {
3498     uint32_t ret;
3499     uint32_t mask;
3500     int i;
3501     ret = 0;
3502     mask = 3;
3503     for (i = 0; i < 16; i += 2) {
3504         ret |= (val >> i) & mask;
3505         mask <<= 2;
3506     }
3507     return ret;
3508 }
3509 
3510 /* Pad basic MPU access permission bits to extended format.  */
3511 static uint32_t extended_mpu_ap_bits(uint32_t val)
3512 {
3513     uint32_t ret;
3514     uint32_t mask;
3515     int i;
3516     ret = 0;
3517     mask = 3;
3518     for (i = 0; i < 16; i += 2) {
3519         ret |= (val & mask) << i;
3520         mask <<= 2;
3521     }
3522     return ret;
3523 }
3524 
3525 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3526                                  uint64_t value)
3527 {
3528     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3529 }
3530 
3531 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3532 {
3533     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3534 }
3535 
3536 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3537                                  uint64_t value)
3538 {
3539     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3540 }
3541 
3542 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3543 {
3544     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3545 }
3546 
3547 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3548 {
3549     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3550 
3551     if (!u32p) {
3552         return 0;
3553     }
3554 
3555     u32p += env->pmsav7.rnr[M_REG_NS];
3556     return *u32p;
3557 }
3558 
3559 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3560                          uint64_t value)
3561 {
3562     ARMCPU *cpu = env_archcpu(env);
3563     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3564 
3565     if (!u32p) {
3566         return;
3567     }
3568 
3569     u32p += env->pmsav7.rnr[M_REG_NS];
3570     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3571     *u32p = value;
3572 }
3573 
3574 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3575                               uint64_t value)
3576 {
3577     ARMCPU *cpu = env_archcpu(env);
3578     uint32_t nrgs = cpu->pmsav7_dregion;
3579 
3580     if (value >= nrgs) {
3581         qemu_log_mask(LOG_GUEST_ERROR,
3582                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3583                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3584         return;
3585     }
3586 
3587     raw_write(env, ri, value);
3588 }
3589 
3590 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3591     /* Reset for all these registers is handled in arm_cpu_reset(),
3592      * because the PMSAv7 is also used by M-profile CPUs, which do
3593      * not register cpregs but still need the state to be reset.
3594      */
3595     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3596       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3597       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3598       .readfn = pmsav7_read, .writefn = pmsav7_write,
3599       .resetfn = arm_cp_reset_ignore },
3600     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3601       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3602       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3603       .readfn = pmsav7_read, .writefn = pmsav7_write,
3604       .resetfn = arm_cp_reset_ignore },
3605     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3606       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3607       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3608       .readfn = pmsav7_read, .writefn = pmsav7_write,
3609       .resetfn = arm_cp_reset_ignore },
3610     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3611       .access = PL1_RW,
3612       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3613       .writefn = pmsav7_rgnr_write,
3614       .resetfn = arm_cp_reset_ignore },
3615 };
3616 
3617 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3618     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3619       .access = PL1_RW, .type = ARM_CP_ALIAS,
3620       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3621       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3622     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3623       .access = PL1_RW, .type = ARM_CP_ALIAS,
3624       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3625       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3626     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3627       .access = PL1_RW,
3628       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3629       .resetvalue = 0, },
3630     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3631       .access = PL1_RW,
3632       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3633       .resetvalue = 0, },
3634     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3635       .access = PL1_RW,
3636       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3637     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3638       .access = PL1_RW,
3639       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3640     /* Protection region base and size registers */
3641     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3642       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3643       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3644     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3645       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3646       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3647     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3648       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3649       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3650     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3651       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3652       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3653     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3654       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3655       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3656     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3657       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3658       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3659     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3660       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3661       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3662     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3663       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3664       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3665 };
3666 
3667 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3668                                  uint64_t value)
3669 {
3670     TCR *tcr = raw_ptr(env, ri);
3671     int maskshift = extract32(value, 0, 3);
3672 
3673     if (!arm_feature(env, ARM_FEATURE_V8)) {
3674         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3675             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3676              * using Long-desciptor translation table format */
3677             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3678         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3679             /* In an implementation that includes the Security Extensions
3680              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3681              * Short-descriptor translation table format.
3682              */
3683             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3684         } else {
3685             value &= TTBCR_N;
3686         }
3687     }
3688 
3689     /* Update the masks corresponding to the TCR bank being written
3690      * Note that we always calculate mask and base_mask, but
3691      * they are only used for short-descriptor tables (ie if EAE is 0);
3692      * for long-descriptor tables the TCR fields are used differently
3693      * and the mask and base_mask values are meaningless.
3694      */
3695     tcr->raw_tcr = value;
3696     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3697     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3698 }
3699 
3700 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3701                              uint64_t value)
3702 {
3703     ARMCPU *cpu = env_archcpu(env);
3704     TCR *tcr = raw_ptr(env, ri);
3705 
3706     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3707         /* With LPAE the TTBCR could result in a change of ASID
3708          * via the TTBCR.A1 bit, so do a TLB flush.
3709          */
3710         tlb_flush(CPU(cpu));
3711     }
3712     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3713     value = deposit64(tcr->raw_tcr, 0, 32, value);
3714     vmsa_ttbcr_raw_write(env, ri, value);
3715 }
3716 
3717 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3718 {
3719     TCR *tcr = raw_ptr(env, ri);
3720 
3721     /* Reset both the TCR as well as the masks corresponding to the bank of
3722      * the TCR being reset.
3723      */
3724     tcr->raw_tcr = 0;
3725     tcr->mask = 0;
3726     tcr->base_mask = 0xffffc000u;
3727 }
3728 
3729 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3730                                uint64_t value)
3731 {
3732     ARMCPU *cpu = env_archcpu(env);
3733     TCR *tcr = raw_ptr(env, ri);
3734 
3735     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3736     tlb_flush(CPU(cpu));
3737     tcr->raw_tcr = value;
3738 }
3739 
3740 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3741                             uint64_t value)
3742 {
3743     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3744     if (cpreg_field_is_64bit(ri) &&
3745         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3746         ARMCPU *cpu = env_archcpu(env);
3747         tlb_flush(CPU(cpu));
3748     }
3749     raw_write(env, ri, value);
3750 }
3751 
3752 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3753                                     uint64_t value)
3754 {
3755     /*
3756      * If we are running with E2&0 regime, then an ASID is active.
3757      * Flush if that might be changing.  Note we're not checking
3758      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
3759      * holds the active ASID, only checking the field that might.
3760      */
3761     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
3762         (arm_hcr_el2_eff(env) & HCR_E2H)) {
3763         uint16_t mask = ARMMMUIdxBit_E20_2 |
3764                         ARMMMUIdxBit_E20_2_PAN |
3765                         ARMMMUIdxBit_E20_0;
3766 
3767         if (arm_is_secure_below_el3(env)) {
3768             mask >>= ARM_MMU_IDX_A_NS;
3769         }
3770 
3771         tlb_flush_by_mmuidx(env_cpu(env), mask);
3772     }
3773     raw_write(env, ri, value);
3774 }
3775 
3776 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3777                         uint64_t value)
3778 {
3779     ARMCPU *cpu = env_archcpu(env);
3780     CPUState *cs = CPU(cpu);
3781 
3782     /*
3783      * A change in VMID to the stage2 page table (Stage2) invalidates
3784      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
3785      */
3786     if (raw_read(env, ri) != value) {
3787         uint16_t mask = ARMMMUIdxBit_E10_1 |
3788                         ARMMMUIdxBit_E10_1_PAN |
3789                         ARMMMUIdxBit_E10_0;
3790 
3791         if (arm_is_secure_below_el3(env)) {
3792             mask >>= ARM_MMU_IDX_A_NS;
3793         }
3794 
3795         tlb_flush_by_mmuidx(cs, mask);
3796         raw_write(env, ri, value);
3797     }
3798 }
3799 
3800 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3801     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3802       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
3803       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3804                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3805     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3806       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3807       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3808                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3809     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3810       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3811       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3812                              offsetof(CPUARMState, cp15.dfar_ns) } },
3813     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3814       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3815       .access = PL1_RW, .accessfn = access_tvm_trvm,
3816       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3817       .resetvalue = 0, },
3818 };
3819 
3820 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3821     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3822       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3823       .access = PL1_RW, .accessfn = access_tvm_trvm,
3824       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3825     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3826       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3827       .access = PL1_RW, .accessfn = access_tvm_trvm,
3828       .writefn = vmsa_ttbr_write, .resetvalue = 0,
3829       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3830                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3831     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3832       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3833       .access = PL1_RW, .accessfn = access_tvm_trvm,
3834       .writefn = vmsa_ttbr_write, .resetvalue = 0,
3835       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3836                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3837     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3838       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3839       .access = PL1_RW, .accessfn = access_tvm_trvm,
3840       .writefn = vmsa_tcr_el12_write,
3841       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3842       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3843     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3844       .access = PL1_RW, .accessfn = access_tvm_trvm,
3845       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3846       .raw_writefn = vmsa_ttbcr_raw_write,
3847       /* No offsetoflow32 -- pass the entire TCR to writefn/raw_writefn. */
3848       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.tcr_el[3]),
3849                              offsetof(CPUARMState, cp15.tcr_el[1])} },
3850 };
3851 
3852 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
3853  * qemu tlbs nor adjusting cached masks.
3854  */
3855 static const ARMCPRegInfo ttbcr2_reginfo = {
3856     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
3857     .access = PL1_RW, .accessfn = access_tvm_trvm,
3858     .type = ARM_CP_ALIAS,
3859     .bank_fieldoffsets = {
3860         offsetofhigh32(CPUARMState, cp15.tcr_el[3].raw_tcr),
3861         offsetofhigh32(CPUARMState, cp15.tcr_el[1].raw_tcr),
3862     },
3863 };
3864 
3865 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
3866                                 uint64_t value)
3867 {
3868     env->cp15.c15_ticonfig = value & 0xe7;
3869     /* The OS_TYPE bit in this register changes the reported CPUID! */
3870     env->cp15.c0_cpuid = (value & (1 << 5)) ?
3871         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
3872 }
3873 
3874 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
3875                                 uint64_t value)
3876 {
3877     env->cp15.c15_threadid = value & 0xffff;
3878 }
3879 
3880 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
3881                            uint64_t value)
3882 {
3883     /* Wait-for-interrupt (deprecated) */
3884     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
3885 }
3886 
3887 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
3888                                   uint64_t value)
3889 {
3890     /* On OMAP there are registers indicating the max/min index of dcache lines
3891      * containing a dirty line; cache flush operations have to reset these.
3892      */
3893     env->cp15.c15_i_max = 0x000;
3894     env->cp15.c15_i_min = 0xff0;
3895 }
3896 
3897 static const ARMCPRegInfo omap_cp_reginfo[] = {
3898     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
3899       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
3900       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
3901       .resetvalue = 0, },
3902     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
3903       .access = PL1_RW, .type = ARM_CP_NOP },
3904     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
3905       .access = PL1_RW,
3906       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
3907       .writefn = omap_ticonfig_write },
3908     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
3909       .access = PL1_RW,
3910       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
3911     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
3912       .access = PL1_RW, .resetvalue = 0xff0,
3913       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
3914     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
3915       .access = PL1_RW,
3916       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
3917       .writefn = omap_threadid_write },
3918     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
3919       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3920       .type = ARM_CP_NO_RAW,
3921       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
3922     /* TODO: Peripheral port remap register:
3923      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
3924      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
3925      * when MMU is off.
3926      */
3927     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
3928       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
3929       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
3930       .writefn = omap_cachemaint_write },
3931     { .name = "C9", .cp = 15, .crn = 9,
3932       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
3933       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
3934 };
3935 
3936 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
3937                               uint64_t value)
3938 {
3939     env->cp15.c15_cpar = value & 0x3fff;
3940 }
3941 
3942 static const ARMCPRegInfo xscale_cp_reginfo[] = {
3943     { .name = "XSCALE_CPAR",
3944       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
3945       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
3946       .writefn = xscale_cpar_write, },
3947     { .name = "XSCALE_AUXCR",
3948       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
3949       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
3950       .resetvalue = 0, },
3951     /* XScale specific cache-lockdown: since we have no cache we NOP these
3952      * and hope the guest does not really rely on cache behaviour.
3953      */
3954     { .name = "XSCALE_LOCK_ICACHE_LINE",
3955       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
3956       .access = PL1_W, .type = ARM_CP_NOP },
3957     { .name = "XSCALE_UNLOCK_ICACHE",
3958       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
3959       .access = PL1_W, .type = ARM_CP_NOP },
3960     { .name = "XSCALE_DCACHE_LOCK",
3961       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
3962       .access = PL1_RW, .type = ARM_CP_NOP },
3963     { .name = "XSCALE_UNLOCK_DCACHE",
3964       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
3965       .access = PL1_W, .type = ARM_CP_NOP },
3966 };
3967 
3968 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
3969     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
3970      * implementation of this implementation-defined space.
3971      * Ideally this should eventually disappear in favour of actually
3972      * implementing the correct behaviour for all cores.
3973      */
3974     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
3975       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
3976       .access = PL1_RW,
3977       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
3978       .resetvalue = 0 },
3979 };
3980 
3981 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
3982     /* Cache status: RAZ because we have no cache so it's always clean */
3983     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
3984       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3985       .resetvalue = 0 },
3986 };
3987 
3988 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
3989     /* We never have a a block transfer operation in progress */
3990     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
3991       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
3992       .resetvalue = 0 },
3993     /* The cache ops themselves: these all NOP for QEMU */
3994     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
3995       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3996     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
3997       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
3998     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
3999       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4000     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4001       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4002     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4003       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4004     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4005       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4006 };
4007 
4008 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4009     /* The cache test-and-clean instructions always return (1 << 30)
4010      * to indicate that there are no dirty cache lines.
4011      */
4012     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4013       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4014       .resetvalue = (1 << 30) },
4015     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4016       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4017       .resetvalue = (1 << 30) },
4018 };
4019 
4020 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4021     /* Ignore ReadBuffer accesses */
4022     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4023       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4024       .access = PL1_RW, .resetvalue = 0,
4025       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4026 };
4027 
4028 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4029 {
4030     unsigned int cur_el = arm_current_el(env);
4031 
4032     if (arm_is_el2_enabled(env) && cur_el == 1) {
4033         return env->cp15.vpidr_el2;
4034     }
4035     return raw_read(env, ri);
4036 }
4037 
4038 static uint64_t mpidr_read_val(CPUARMState *env)
4039 {
4040     ARMCPU *cpu = env_archcpu(env);
4041     uint64_t mpidr = cpu->mp_affinity;
4042 
4043     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4044         mpidr |= (1U << 31);
4045         /* Cores which are uniprocessor (non-coherent)
4046          * but still implement the MP extensions set
4047          * bit 30. (For instance, Cortex-R5).
4048          */
4049         if (cpu->mp_is_up) {
4050             mpidr |= (1u << 30);
4051         }
4052     }
4053     return mpidr;
4054 }
4055 
4056 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4057 {
4058     unsigned int cur_el = arm_current_el(env);
4059 
4060     if (arm_is_el2_enabled(env) && cur_el == 1) {
4061         return env->cp15.vmpidr_el2;
4062     }
4063     return mpidr_read_val(env);
4064 }
4065 
4066 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4067     /* NOP AMAIR0/1 */
4068     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4069       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4070       .access = PL1_RW, .accessfn = access_tvm_trvm,
4071       .type = ARM_CP_CONST, .resetvalue = 0 },
4072     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4073     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4074       .access = PL1_RW, .accessfn = access_tvm_trvm,
4075       .type = ARM_CP_CONST, .resetvalue = 0 },
4076     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4077       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4078       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4079                              offsetof(CPUARMState, cp15.par_ns)} },
4080     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4081       .access = PL1_RW, .accessfn = access_tvm_trvm,
4082       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4083       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4084                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4085       .writefn = vmsa_ttbr_write, },
4086     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4087       .access = PL1_RW, .accessfn = access_tvm_trvm,
4088       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4089       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4090                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4091       .writefn = vmsa_ttbr_write, },
4092 };
4093 
4094 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4095 {
4096     return vfp_get_fpcr(env);
4097 }
4098 
4099 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4100                             uint64_t value)
4101 {
4102     vfp_set_fpcr(env, value);
4103 }
4104 
4105 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4106 {
4107     return vfp_get_fpsr(env);
4108 }
4109 
4110 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4111                             uint64_t value)
4112 {
4113     vfp_set_fpsr(env, value);
4114 }
4115 
4116 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4117                                        bool isread)
4118 {
4119     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4120         return CP_ACCESS_TRAP;
4121     }
4122     return CP_ACCESS_OK;
4123 }
4124 
4125 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4126                             uint64_t value)
4127 {
4128     env->daif = value & PSTATE_DAIF;
4129 }
4130 
4131 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4132 {
4133     return env->pstate & PSTATE_PAN;
4134 }
4135 
4136 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4137                            uint64_t value)
4138 {
4139     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4140 }
4141 
4142 static const ARMCPRegInfo pan_reginfo = {
4143     .name = "PAN", .state = ARM_CP_STATE_AA64,
4144     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4145     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4146     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4147 };
4148 
4149 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4150 {
4151     return env->pstate & PSTATE_UAO;
4152 }
4153 
4154 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4155                            uint64_t value)
4156 {
4157     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4158 }
4159 
4160 static const ARMCPRegInfo uao_reginfo = {
4161     .name = "UAO", .state = ARM_CP_STATE_AA64,
4162     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4163     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4164     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4165 };
4166 
4167 static uint64_t aa64_dit_read(CPUARMState *env, const ARMCPRegInfo *ri)
4168 {
4169     return env->pstate & PSTATE_DIT;
4170 }
4171 
4172 static void aa64_dit_write(CPUARMState *env, const ARMCPRegInfo *ri,
4173                            uint64_t value)
4174 {
4175     env->pstate = (env->pstate & ~PSTATE_DIT) | (value & PSTATE_DIT);
4176 }
4177 
4178 static const ARMCPRegInfo dit_reginfo = {
4179     .name = "DIT", .state = ARM_CP_STATE_AA64,
4180     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 5,
4181     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4182     .readfn = aa64_dit_read, .writefn = aa64_dit_write
4183 };
4184 
4185 static uint64_t aa64_ssbs_read(CPUARMState *env, const ARMCPRegInfo *ri)
4186 {
4187     return env->pstate & PSTATE_SSBS;
4188 }
4189 
4190 static void aa64_ssbs_write(CPUARMState *env, const ARMCPRegInfo *ri,
4191                            uint64_t value)
4192 {
4193     env->pstate = (env->pstate & ~PSTATE_SSBS) | (value & PSTATE_SSBS);
4194 }
4195 
4196 static const ARMCPRegInfo ssbs_reginfo = {
4197     .name = "SSBS", .state = ARM_CP_STATE_AA64,
4198     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 6,
4199     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4200     .readfn = aa64_ssbs_read, .writefn = aa64_ssbs_write
4201 };
4202 
4203 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4204                                               const ARMCPRegInfo *ri,
4205                                               bool isread)
4206 {
4207     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4208     switch (arm_current_el(env)) {
4209     case 0:
4210         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4211         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4212             return CP_ACCESS_TRAP;
4213         }
4214         /* fall through */
4215     case 1:
4216         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4217         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4218             return CP_ACCESS_TRAP_EL2;
4219         }
4220         break;
4221     }
4222     return CP_ACCESS_OK;
4223 }
4224 
4225 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4226                                               const ARMCPRegInfo *ri,
4227                                               bool isread)
4228 {
4229     /* Cache invalidate/clean to Point of Unification... */
4230     switch (arm_current_el(env)) {
4231     case 0:
4232         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4233         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4234             return CP_ACCESS_TRAP;
4235         }
4236         /* fall through */
4237     case 1:
4238         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4239         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4240             return CP_ACCESS_TRAP_EL2;
4241         }
4242         break;
4243     }
4244     return CP_ACCESS_OK;
4245 }
4246 
4247 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4248  * Page D4-1736 (DDI0487A.b)
4249  */
4250 
4251 static int vae1_tlbmask(CPUARMState *env)
4252 {
4253     uint64_t hcr = arm_hcr_el2_eff(env);
4254     uint16_t mask;
4255 
4256     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4257         mask = ARMMMUIdxBit_E20_2 |
4258                ARMMMUIdxBit_E20_2_PAN |
4259                ARMMMUIdxBit_E20_0;
4260     } else {
4261         mask = ARMMMUIdxBit_E10_1 |
4262                ARMMMUIdxBit_E10_1_PAN |
4263                ARMMMUIdxBit_E10_0;
4264     }
4265 
4266     if (arm_is_secure_below_el3(env)) {
4267         mask >>= ARM_MMU_IDX_A_NS;
4268     }
4269 
4270     return mask;
4271 }
4272 
4273 /* Return 56 if TBI is enabled, 64 otherwise. */
4274 static int tlbbits_for_regime(CPUARMState *env, ARMMMUIdx mmu_idx,
4275                               uint64_t addr)
4276 {
4277     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
4278     int tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
4279     int select = extract64(addr, 55, 1);
4280 
4281     return (tbi >> select) & 1 ? 56 : 64;
4282 }
4283 
4284 static int vae1_tlbbits(CPUARMState *env, uint64_t addr)
4285 {
4286     uint64_t hcr = arm_hcr_el2_eff(env);
4287     ARMMMUIdx mmu_idx;
4288 
4289     /* Only the regime of the mmu_idx below is significant. */
4290     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4291         mmu_idx = ARMMMUIdx_E20_0;
4292     } else {
4293         mmu_idx = ARMMMUIdx_E10_0;
4294     }
4295 
4296     if (arm_is_secure_below_el3(env)) {
4297         mmu_idx &= ~ARM_MMU_IDX_A_NS;
4298     }
4299 
4300     return tlbbits_for_regime(env, mmu_idx, addr);
4301 }
4302 
4303 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4304                                       uint64_t value)
4305 {
4306     CPUState *cs = env_cpu(env);
4307     int mask = vae1_tlbmask(env);
4308 
4309     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4310 }
4311 
4312 static void tlbi_aa64_vmalle1_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     if (tlb_force_broadcast(env)) {
4319         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4320     } else {
4321         tlb_flush_by_mmuidx(cs, mask);
4322     }
4323 }
4324 
4325 static int alle1_tlbmask(CPUARMState *env)
4326 {
4327     /*
4328      * Note that the 'ALL' scope must invalidate both stage 1 and
4329      * stage 2 translations, whereas most other scopes only invalidate
4330      * stage 1 translations.
4331      */
4332     if (arm_is_secure_below_el3(env)) {
4333         return ARMMMUIdxBit_SE10_1 |
4334                ARMMMUIdxBit_SE10_1_PAN |
4335                ARMMMUIdxBit_SE10_0;
4336     } else {
4337         return ARMMMUIdxBit_E10_1 |
4338                ARMMMUIdxBit_E10_1_PAN |
4339                ARMMMUIdxBit_E10_0;
4340     }
4341 }
4342 
4343 static int e2_tlbmask(CPUARMState *env)
4344 {
4345     if (arm_is_secure_below_el3(env)) {
4346         return ARMMMUIdxBit_SE20_0 |
4347                ARMMMUIdxBit_SE20_2 |
4348                ARMMMUIdxBit_SE20_2_PAN |
4349                ARMMMUIdxBit_SE2;
4350     } else {
4351         return ARMMMUIdxBit_E20_0 |
4352                ARMMMUIdxBit_E20_2 |
4353                ARMMMUIdxBit_E20_2_PAN |
4354                ARMMMUIdxBit_E2;
4355     }
4356 }
4357 
4358 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4359                                   uint64_t value)
4360 {
4361     CPUState *cs = env_cpu(env);
4362     int mask = alle1_tlbmask(env);
4363 
4364     tlb_flush_by_mmuidx(cs, mask);
4365 }
4366 
4367 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4368                                   uint64_t value)
4369 {
4370     CPUState *cs = env_cpu(env);
4371     int mask = e2_tlbmask(env);
4372 
4373     tlb_flush_by_mmuidx(cs, mask);
4374 }
4375 
4376 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4377                                   uint64_t value)
4378 {
4379     ARMCPU *cpu = env_archcpu(env);
4380     CPUState *cs = CPU(cpu);
4381 
4382     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4383 }
4384 
4385 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4386                                     uint64_t value)
4387 {
4388     CPUState *cs = env_cpu(env);
4389     int mask = alle1_tlbmask(env);
4390 
4391     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4392 }
4393 
4394 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4395                                     uint64_t value)
4396 {
4397     CPUState *cs = env_cpu(env);
4398     int mask = e2_tlbmask(env);
4399 
4400     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4401 }
4402 
4403 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4404                                     uint64_t value)
4405 {
4406     CPUState *cs = env_cpu(env);
4407 
4408     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4409 }
4410 
4411 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4412                                  uint64_t value)
4413 {
4414     /* Invalidate by VA, EL2
4415      * Currently handles both VAE2 and VALE2, since we don't support
4416      * flush-last-level-only.
4417      */
4418     CPUState *cs = env_cpu(env);
4419     int mask = e2_tlbmask(env);
4420     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4421 
4422     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4423 }
4424 
4425 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4426                                  uint64_t value)
4427 {
4428     /* Invalidate by VA, EL3
4429      * Currently handles both VAE3 and VALE3, since we don't support
4430      * flush-last-level-only.
4431      */
4432     ARMCPU *cpu = env_archcpu(env);
4433     CPUState *cs = CPU(cpu);
4434     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4435 
4436     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4437 }
4438 
4439 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4440                                    uint64_t value)
4441 {
4442     CPUState *cs = env_cpu(env);
4443     int mask = vae1_tlbmask(env);
4444     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4445     int bits = vae1_tlbbits(env, pageaddr);
4446 
4447     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4448 }
4449 
4450 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4451                                  uint64_t value)
4452 {
4453     /* Invalidate by VA, EL1&0 (AArch64 version).
4454      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4455      * since we don't support flush-for-specific-ASID-only or
4456      * flush-last-level-only.
4457      */
4458     CPUState *cs = env_cpu(env);
4459     int mask = vae1_tlbmask(env);
4460     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4461     int bits = vae1_tlbbits(env, pageaddr);
4462 
4463     if (tlb_force_broadcast(env)) {
4464         tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4465     } else {
4466         tlb_flush_page_bits_by_mmuidx(cs, pageaddr, mask, bits);
4467     }
4468 }
4469 
4470 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4471                                    uint64_t value)
4472 {
4473     CPUState *cs = env_cpu(env);
4474     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4475     bool secure = arm_is_secure_below_el3(env);
4476     int mask = secure ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2;
4477     int bits = tlbbits_for_regime(env, secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2,
4478                                   pageaddr);
4479 
4480     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4481 }
4482 
4483 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4484                                    uint64_t value)
4485 {
4486     CPUState *cs = env_cpu(env);
4487     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4488     int bits = tlbbits_for_regime(env, ARMMMUIdx_SE3, pageaddr);
4489 
4490     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr,
4491                                                   ARMMMUIdxBit_SE3, bits);
4492 }
4493 
4494 #ifdef TARGET_AARCH64
4495 typedef struct {
4496     uint64_t base;
4497     uint64_t length;
4498 } TLBIRange;
4499 
4500 static TLBIRange tlbi_aa64_get_range(CPUARMState *env, ARMMMUIdx mmuidx,
4501                                      uint64_t value)
4502 {
4503     unsigned int page_size_granule, page_shift, num, scale, exponent;
4504     /* Extract one bit to represent the va selector in use. */
4505     uint64_t select = sextract64(value, 36, 1);
4506     ARMVAParameters param = aa64_va_parameters(env, select, mmuidx, true);
4507     TLBIRange ret = { };
4508 
4509     page_size_granule = extract64(value, 46, 2);
4510 
4511     /* The granule encoded in value must match the granule in use. */
4512     if (page_size_granule != (param.using64k ? 3 : param.using16k ? 2 : 1)) {
4513         qemu_log_mask(LOG_GUEST_ERROR, "Invalid tlbi page size granule %d\n",
4514                       page_size_granule);
4515         return ret;
4516     }
4517 
4518     page_shift = (page_size_granule - 1) * 2 + 12;
4519     num = extract64(value, 39, 5);
4520     scale = extract64(value, 44, 2);
4521     exponent = (5 * scale) + 1;
4522 
4523     ret.length = (num + 1) << (exponent + page_shift);
4524 
4525     if (param.select) {
4526         ret.base = sextract64(value, 0, 37);
4527     } else {
4528         ret.base = extract64(value, 0, 37);
4529     }
4530     if (param.ds) {
4531         /*
4532          * With DS=1, BaseADDR is always shifted 16 so that it is able
4533          * to address all 52 va bits.  The input address is perforce
4534          * aligned on a 64k boundary regardless of translation granule.
4535          */
4536         page_shift = 16;
4537     }
4538     ret.base <<= page_shift;
4539 
4540     return ret;
4541 }
4542 
4543 static void do_rvae_write(CPUARMState *env, uint64_t value,
4544                           int idxmap, bool synced)
4545 {
4546     ARMMMUIdx one_idx = ARM_MMU_IDX_A | ctz32(idxmap);
4547     TLBIRange range;
4548     int bits;
4549 
4550     range = tlbi_aa64_get_range(env, one_idx, value);
4551     bits = tlbbits_for_regime(env, one_idx, range.base);
4552 
4553     if (synced) {
4554         tlb_flush_range_by_mmuidx_all_cpus_synced(env_cpu(env),
4555                                                   range.base,
4556                                                   range.length,
4557                                                   idxmap,
4558                                                   bits);
4559     } else {
4560         tlb_flush_range_by_mmuidx(env_cpu(env), range.base,
4561                                   range.length, idxmap, bits);
4562     }
4563 }
4564 
4565 static void tlbi_aa64_rvae1_write(CPUARMState *env,
4566                                   const ARMCPRegInfo *ri,
4567                                   uint64_t value)
4568 {
4569     /*
4570      * Invalidate by VA range, EL1&0.
4571      * Currently handles all of RVAE1, RVAAE1, RVAALE1 and RVALE1,
4572      * since we don't support flush-for-specific-ASID-only or
4573      * flush-last-level-only.
4574      */
4575 
4576     do_rvae_write(env, value, vae1_tlbmask(env),
4577                   tlb_force_broadcast(env));
4578 }
4579 
4580 static void tlbi_aa64_rvae1is_write(CPUARMState *env,
4581                                     const ARMCPRegInfo *ri,
4582                                     uint64_t value)
4583 {
4584     /*
4585      * Invalidate by VA range, Inner/Outer Shareable EL1&0.
4586      * Currently handles all of RVAE1IS, RVAE1OS, RVAAE1IS, RVAAE1OS,
4587      * RVAALE1IS, RVAALE1OS, RVALE1IS and RVALE1OS, since we don't support
4588      * flush-for-specific-ASID-only, flush-last-level-only or inner/outer
4589      * shareable specific flushes.
4590      */
4591 
4592     do_rvae_write(env, value, vae1_tlbmask(env), true);
4593 }
4594 
4595 static int vae2_tlbmask(CPUARMState *env)
4596 {
4597     return (arm_is_secure_below_el3(env)
4598             ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2);
4599 }
4600 
4601 static void tlbi_aa64_rvae2_write(CPUARMState *env,
4602                                   const ARMCPRegInfo *ri,
4603                                   uint64_t value)
4604 {
4605     /*
4606      * Invalidate by VA range, EL2.
4607      * Currently handles all of RVAE2 and RVALE2,
4608      * since we don't support flush-for-specific-ASID-only or
4609      * flush-last-level-only.
4610      */
4611 
4612     do_rvae_write(env, value, vae2_tlbmask(env),
4613                   tlb_force_broadcast(env));
4614 
4615 
4616 }
4617 
4618 static void tlbi_aa64_rvae2is_write(CPUARMState *env,
4619                                     const ARMCPRegInfo *ri,
4620                                     uint64_t value)
4621 {
4622     /*
4623      * Invalidate by VA range, Inner/Outer Shareable, EL2.
4624      * Currently handles all of RVAE2IS, RVAE2OS, RVALE2IS and RVALE2OS,
4625      * since we don't support flush-for-specific-ASID-only,
4626      * flush-last-level-only or inner/outer shareable specific flushes.
4627      */
4628 
4629     do_rvae_write(env, value, vae2_tlbmask(env), true);
4630 
4631 }
4632 
4633 static void tlbi_aa64_rvae3_write(CPUARMState *env,
4634                                   const ARMCPRegInfo *ri,
4635                                   uint64_t value)
4636 {
4637     /*
4638      * Invalidate by VA range, EL3.
4639      * Currently handles all of RVAE3 and RVALE3,
4640      * since we don't support flush-for-specific-ASID-only or
4641      * flush-last-level-only.
4642      */
4643 
4644     do_rvae_write(env, value, ARMMMUIdxBit_SE3,
4645                   tlb_force_broadcast(env));
4646 }
4647 
4648 static void tlbi_aa64_rvae3is_write(CPUARMState *env,
4649                                     const ARMCPRegInfo *ri,
4650                                     uint64_t value)
4651 {
4652     /*
4653      * Invalidate by VA range, EL3, Inner/Outer Shareable.
4654      * Currently handles all of RVAE3IS, RVAE3OS, RVALE3IS and RVALE3OS,
4655      * since we don't support flush-for-specific-ASID-only,
4656      * flush-last-level-only or inner/outer specific flushes.
4657      */
4658 
4659     do_rvae_write(env, value, ARMMMUIdxBit_SE3, true);
4660 }
4661 #endif
4662 
4663 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4664                                       bool isread)
4665 {
4666     int cur_el = arm_current_el(env);
4667 
4668     if (cur_el < 2) {
4669         uint64_t hcr = arm_hcr_el2_eff(env);
4670 
4671         if (cur_el == 0) {
4672             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4673                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4674                     return CP_ACCESS_TRAP_EL2;
4675                 }
4676             } else {
4677                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4678                     return CP_ACCESS_TRAP;
4679                 }
4680                 if (hcr & HCR_TDZ) {
4681                     return CP_ACCESS_TRAP_EL2;
4682                 }
4683             }
4684         } else if (hcr & HCR_TDZ) {
4685             return CP_ACCESS_TRAP_EL2;
4686         }
4687     }
4688     return CP_ACCESS_OK;
4689 }
4690 
4691 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4692 {
4693     ARMCPU *cpu = env_archcpu(env);
4694     int dzp_bit = 1 << 4;
4695 
4696     /* DZP indicates whether DC ZVA access is allowed */
4697     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4698         dzp_bit = 0;
4699     }
4700     return cpu->dcz_blocksize | dzp_bit;
4701 }
4702 
4703 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4704                                     bool isread)
4705 {
4706     if (!(env->pstate & PSTATE_SP)) {
4707         /* Access to SP_EL0 is undefined if it's being used as
4708          * the stack pointer.
4709          */
4710         return CP_ACCESS_TRAP_UNCATEGORIZED;
4711     }
4712     return CP_ACCESS_OK;
4713 }
4714 
4715 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4716 {
4717     return env->pstate & PSTATE_SP;
4718 }
4719 
4720 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4721 {
4722     update_spsel(env, val);
4723 }
4724 
4725 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4726                         uint64_t value)
4727 {
4728     ARMCPU *cpu = env_archcpu(env);
4729 
4730     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4731         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4732         value &= ~SCTLR_M;
4733     }
4734 
4735     /* ??? Lots of these bits are not implemented.  */
4736 
4737     if (ri->state == ARM_CP_STATE_AA64 && !cpu_isar_feature(aa64_mte, cpu)) {
4738         if (ri->opc1 == 6) { /* SCTLR_EL3 */
4739             value &= ~(SCTLR_ITFSB | SCTLR_TCF | SCTLR_ATA);
4740         } else {
4741             value &= ~(SCTLR_ITFSB | SCTLR_TCF0 | SCTLR_TCF |
4742                        SCTLR_ATA0 | SCTLR_ATA);
4743         }
4744     }
4745 
4746     if (raw_read(env, ri) == value) {
4747         /* Skip the TLB flush if nothing actually changed; Linux likes
4748          * to do a lot of pointless SCTLR writes.
4749          */
4750         return;
4751     }
4752 
4753     raw_write(env, ri, value);
4754 
4755     /* This may enable/disable the MMU, so do a TLB flush.  */
4756     tlb_flush(CPU(cpu));
4757 
4758     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4759         /*
4760          * Normally we would always end the TB on an SCTLR write; see the
4761          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4762          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4763          * of hflags from the translator, so do it here.
4764          */
4765         arm_rebuild_hflags(env);
4766     }
4767 }
4768 
4769 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4770                        uint64_t value)
4771 {
4772     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4773 }
4774 
4775 static const ARMCPRegInfo v8_cp_reginfo[] = {
4776     /* Minimal set of EL0-visible registers. This will need to be expanded
4777      * significantly for system emulation of AArch64 CPUs.
4778      */
4779     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4780       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4781       .access = PL0_RW, .type = ARM_CP_NZCV },
4782     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4783       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4784       .type = ARM_CP_NO_RAW,
4785       .access = PL0_RW, .accessfn = aa64_daif_access,
4786       .fieldoffset = offsetof(CPUARMState, daif),
4787       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4788     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4789       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4790       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4791       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4792     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4793       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4794       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4795       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4796     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4797       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4798       .access = PL0_R, .type = ARM_CP_NO_RAW,
4799       .readfn = aa64_dczid_read },
4800     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4801       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4802       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4803 #ifndef CONFIG_USER_ONLY
4804       /* Avoid overhead of an access check that always passes in user-mode */
4805       .accessfn = aa64_zva_access,
4806 #endif
4807     },
4808     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4809       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4810       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4811     /* Cache ops: all NOPs since we don't emulate caches */
4812     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4813       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4814       .access = PL1_W, .type = ARM_CP_NOP,
4815       .accessfn = aa64_cacheop_pou_access },
4816     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4817       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4818       .access = PL1_W, .type = ARM_CP_NOP,
4819       .accessfn = aa64_cacheop_pou_access },
4820     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4821       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4822       .access = PL0_W, .type = ARM_CP_NOP,
4823       .accessfn = aa64_cacheop_pou_access },
4824     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4825       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4826       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4827       .type = ARM_CP_NOP },
4828     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4829       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4830       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4831     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4832       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4833       .access = PL0_W, .type = ARM_CP_NOP,
4834       .accessfn = aa64_cacheop_poc_access },
4835     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4836       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4837       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4838     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4839       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4840       .access = PL0_W, .type = ARM_CP_NOP,
4841       .accessfn = aa64_cacheop_pou_access },
4842     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4843       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4844       .access = PL0_W, .type = ARM_CP_NOP,
4845       .accessfn = aa64_cacheop_poc_access },
4846     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4847       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4848       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4849     /* TLBI operations */
4850     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4851       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4852       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4853       .writefn = tlbi_aa64_vmalle1is_write },
4854     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4855       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4856       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4857       .writefn = tlbi_aa64_vae1is_write },
4858     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4859       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4860       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4861       .writefn = tlbi_aa64_vmalle1is_write },
4862     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4863       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4864       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4865       .writefn = tlbi_aa64_vae1is_write },
4866     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4867       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4868       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4869       .writefn = tlbi_aa64_vae1is_write },
4870     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4871       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4872       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4873       .writefn = tlbi_aa64_vae1is_write },
4874     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4875       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4876       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4877       .writefn = tlbi_aa64_vmalle1_write },
4878     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4879       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4880       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4881       .writefn = tlbi_aa64_vae1_write },
4882     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4883       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4884       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4885       .writefn = tlbi_aa64_vmalle1_write },
4886     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4887       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4888       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4889       .writefn = tlbi_aa64_vae1_write },
4890     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4891       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4892       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4893       .writefn = tlbi_aa64_vae1_write },
4894     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4895       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4896       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4897       .writefn = tlbi_aa64_vae1_write },
4898     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4899       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4900       .access = PL2_W, .type = ARM_CP_NOP },
4901     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4902       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4903       .access = PL2_W, .type = ARM_CP_NOP },
4904     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4905       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4906       .access = PL2_W, .type = ARM_CP_NO_RAW,
4907       .writefn = tlbi_aa64_alle1is_write },
4908     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4909       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4910       .access = PL2_W, .type = ARM_CP_NO_RAW,
4911       .writefn = tlbi_aa64_alle1is_write },
4912     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4913       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4914       .access = PL2_W, .type = ARM_CP_NOP },
4915     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4916       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4917       .access = PL2_W, .type = ARM_CP_NOP },
4918     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4919       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4920       .access = PL2_W, .type = ARM_CP_NO_RAW,
4921       .writefn = tlbi_aa64_alle1_write },
4922     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4923       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4924       .access = PL2_W, .type = ARM_CP_NO_RAW,
4925       .writefn = tlbi_aa64_alle1is_write },
4926 #ifndef CONFIG_USER_ONLY
4927     /* 64 bit address translation operations */
4928     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4929       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4930       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4931       .writefn = ats_write64 },
4932     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4933       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4934       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4935       .writefn = ats_write64 },
4936     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4937       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4938       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4939       .writefn = ats_write64 },
4940     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4941       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4942       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4943       .writefn = ats_write64 },
4944     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4945       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4946       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4947       .writefn = ats_write64 },
4948     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4949       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4950       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4951       .writefn = ats_write64 },
4952     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4953       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4954       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4955       .writefn = ats_write64 },
4956     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4957       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4958       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4959       .writefn = ats_write64 },
4960     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4961     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4962       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4963       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4964       .writefn = ats_write64 },
4965     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4966       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4967       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4968       .writefn = ats_write64 },
4969     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4970       .type = ARM_CP_ALIAS,
4971       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4972       .access = PL1_RW, .resetvalue = 0,
4973       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4974       .writefn = par_write },
4975 #endif
4976     /* TLB invalidate last level of translation table walk */
4977     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4978       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4979       .writefn = tlbimva_is_write },
4980     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4981       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4982       .writefn = tlbimvaa_is_write },
4983     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4984       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4985       .writefn = tlbimva_write },
4986     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4987       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4988       .writefn = tlbimvaa_write },
4989     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4990       .type = ARM_CP_NO_RAW, .access = PL2_W,
4991       .writefn = tlbimva_hyp_write },
4992     { .name = "TLBIMVALHIS",
4993       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4994       .type = ARM_CP_NO_RAW, .access = PL2_W,
4995       .writefn = tlbimva_hyp_is_write },
4996     { .name = "TLBIIPAS2",
4997       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4998       .type = ARM_CP_NOP, .access = PL2_W },
4999     { .name = "TLBIIPAS2IS",
5000       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5001       .type = ARM_CP_NOP, .access = PL2_W },
5002     { .name = "TLBIIPAS2L",
5003       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5004       .type = ARM_CP_NOP, .access = PL2_W },
5005     { .name = "TLBIIPAS2LIS",
5006       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5007       .type = ARM_CP_NOP, .access = PL2_W },
5008     /* 32 bit cache operations */
5009     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5010       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5011     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5012       .type = ARM_CP_NOP, .access = PL1_W },
5013     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5014       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5015     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5016       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5017     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5018       .type = ARM_CP_NOP, .access = PL1_W },
5019     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5020       .type = ARM_CP_NOP, .access = PL1_W },
5021     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5022       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5023     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5024       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5025     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5026       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5027     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5028       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5029     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5030       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5031     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5032       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5033     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5034       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5035     /* MMU Domain access control / MPU write buffer control */
5036     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5037       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5038       .writefn = dacr_write, .raw_writefn = raw_write,
5039       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5040                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5041     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5042       .type = ARM_CP_ALIAS,
5043       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5044       .access = PL1_RW,
5045       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5046     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5047       .type = ARM_CP_ALIAS,
5048       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5049       .access = PL1_RW,
5050       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5051     /* We rely on the access checks not allowing the guest to write to the
5052      * state field when SPSel indicates that it's being used as the stack
5053      * pointer.
5054      */
5055     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5056       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5057       .access = PL1_RW, .accessfn = sp_el0_access,
5058       .type = ARM_CP_ALIAS,
5059       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5060     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5061       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5062       .access = PL2_RW, .type = ARM_CP_ALIAS,
5063       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5064     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5065       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5066       .type = ARM_CP_NO_RAW,
5067       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5068     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5069       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5070       .access = PL2_RW,
5071       .type = ARM_CP_ALIAS | ARM_CP_FPU | ARM_CP_EL3_NO_EL2_KEEP,
5072       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]) },
5073     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5074       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5075       .access = PL2_RW, .resetvalue = 0, .type = ARM_CP_EL3_NO_EL2_KEEP,
5076       .writefn = dacr_write, .raw_writefn = raw_write,
5077       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5078     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5079       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5080       .access = PL2_RW, .resetvalue = 0, .type = ARM_CP_EL3_NO_EL2_KEEP,
5081       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5082     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5083       .type = ARM_CP_ALIAS,
5084       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5085       .access = PL2_RW,
5086       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5087     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5088       .type = ARM_CP_ALIAS,
5089       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5090       .access = PL2_RW,
5091       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5092     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5093       .type = ARM_CP_ALIAS,
5094       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5095       .access = PL2_RW,
5096       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5097     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5098       .type = ARM_CP_ALIAS,
5099       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5100       .access = PL2_RW,
5101       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5102     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5103       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5104       .resetvalue = 0,
5105       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5106     { .name = "SDCR", .type = ARM_CP_ALIAS,
5107       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5108       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5109       .writefn = sdcr_write,
5110       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5111 };
5112 
5113 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5114 {
5115     ARMCPU *cpu = env_archcpu(env);
5116 
5117     if (arm_feature(env, ARM_FEATURE_V8)) {
5118         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5119     } else {
5120         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5121     }
5122 
5123     if (arm_feature(env, ARM_FEATURE_EL3)) {
5124         valid_mask &= ~HCR_HCD;
5125     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5126         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5127          * However, if we're using the SMC PSCI conduit then QEMU is
5128          * effectively acting like EL3 firmware and so the guest at
5129          * EL2 should retain the ability to prevent EL1 from being
5130          * able to make SMC calls into the ersatz firmware, so in
5131          * that case HCR.TSC should be read/write.
5132          */
5133         valid_mask &= ~HCR_TSC;
5134     }
5135 
5136     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5137         if (cpu_isar_feature(aa64_vh, cpu)) {
5138             valid_mask |= HCR_E2H;
5139         }
5140         if (cpu_isar_feature(aa64_ras, cpu)) {
5141             valid_mask |= HCR_TERR | HCR_TEA;
5142         }
5143         if (cpu_isar_feature(aa64_lor, cpu)) {
5144             valid_mask |= HCR_TLOR;
5145         }
5146         if (cpu_isar_feature(aa64_pauth, cpu)) {
5147             valid_mask |= HCR_API | HCR_APK;
5148         }
5149         if (cpu_isar_feature(aa64_mte, cpu)) {
5150             valid_mask |= HCR_ATA | HCR_DCT | HCR_TID5;
5151         }
5152     }
5153 
5154     /* Clear RES0 bits.  */
5155     value &= valid_mask;
5156 
5157     /*
5158      * These bits change the MMU setup:
5159      * HCR_VM enables stage 2 translation
5160      * HCR_PTW forbids certain page-table setups
5161      * HCR_DC disables stage1 and enables stage2 translation
5162      * HCR_DCT enables tagging on (disabled) stage1 translation
5163      */
5164     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC | HCR_DCT)) {
5165         tlb_flush(CPU(cpu));
5166     }
5167     env->cp15.hcr_el2 = value;
5168 
5169     /*
5170      * Updates to VI and VF require us to update the status of
5171      * virtual interrupts, which are the logical OR of these bits
5172      * and the state of the input lines from the GIC. (This requires
5173      * that we have the iothread lock, which is done by marking the
5174      * reginfo structs as ARM_CP_IO.)
5175      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5176      * possible for it to be taken immediately, because VIRQ and
5177      * VFIQ are masked unless running at EL0 or EL1, and HCR
5178      * can only be written at EL2.
5179      */
5180     g_assert(qemu_mutex_iothread_locked());
5181     arm_cpu_update_virq(cpu);
5182     arm_cpu_update_vfiq(cpu);
5183     arm_cpu_update_vserr(cpu);
5184 }
5185 
5186 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5187 {
5188     do_hcr_write(env, value, 0);
5189 }
5190 
5191 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5192                           uint64_t value)
5193 {
5194     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5195     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5196     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5197 }
5198 
5199 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5200                          uint64_t value)
5201 {
5202     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5203     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5204     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5205 }
5206 
5207 /*
5208  * Return the effective value of HCR_EL2.
5209  * Bits that are not included here:
5210  * RW       (read from SCR_EL3.RW as needed)
5211  */
5212 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5213 {
5214     uint64_t ret = env->cp15.hcr_el2;
5215 
5216     if (!arm_is_el2_enabled(env)) {
5217         /*
5218          * "This register has no effect if EL2 is not enabled in the
5219          * current Security state".  This is ARMv8.4-SecEL2 speak for
5220          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5221          *
5222          * Prior to that, the language was "In an implementation that
5223          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5224          * as if this field is 0 for all purposes other than a direct
5225          * read or write access of HCR_EL2".  With lots of enumeration
5226          * on a per-field basis.  In current QEMU, this is condition
5227          * is arm_is_secure_below_el3.
5228          *
5229          * Since the v8.4 language applies to the entire register, and
5230          * appears to be backward compatible, use that.
5231          */
5232         return 0;
5233     }
5234 
5235     /*
5236      * For a cpu that supports both aarch64 and aarch32, we can set bits
5237      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5238      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5239      */
5240     if (!arm_el_is_aa64(env, 2)) {
5241         uint64_t aa32_valid;
5242 
5243         /*
5244          * These bits are up-to-date as of ARMv8.6.
5245          * For HCR, it's easiest to list just the 2 bits that are invalid.
5246          * For HCR2, list those that are valid.
5247          */
5248         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5249         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5250                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5251         ret &= aa32_valid;
5252     }
5253 
5254     if (ret & HCR_TGE) {
5255         /* These bits are up-to-date as of ARMv8.6.  */
5256         if (ret & HCR_E2H) {
5257             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5258                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5259                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5260                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5261                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5262                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5263         } else {
5264             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5265         }
5266         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5267                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5268                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5269                  HCR_TLOR);
5270     }
5271 
5272     return ret;
5273 }
5274 
5275 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5276                            uint64_t value)
5277 {
5278     /*
5279      * For A-profile AArch32 EL3, if NSACR.CP10
5280      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5281      */
5282     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5283         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5284         value &= ~(0x3 << 10);
5285         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5286     }
5287     env->cp15.cptr_el[2] = value;
5288 }
5289 
5290 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5291 {
5292     /*
5293      * For A-profile AArch32 EL3, if NSACR.CP10
5294      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5295      */
5296     uint64_t value = env->cp15.cptr_el[2];
5297 
5298     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5299         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5300         value |= 0x3 << 10;
5301     }
5302     return value;
5303 }
5304 
5305 static const ARMCPRegInfo el2_cp_reginfo[] = {
5306     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5307       .type = ARM_CP_IO,
5308       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5309       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5310       .writefn = hcr_write },
5311     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5312       .type = ARM_CP_ALIAS | ARM_CP_IO,
5313       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5314       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5315       .writefn = hcr_writelow },
5316     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5317       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5318       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5319     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5320       .type = ARM_CP_ALIAS,
5321       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5322       .access = PL2_RW,
5323       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5324     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5325       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5326       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5327     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5328       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5329       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5330     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5331       .type = ARM_CP_ALIAS,
5332       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5333       .access = PL2_RW,
5334       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5335     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5336       .type = ARM_CP_ALIAS,
5337       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5338       .access = PL2_RW,
5339       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5340     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5341       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5342       .access = PL2_RW, .writefn = vbar_write,
5343       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5344       .resetvalue = 0 },
5345     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5346       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5347       .access = PL3_RW, .type = ARM_CP_ALIAS,
5348       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5349     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5350       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5351       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5352       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5353       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5354     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5355       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5356       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5357       .resetvalue = 0 },
5358     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5359       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5360       .access = PL2_RW, .type = ARM_CP_ALIAS,
5361       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5362     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5363       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5364       .access = PL2_RW, .type = ARM_CP_CONST,
5365       .resetvalue = 0 },
5366     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5367     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5368       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5369       .access = PL2_RW, .type = ARM_CP_CONST,
5370       .resetvalue = 0 },
5371     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5372       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5373       .access = PL2_RW, .type = ARM_CP_CONST,
5374       .resetvalue = 0 },
5375     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5376       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5377       .access = PL2_RW, .type = ARM_CP_CONST,
5378       .resetvalue = 0 },
5379     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5380       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5381       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5382       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5383       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5384     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5385       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5386       .type = ARM_CP_ALIAS,
5387       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5388       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5389     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5390       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5391       .access = PL2_RW,
5392       /* no .writefn needed as this can't cause an ASID change;
5393        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5394        */
5395       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5396     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5397       .cp = 15, .opc1 = 6, .crm = 2,
5398       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5399       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5400       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5401       .writefn = vttbr_write },
5402     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5403       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5404       .access = PL2_RW, .writefn = vttbr_write,
5405       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5406     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5407       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5408       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5409       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5410     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5411       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5412       .access = PL2_RW, .resetvalue = 0,
5413       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5414     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5415       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5416       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5417       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5418     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5419       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5420       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5421     { .name = "TLBIALLNSNH",
5422       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5423       .type = ARM_CP_NO_RAW, .access = PL2_W,
5424       .writefn = tlbiall_nsnh_write },
5425     { .name = "TLBIALLNSNHIS",
5426       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5427       .type = ARM_CP_NO_RAW, .access = PL2_W,
5428       .writefn = tlbiall_nsnh_is_write },
5429     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5430       .type = ARM_CP_NO_RAW, .access = PL2_W,
5431       .writefn = tlbiall_hyp_write },
5432     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5433       .type = ARM_CP_NO_RAW, .access = PL2_W,
5434       .writefn = tlbiall_hyp_is_write },
5435     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5436       .type = ARM_CP_NO_RAW, .access = PL2_W,
5437       .writefn = tlbimva_hyp_write },
5438     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5439       .type = ARM_CP_NO_RAW, .access = PL2_W,
5440       .writefn = tlbimva_hyp_is_write },
5441     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5442       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5443       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5444       .writefn = tlbi_aa64_alle2_write },
5445     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5446       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5447       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5448       .writefn = tlbi_aa64_vae2_write },
5449     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5450       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5451       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5452       .writefn = tlbi_aa64_vae2_write },
5453     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5454       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5455       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5456       .writefn = tlbi_aa64_alle2is_write },
5457     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5458       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5459       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5460       .writefn = tlbi_aa64_vae2is_write },
5461     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5462       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5463       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
5464       .writefn = tlbi_aa64_vae2is_write },
5465 #ifndef CONFIG_USER_ONLY
5466     /* Unlike the other EL2-related AT operations, these must
5467      * UNDEF from EL3 if EL2 is not implemented, which is why we
5468      * define them here rather than with the rest of the AT ops.
5469      */
5470     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5471       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5472       .access = PL2_W, .accessfn = at_s1e2_access,
5473       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC | ARM_CP_EL3_NO_EL2_UNDEF,
5474       .writefn = ats_write64 },
5475     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5476       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5477       .access = PL2_W, .accessfn = at_s1e2_access,
5478       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC | ARM_CP_EL3_NO_EL2_UNDEF,
5479       .writefn = ats_write64 },
5480     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5481      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5482      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5483      * to behave as if SCR.NS was 1.
5484      */
5485     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5486       .access = PL2_W,
5487       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5488     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5489       .access = PL2_W,
5490       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5491     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5492       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5493       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5494        * reset values as IMPDEF. We choose to reset to 3 to comply with
5495        * both ARMv7 and ARMv8.
5496        */
5497       .access = PL2_RW, .resetvalue = 3,
5498       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5499     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5500       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5501       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5502       .writefn = gt_cntvoff_write,
5503       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5504     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5505       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5506       .writefn = gt_cntvoff_write,
5507       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5508     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5509       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5510       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5511       .type = ARM_CP_IO, .access = PL2_RW,
5512       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5513     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5514       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5515       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5516       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5517     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5518       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5519       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5520       .resetfn = gt_hyp_timer_reset,
5521       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5522     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5523       .type = ARM_CP_IO,
5524       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5525       .access = PL2_RW,
5526       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5527       .resetvalue = 0,
5528       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5529 #endif
5530     /* The only field of MDCR_EL2 that has a defined architectural reset value
5531      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N.
5532      */
5533     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5534       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5535       .access = PL2_RW, .resetvalue = PMCR_NUM_COUNTERS,
5536       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5537     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5538       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5539       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5540       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5541     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5542       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5543       .access = PL2_RW,
5544       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5545     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5546       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5547       .access = PL2_RW,
5548       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5549 };
5550 
5551 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5552     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5553       .type = ARM_CP_ALIAS | ARM_CP_IO,
5554       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5555       .access = PL2_RW,
5556       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5557       .writefn = hcr_writehigh },
5558 };
5559 
5560 static CPAccessResult sel2_access(CPUARMState *env, const ARMCPRegInfo *ri,
5561                                   bool isread)
5562 {
5563     if (arm_current_el(env) == 3 || arm_is_secure_below_el3(env)) {
5564         return CP_ACCESS_OK;
5565     }
5566     return CP_ACCESS_TRAP_UNCATEGORIZED;
5567 }
5568 
5569 static const ARMCPRegInfo el2_sec_cp_reginfo[] = {
5570     { .name = "VSTTBR_EL2", .state = ARM_CP_STATE_AA64,
5571       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 0,
5572       .access = PL2_RW, .accessfn = sel2_access,
5573       .fieldoffset = offsetof(CPUARMState, cp15.vsttbr_el2) },
5574     { .name = "VSTCR_EL2", .state = ARM_CP_STATE_AA64,
5575       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 2,
5576       .access = PL2_RW, .accessfn = sel2_access,
5577       .fieldoffset = offsetof(CPUARMState, cp15.vstcr_el2) },
5578 };
5579 
5580 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5581                                    bool isread)
5582 {
5583     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5584      * At Secure EL1 it traps to EL3 or EL2.
5585      */
5586     if (arm_current_el(env) == 3) {
5587         return CP_ACCESS_OK;
5588     }
5589     if (arm_is_secure_below_el3(env)) {
5590         if (env->cp15.scr_el3 & SCR_EEL2) {
5591             return CP_ACCESS_TRAP_EL2;
5592         }
5593         return CP_ACCESS_TRAP_EL3;
5594     }
5595     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5596     if (isread) {
5597         return CP_ACCESS_OK;
5598     }
5599     return CP_ACCESS_TRAP_UNCATEGORIZED;
5600 }
5601 
5602 static const ARMCPRegInfo el3_cp_reginfo[] = {
5603     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5604       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5605       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5606       .resetfn = scr_reset, .writefn = scr_write },
5607     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5608       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5609       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5610       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5611       .writefn = scr_write },
5612     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5613       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5614       .access = PL3_RW, .resetvalue = 0,
5615       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5616     { .name = "SDER",
5617       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5618       .access = PL3_RW, .resetvalue = 0,
5619       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5620     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5621       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5622       .writefn = vbar_write, .resetvalue = 0,
5623       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5624     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5625       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5626       .access = PL3_RW, .resetvalue = 0,
5627       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5628     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5629       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5630       .access = PL3_RW,
5631       /* no .writefn needed as this can't cause an ASID change;
5632        * we must provide a .raw_writefn and .resetfn because we handle
5633        * reset and migration for the AArch32 TTBCR(S), which might be
5634        * using mask and base_mask.
5635        */
5636       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5637       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5638     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5639       .type = ARM_CP_ALIAS,
5640       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5641       .access = PL3_RW,
5642       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5643     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5644       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5645       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5646     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5647       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5648       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5649     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5650       .type = ARM_CP_ALIAS,
5651       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5652       .access = PL3_RW,
5653       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5654     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5655       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5656       .access = PL3_RW, .writefn = vbar_write,
5657       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5658       .resetvalue = 0 },
5659     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5660       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5661       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5662       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5663     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5664       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5665       .access = PL3_RW, .resetvalue = 0,
5666       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5667     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5668       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5669       .access = PL3_RW, .type = ARM_CP_CONST,
5670       .resetvalue = 0 },
5671     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5672       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5673       .access = PL3_RW, .type = ARM_CP_CONST,
5674       .resetvalue = 0 },
5675     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5676       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5677       .access = PL3_RW, .type = ARM_CP_CONST,
5678       .resetvalue = 0 },
5679     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5680       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5681       .access = PL3_W, .type = ARM_CP_NO_RAW,
5682       .writefn = tlbi_aa64_alle3is_write },
5683     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5684       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5685       .access = PL3_W, .type = ARM_CP_NO_RAW,
5686       .writefn = tlbi_aa64_vae3is_write },
5687     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5688       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5689       .access = PL3_W, .type = ARM_CP_NO_RAW,
5690       .writefn = tlbi_aa64_vae3is_write },
5691     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5692       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5693       .access = PL3_W, .type = ARM_CP_NO_RAW,
5694       .writefn = tlbi_aa64_alle3_write },
5695     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5696       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5697       .access = PL3_W, .type = ARM_CP_NO_RAW,
5698       .writefn = tlbi_aa64_vae3_write },
5699     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5700       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5701       .access = PL3_W, .type = ARM_CP_NO_RAW,
5702       .writefn = tlbi_aa64_vae3_write },
5703 };
5704 
5705 #ifndef CONFIG_USER_ONLY
5706 /* Test if system register redirection is to occur in the current state.  */
5707 static bool redirect_for_e2h(CPUARMState *env)
5708 {
5709     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5710 }
5711 
5712 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5713 {
5714     CPReadFn *readfn;
5715 
5716     if (redirect_for_e2h(env)) {
5717         /* Switch to the saved EL2 version of the register.  */
5718         ri = ri->opaque;
5719         readfn = ri->readfn;
5720     } else {
5721         readfn = ri->orig_readfn;
5722     }
5723     if (readfn == NULL) {
5724         readfn = raw_read;
5725     }
5726     return readfn(env, ri);
5727 }
5728 
5729 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5730                           uint64_t value)
5731 {
5732     CPWriteFn *writefn;
5733 
5734     if (redirect_for_e2h(env)) {
5735         /* Switch to the saved EL2 version of the register.  */
5736         ri = ri->opaque;
5737         writefn = ri->writefn;
5738     } else {
5739         writefn = ri->orig_writefn;
5740     }
5741     if (writefn == NULL) {
5742         writefn = raw_write;
5743     }
5744     writefn(env, ri, value);
5745 }
5746 
5747 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5748 {
5749     struct E2HAlias {
5750         uint32_t src_key, dst_key, new_key;
5751         const char *src_name, *dst_name, *new_name;
5752         bool (*feature)(const ARMISARegisters *id);
5753     };
5754 
5755 #define K(op0, op1, crn, crm, op2) \
5756     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5757 
5758     static const struct E2HAlias aliases[] = {
5759         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5760           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5761         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5762           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5763         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5764           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5765         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5766           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5767         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5768           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5769         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5770           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5771         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5772           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5773         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5774           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5775         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5776           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5777         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5778           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5779         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5780           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5781         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5782           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5783         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5784           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5785         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5786           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5787         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
5788           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
5789         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
5790           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
5791 
5792         /*
5793          * Note that redirection of ZCR is mentioned in the description
5794          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
5795          * not in the summary table.
5796          */
5797         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
5798           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
5799 
5800         { K(3, 0,  5, 6, 0), K(3, 4,  5, 6, 0), K(3, 5, 5, 6, 0),
5801           "TFSR_EL1", "TFSR_EL2", "TFSR_EL12", isar_feature_aa64_mte },
5802 
5803         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
5804         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
5805     };
5806 #undef K
5807 
5808     size_t i;
5809 
5810     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
5811         const struct E2HAlias *a = &aliases[i];
5812         ARMCPRegInfo *src_reg, *dst_reg, *new_reg;
5813         bool ok;
5814 
5815         if (a->feature && !a->feature(&cpu->isar)) {
5816             continue;
5817         }
5818 
5819         src_reg = g_hash_table_lookup(cpu->cp_regs,
5820                                       (gpointer)(uintptr_t)a->src_key);
5821         dst_reg = g_hash_table_lookup(cpu->cp_regs,
5822                                       (gpointer)(uintptr_t)a->dst_key);
5823         g_assert(src_reg != NULL);
5824         g_assert(dst_reg != NULL);
5825 
5826         /* Cross-compare names to detect typos in the keys.  */
5827         g_assert(strcmp(src_reg->name, a->src_name) == 0);
5828         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
5829 
5830         /* None of the core system registers use opaque; we will.  */
5831         g_assert(src_reg->opaque == NULL);
5832 
5833         /* Create alias before redirection so we dup the right data. */
5834         new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
5835 
5836         new_reg->name = a->new_name;
5837         new_reg->type |= ARM_CP_ALIAS;
5838         /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
5839         new_reg->access &= PL2_RW | PL3_RW;
5840 
5841         ok = g_hash_table_insert(cpu->cp_regs,
5842                                  (gpointer)(uintptr_t)a->new_key, new_reg);
5843         g_assert(ok);
5844 
5845         src_reg->opaque = dst_reg;
5846         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
5847         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
5848         if (!src_reg->raw_readfn) {
5849             src_reg->raw_readfn = raw_read;
5850         }
5851         if (!src_reg->raw_writefn) {
5852             src_reg->raw_writefn = raw_write;
5853         }
5854         src_reg->readfn = el2_e2h_read;
5855         src_reg->writefn = el2_e2h_write;
5856     }
5857 }
5858 #endif
5859 
5860 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5861                                      bool isread)
5862 {
5863     int cur_el = arm_current_el(env);
5864 
5865     if (cur_el < 2) {
5866         uint64_t hcr = arm_hcr_el2_eff(env);
5867 
5868         if (cur_el == 0) {
5869             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
5870                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
5871                     return CP_ACCESS_TRAP_EL2;
5872                 }
5873             } else {
5874                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5875                     return CP_ACCESS_TRAP;
5876                 }
5877                 if (hcr & HCR_TID2) {
5878                     return CP_ACCESS_TRAP_EL2;
5879                 }
5880             }
5881         } else if (hcr & HCR_TID2) {
5882             return CP_ACCESS_TRAP_EL2;
5883         }
5884     }
5885 
5886     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
5887         return CP_ACCESS_TRAP_EL2;
5888     }
5889 
5890     return CP_ACCESS_OK;
5891 }
5892 
5893 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5894                         uint64_t value)
5895 {
5896     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5897      * read via a bit in OSLSR_EL1.
5898      */
5899     int oslock;
5900 
5901     if (ri->state == ARM_CP_STATE_AA32) {
5902         oslock = (value == 0xC5ACCE55);
5903     } else {
5904         oslock = value & 1;
5905     }
5906 
5907     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5908 }
5909 
5910 static const ARMCPRegInfo debug_cp_reginfo[] = {
5911     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5912      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5913      * unlike DBGDRAR it is never accessible from EL0.
5914      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5915      * accessor.
5916      */
5917     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5918       .access = PL0_R, .accessfn = access_tdra,
5919       .type = ARM_CP_CONST, .resetvalue = 0 },
5920     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5921       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5922       .access = PL1_R, .accessfn = access_tdra,
5923       .type = ARM_CP_CONST, .resetvalue = 0 },
5924     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5925       .access = PL0_R, .accessfn = access_tdra,
5926       .type = ARM_CP_CONST, .resetvalue = 0 },
5927     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5928     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5929       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5930       .access = PL1_RW, .accessfn = access_tda,
5931       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5932       .resetvalue = 0 },
5933     /*
5934      * MDCCSR_EL0[30:29] map to EDSCR[30:29].  Simply RAZ as the external
5935      * Debug Communication Channel is not implemented.
5936      */
5937     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_AA64,
5938       .opc0 = 2, .opc1 = 3, .crn = 0, .crm = 1, .opc2 = 0,
5939       .access = PL0_R, .accessfn = access_tda,
5940       .type = ARM_CP_CONST, .resetvalue = 0 },
5941     /*
5942      * DBGDSCRint[15,12,5:2] map to MDSCR_EL1[15,12,5:2].  Map all bits as
5943      * it is unlikely a guest will care.
5944      * We don't implement the configurable EL0 access.
5945      */
5946     { .name = "DBGDSCRint", .state = ARM_CP_STATE_AA32,
5947       .cp = 14, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5948       .type = ARM_CP_ALIAS,
5949       .access = PL1_R, .accessfn = access_tda,
5950       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
5951     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
5952       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
5953       .access = PL1_W, .type = ARM_CP_NO_RAW,
5954       .accessfn = access_tdosa,
5955       .writefn = oslar_write },
5956     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
5957       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
5958       .access = PL1_R, .resetvalue = 10,
5959       .accessfn = access_tdosa,
5960       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
5961     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
5962     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
5963       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
5964       .access = PL1_RW, .accessfn = access_tdosa,
5965       .type = ARM_CP_NOP },
5966     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
5967      * implement vector catch debug events yet.
5968      */
5969     { .name = "DBGVCR",
5970       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
5971       .access = PL1_RW, .accessfn = access_tda,
5972       .type = ARM_CP_NOP },
5973     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
5974      * to save and restore a 32-bit guest's DBGVCR)
5975      */
5976     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
5977       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
5978       .access = PL2_RW, .accessfn = access_tda,
5979       .type = ARM_CP_NOP | ARM_CP_EL3_NO_EL2_KEEP },
5980     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
5981      * Channel but Linux may try to access this register. The 32-bit
5982      * alias is DBGDCCINT.
5983      */
5984     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
5985       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
5986       .access = PL1_RW, .accessfn = access_tda,
5987       .type = ARM_CP_NOP },
5988 };
5989 
5990 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
5991     /* 64 bit access versions of the (dummy) debug registers */
5992     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
5993       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5994     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
5995       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
5996 };
5997 
5998 /*
5999  * Check for traps to RAS registers, which are controlled
6000  * by HCR_EL2.TERR and SCR_EL3.TERR.
6001  */
6002 static CPAccessResult access_terr(CPUARMState *env, const ARMCPRegInfo *ri,
6003                                   bool isread)
6004 {
6005     int el = arm_current_el(env);
6006 
6007     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TERR)) {
6008         return CP_ACCESS_TRAP_EL2;
6009     }
6010     if (el < 3 && (env->cp15.scr_el3 & SCR_TERR)) {
6011         return CP_ACCESS_TRAP_EL3;
6012     }
6013     return CP_ACCESS_OK;
6014 }
6015 
6016 static uint64_t disr_read(CPUARMState *env, const ARMCPRegInfo *ri)
6017 {
6018     int el = arm_current_el(env);
6019 
6020     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_AMO)) {
6021         return env->cp15.vdisr_el2;
6022     }
6023     if (el < 3 && (env->cp15.scr_el3 & SCR_EA)) {
6024         return 0; /* RAZ/WI */
6025     }
6026     return env->cp15.disr_el1;
6027 }
6028 
6029 static void disr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
6030 {
6031     int el = arm_current_el(env);
6032 
6033     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_AMO)) {
6034         env->cp15.vdisr_el2 = val;
6035         return;
6036     }
6037     if (el < 3 && (env->cp15.scr_el3 & SCR_EA)) {
6038         return; /* RAZ/WI */
6039     }
6040     env->cp15.disr_el1 = val;
6041 }
6042 
6043 /*
6044  * Minimal RAS implementation with no Error Records.
6045  * Which means that all of the Error Record registers:
6046  *   ERXADDR_EL1
6047  *   ERXCTLR_EL1
6048  *   ERXFR_EL1
6049  *   ERXMISC0_EL1
6050  *   ERXMISC1_EL1
6051  *   ERXMISC2_EL1
6052  *   ERXMISC3_EL1
6053  *   ERXPFGCDN_EL1  (RASv1p1)
6054  *   ERXPFGCTL_EL1  (RASv1p1)
6055  *   ERXPFGF_EL1    (RASv1p1)
6056  *   ERXSTATUS_EL1
6057  * and
6058  *   ERRSELR_EL1
6059  * may generate UNDEFINED, which is the effect we get by not
6060  * listing them at all.
6061  */
6062 static const ARMCPRegInfo minimal_ras_reginfo[] = {
6063     { .name = "DISR_EL1", .state = ARM_CP_STATE_BOTH,
6064       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 1,
6065       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.disr_el1),
6066       .readfn = disr_read, .writefn = disr_write, .raw_writefn = raw_write },
6067     { .name = "ERRIDR_EL1", .state = ARM_CP_STATE_BOTH,
6068       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 3, .opc2 = 0,
6069       .access = PL1_R, .accessfn = access_terr,
6070       .type = ARM_CP_CONST, .resetvalue = 0 },
6071     { .name = "VDISR_EL2", .state = ARM_CP_STATE_BOTH,
6072       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 1, .opc2 = 1,
6073       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.vdisr_el2) },
6074     { .name = "VSESR_EL2", .state = ARM_CP_STATE_BOTH,
6075       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 3,
6076       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.vsesr_el2) },
6077 };
6078 
6079 /* Return the exception level to which exceptions should be taken
6080  * via SVEAccessTrap.  If an exception should be routed through
6081  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6082  * take care of raising that exception.
6083  * C.f. the ARM pseudocode function CheckSVEEnabled.
6084  */
6085 int sve_exception_el(CPUARMState *env, int el)
6086 {
6087 #ifndef CONFIG_USER_ONLY
6088     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6089 
6090     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6091         /* Check CPACR.ZEN.  */
6092         switch (extract32(env->cp15.cpacr_el1, 16, 2)) {
6093         case 1:
6094             if (el != 0) {
6095                 break;
6096             }
6097             /* fall through */
6098         case 0:
6099         case 2:
6100             /* route_to_el2 */
6101             return hcr_el2 & HCR_TGE ? 2 : 1;
6102         }
6103 
6104         /* Check CPACR.FPEN.  */
6105         switch (extract32(env->cp15.cpacr_el1, 20, 2)) {
6106         case 1:
6107             if (el != 0) {
6108                 break;
6109             }
6110             /* fall through */
6111         case 0:
6112         case 2:
6113             return 0;
6114         }
6115     }
6116 
6117     /*
6118      * CPTR_EL2 changes format with HCR_EL2.E2H (regardless of TGE).
6119      */
6120     if (el <= 2) {
6121         if (hcr_el2 & HCR_E2H) {
6122             /* Check CPTR_EL2.ZEN.  */
6123             switch (extract32(env->cp15.cptr_el[2], 16, 2)) {
6124             case 1:
6125                 if (el != 0 || !(hcr_el2 & HCR_TGE)) {
6126                     break;
6127                 }
6128                 /* fall through */
6129             case 0:
6130             case 2:
6131                 return 2;
6132             }
6133 
6134             /* Check CPTR_EL2.FPEN.  */
6135             switch (extract32(env->cp15.cptr_el[2], 20, 2)) {
6136             case 1:
6137                 if (el == 2 || !(hcr_el2 & HCR_TGE)) {
6138                     break;
6139                 }
6140                 /* fall through */
6141             case 0:
6142             case 2:
6143                 return 0;
6144             }
6145         } else if (arm_is_el2_enabled(env)) {
6146             if (env->cp15.cptr_el[2] & CPTR_TZ) {
6147                 return 2;
6148             }
6149             if (env->cp15.cptr_el[2] & CPTR_TFP) {
6150                 return 0;
6151             }
6152         }
6153     }
6154 
6155     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6156     if (arm_feature(env, ARM_FEATURE_EL3)
6157         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6158         return 3;
6159     }
6160 #endif
6161     return 0;
6162 }
6163 
6164 uint32_t aarch64_sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6165 {
6166     uint32_t end_len;
6167 
6168     start_len = MIN(start_len, ARM_MAX_VQ - 1);
6169     end_len = start_len;
6170 
6171     if (!test_bit(start_len, cpu->sve_vq_map)) {
6172         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6173         assert(end_len < start_len);
6174     }
6175     return end_len;
6176 }
6177 
6178 /*
6179  * Given that SVE is enabled, return the vector length for EL.
6180  */
6181 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6182 {
6183     ARMCPU *cpu = env_archcpu(env);
6184     uint32_t zcr_len = cpu->sve_max_vq - 1;
6185 
6186     if (el <= 1 &&
6187         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6188         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6189     }
6190     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6191         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6192     }
6193     if (arm_feature(env, ARM_FEATURE_EL3)) {
6194         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6195     }
6196 
6197     return aarch64_sve_zcr_get_valid_len(cpu, zcr_len);
6198 }
6199 
6200 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6201                       uint64_t value)
6202 {
6203     int cur_el = arm_current_el(env);
6204     int old_len = sve_zcr_len_for_el(env, cur_el);
6205     int new_len;
6206 
6207     /* Bits other than [3:0] are RAZ/WI.  */
6208     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6209     raw_write(env, ri, value & 0xf);
6210 
6211     /*
6212      * Because we arrived here, we know both FP and SVE are enabled;
6213      * otherwise we would have trapped access to the ZCR_ELn register.
6214      */
6215     new_len = sve_zcr_len_for_el(env, cur_el);
6216     if (new_len < old_len) {
6217         aarch64_sve_narrow_vq(env, new_len + 1);
6218     }
6219 }
6220 
6221 static const ARMCPRegInfo zcr_reginfo[] = {
6222     { .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6223       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6224       .access = PL1_RW, .type = ARM_CP_SVE,
6225       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6226       .writefn = zcr_write, .raw_writefn = raw_write },
6227     { .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6228       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6229       .access = PL2_RW, .type = ARM_CP_SVE,
6230       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6231       .writefn = zcr_write, .raw_writefn = raw_write },
6232     { .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6233       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6234       .access = PL3_RW, .type = ARM_CP_SVE,
6235       .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6236       .writefn = zcr_write, .raw_writefn = raw_write },
6237 };
6238 
6239 void hw_watchpoint_update(ARMCPU *cpu, int n)
6240 {
6241     CPUARMState *env = &cpu->env;
6242     vaddr len = 0;
6243     vaddr wvr = env->cp15.dbgwvr[n];
6244     uint64_t wcr = env->cp15.dbgwcr[n];
6245     int mask;
6246     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6247 
6248     if (env->cpu_watchpoint[n]) {
6249         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6250         env->cpu_watchpoint[n] = NULL;
6251     }
6252 
6253     if (!FIELD_EX64(wcr, DBGWCR, E)) {
6254         /* E bit clear : watchpoint disabled */
6255         return;
6256     }
6257 
6258     switch (FIELD_EX64(wcr, DBGWCR, LSC)) {
6259     case 0:
6260         /* LSC 00 is reserved and must behave as if the wp is disabled */
6261         return;
6262     case 1:
6263         flags |= BP_MEM_READ;
6264         break;
6265     case 2:
6266         flags |= BP_MEM_WRITE;
6267         break;
6268     case 3:
6269         flags |= BP_MEM_ACCESS;
6270         break;
6271     }
6272 
6273     /* Attempts to use both MASK and BAS fields simultaneously are
6274      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6275      * thus generating a watchpoint for every byte in the masked region.
6276      */
6277     mask = FIELD_EX64(wcr, DBGWCR, MASK);
6278     if (mask == 1 || mask == 2) {
6279         /* Reserved values of MASK; we must act as if the mask value was
6280          * some non-reserved value, or as if the watchpoint were disabled.
6281          * We choose the latter.
6282          */
6283         return;
6284     } else if (mask) {
6285         /* Watchpoint covers an aligned area up to 2GB in size */
6286         len = 1ULL << mask;
6287         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6288          * whether the watchpoint fires when the unmasked bits match; we opt
6289          * to generate the exceptions.
6290          */
6291         wvr &= ~(len - 1);
6292     } else {
6293         /* Watchpoint covers bytes defined by the byte address select bits */
6294         int bas = FIELD_EX64(wcr, DBGWCR, BAS);
6295         int basstart;
6296 
6297         if (extract64(wvr, 2, 1)) {
6298             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6299              * ignored, and BAS[3:0] define which bytes to watch.
6300              */
6301             bas &= 0xf;
6302         }
6303 
6304         if (bas == 0) {
6305             /* This must act as if the watchpoint is disabled */
6306             return;
6307         }
6308 
6309         /* The BAS bits are supposed to be programmed to indicate a contiguous
6310          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6311          * we fire for each byte in the word/doubleword addressed by the WVR.
6312          * We choose to ignore any non-zero bits after the first range of 1s.
6313          */
6314         basstart = ctz32(bas);
6315         len = cto32(bas >> basstart);
6316         wvr += basstart;
6317     }
6318 
6319     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6320                           &env->cpu_watchpoint[n]);
6321 }
6322 
6323 void hw_watchpoint_update_all(ARMCPU *cpu)
6324 {
6325     int i;
6326     CPUARMState *env = &cpu->env;
6327 
6328     /* Completely clear out existing QEMU watchpoints and our array, to
6329      * avoid possible stale entries following migration load.
6330      */
6331     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6332     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6333 
6334     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6335         hw_watchpoint_update(cpu, i);
6336     }
6337 }
6338 
6339 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6340                          uint64_t value)
6341 {
6342     ARMCPU *cpu = env_archcpu(env);
6343     int i = ri->crm;
6344 
6345     /*
6346      * Bits [1:0] are RES0.
6347      *
6348      * It is IMPLEMENTATION DEFINED whether [63:49] ([63:53] with FEAT_LVA)
6349      * are hardwired to the value of bit [48] ([52] with FEAT_LVA), or if
6350      * they contain the value written.  It is CONSTRAINED UNPREDICTABLE
6351      * whether the RESS bits are ignored when comparing an address.
6352      *
6353      * Therefore we are allowed to compare the entire register, which lets
6354      * us avoid considering whether or not FEAT_LVA is actually enabled.
6355      */
6356     value &= ~3ULL;
6357 
6358     raw_write(env, ri, value);
6359     hw_watchpoint_update(cpu, i);
6360 }
6361 
6362 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6363                          uint64_t value)
6364 {
6365     ARMCPU *cpu = env_archcpu(env);
6366     int i = ri->crm;
6367 
6368     raw_write(env, ri, value);
6369     hw_watchpoint_update(cpu, i);
6370 }
6371 
6372 void hw_breakpoint_update(ARMCPU *cpu, int n)
6373 {
6374     CPUARMState *env = &cpu->env;
6375     uint64_t bvr = env->cp15.dbgbvr[n];
6376     uint64_t bcr = env->cp15.dbgbcr[n];
6377     vaddr addr;
6378     int bt;
6379     int flags = BP_CPU;
6380 
6381     if (env->cpu_breakpoint[n]) {
6382         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6383         env->cpu_breakpoint[n] = NULL;
6384     }
6385 
6386     if (!extract64(bcr, 0, 1)) {
6387         /* E bit clear : watchpoint disabled */
6388         return;
6389     }
6390 
6391     bt = extract64(bcr, 20, 4);
6392 
6393     switch (bt) {
6394     case 4: /* unlinked address mismatch (reserved if AArch64) */
6395     case 5: /* linked address mismatch (reserved if AArch64) */
6396         qemu_log_mask(LOG_UNIMP,
6397                       "arm: address mismatch breakpoint types not implemented\n");
6398         return;
6399     case 0: /* unlinked address match */
6400     case 1: /* linked address match */
6401     {
6402         /*
6403          * Bits [1:0] are RES0.
6404          *
6405          * It is IMPLEMENTATION DEFINED whether bits [63:49]
6406          * ([63:53] for FEAT_LVA) are hardwired to a copy of the sign bit
6407          * of the VA field ([48] or [52] for FEAT_LVA), or whether the
6408          * value is read as written.  It is CONSTRAINED UNPREDICTABLE
6409          * whether the RESS bits are ignored when comparing an address.
6410          * Therefore we are allowed to compare the entire register, which
6411          * lets us avoid considering whether FEAT_LVA is actually enabled.
6412          *
6413          * The BAS field is used to allow setting breakpoints on 16-bit
6414          * wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6415          * a bp will fire if the addresses covered by the bp and the addresses
6416          * covered by the insn overlap but the insn doesn't start at the
6417          * start of the bp address range. We choose to require the insn and
6418          * the bp to have the same address. The constraints on writing to
6419          * BAS enforced in dbgbcr_write mean we have only four cases:
6420          *  0b0000  => no breakpoint
6421          *  0b0011  => breakpoint on addr
6422          *  0b1100  => breakpoint on addr + 2
6423          *  0b1111  => breakpoint on addr
6424          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6425          */
6426         int bas = extract64(bcr, 5, 4);
6427         addr = bvr & ~3ULL;
6428         if (bas == 0) {
6429             return;
6430         }
6431         if (bas == 0xc) {
6432             addr += 2;
6433         }
6434         break;
6435     }
6436     case 2: /* unlinked context ID match */
6437     case 8: /* unlinked VMID match (reserved if no EL2) */
6438     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6439         qemu_log_mask(LOG_UNIMP,
6440                       "arm: unlinked context breakpoint types not implemented\n");
6441         return;
6442     case 9: /* linked VMID match (reserved if no EL2) */
6443     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6444     case 3: /* linked context ID match */
6445     default:
6446         /* We must generate no events for Linked context matches (unless
6447          * they are linked to by some other bp/wp, which is handled in
6448          * updates for the linking bp/wp). We choose to also generate no events
6449          * for reserved values.
6450          */
6451         return;
6452     }
6453 
6454     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6455 }
6456 
6457 void hw_breakpoint_update_all(ARMCPU *cpu)
6458 {
6459     int i;
6460     CPUARMState *env = &cpu->env;
6461 
6462     /* Completely clear out existing QEMU breakpoints and our array, to
6463      * avoid possible stale entries following migration load.
6464      */
6465     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6466     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6467 
6468     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6469         hw_breakpoint_update(cpu, i);
6470     }
6471 }
6472 
6473 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6474                          uint64_t value)
6475 {
6476     ARMCPU *cpu = env_archcpu(env);
6477     int i = ri->crm;
6478 
6479     raw_write(env, ri, value);
6480     hw_breakpoint_update(cpu, i);
6481 }
6482 
6483 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6484                          uint64_t value)
6485 {
6486     ARMCPU *cpu = env_archcpu(env);
6487     int i = ri->crm;
6488 
6489     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6490      * copy of BAS[0].
6491      */
6492     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6493     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6494 
6495     raw_write(env, ri, value);
6496     hw_breakpoint_update(cpu, i);
6497 }
6498 
6499 static void define_debug_regs(ARMCPU *cpu)
6500 {
6501     /* Define v7 and v8 architectural debug registers.
6502      * These are just dummy implementations for now.
6503      */
6504     int i;
6505     int wrps, brps, ctx_cmps;
6506 
6507     /*
6508      * The Arm ARM says DBGDIDR is optional and deprecated if EL1 cannot
6509      * use AArch32.  Given that bit 15 is RES1, if the value is 0 then
6510      * the register must not exist for this cpu.
6511      */
6512     if (cpu->isar.dbgdidr != 0) {
6513         ARMCPRegInfo dbgdidr = {
6514             .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0,
6515             .opc1 = 0, .opc2 = 0,
6516             .access = PL0_R, .accessfn = access_tda,
6517             .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6518         };
6519         define_one_arm_cp_reg(cpu, &dbgdidr);
6520     }
6521 
6522     /* Note that all these register fields hold "number of Xs minus 1". */
6523     brps = arm_num_brps(cpu);
6524     wrps = arm_num_wrps(cpu);
6525     ctx_cmps = arm_num_ctx_cmps(cpu);
6526 
6527     assert(ctx_cmps <= brps);
6528 
6529     define_arm_cp_regs(cpu, debug_cp_reginfo);
6530 
6531     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6532         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6533     }
6534 
6535     for (i = 0; i < brps; i++) {
6536         ARMCPRegInfo dbgregs[] = {
6537             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6538               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6539               .access = PL1_RW, .accessfn = access_tda,
6540               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6541               .writefn = dbgbvr_write, .raw_writefn = raw_write
6542             },
6543             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6544               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6545               .access = PL1_RW, .accessfn = access_tda,
6546               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6547               .writefn = dbgbcr_write, .raw_writefn = raw_write
6548             },
6549         };
6550         define_arm_cp_regs(cpu, dbgregs);
6551     }
6552 
6553     for (i = 0; i < wrps; i++) {
6554         ARMCPRegInfo dbgregs[] = {
6555             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6556               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6557               .access = PL1_RW, .accessfn = access_tda,
6558               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6559               .writefn = dbgwvr_write, .raw_writefn = raw_write
6560             },
6561             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6562               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6563               .access = PL1_RW, .accessfn = access_tda,
6564               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6565               .writefn = dbgwcr_write, .raw_writefn = raw_write
6566             },
6567         };
6568         define_arm_cp_regs(cpu, dbgregs);
6569     }
6570 }
6571 
6572 static void define_pmu_regs(ARMCPU *cpu)
6573 {
6574     /*
6575      * v7 performance monitor control register: same implementor
6576      * field as main ID register, and we implement four counters in
6577      * addition to the cycle count register.
6578      */
6579     unsigned int i, pmcrn = PMCR_NUM_COUNTERS;
6580     ARMCPRegInfo pmcr = {
6581         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6582         .access = PL0_RW,
6583         .type = ARM_CP_IO | ARM_CP_ALIAS,
6584         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6585         .accessfn = pmreg_access, .writefn = pmcr_write,
6586         .raw_writefn = raw_write,
6587     };
6588     ARMCPRegInfo pmcr64 = {
6589         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6590         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6591         .access = PL0_RW, .accessfn = pmreg_access,
6592         .type = ARM_CP_IO,
6593         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6594         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6595                       PMCRLC,
6596         .writefn = pmcr_write, .raw_writefn = raw_write,
6597     };
6598     define_one_arm_cp_reg(cpu, &pmcr);
6599     define_one_arm_cp_reg(cpu, &pmcr64);
6600     for (i = 0; i < pmcrn; i++) {
6601         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6602         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6603         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6604         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6605         ARMCPRegInfo pmev_regs[] = {
6606             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6607               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6608               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6609               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6610               .accessfn = pmreg_access_xevcntr },
6611             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6612               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6613               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access_xevcntr,
6614               .type = ARM_CP_IO,
6615               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6616               .raw_readfn = pmevcntr_rawread,
6617               .raw_writefn = pmevcntr_rawwrite },
6618             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6619               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6620               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6621               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6622               .accessfn = pmreg_access },
6623             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6624               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6625               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6626               .type = ARM_CP_IO,
6627               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6628               .raw_writefn = pmevtyper_rawwrite },
6629         };
6630         define_arm_cp_regs(cpu, pmev_regs);
6631         g_free(pmevcntr_name);
6632         g_free(pmevcntr_el0_name);
6633         g_free(pmevtyper_name);
6634         g_free(pmevtyper_el0_name);
6635     }
6636     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6637         ARMCPRegInfo v81_pmu_regs[] = {
6638             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6639               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6640               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6641               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6642             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6643               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6644               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6645               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6646         };
6647         define_arm_cp_regs(cpu, v81_pmu_regs);
6648     }
6649     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6650         static const ARMCPRegInfo v84_pmmir = {
6651             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6652             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6653             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6654             .resetvalue = 0
6655         };
6656         define_one_arm_cp_reg(cpu, &v84_pmmir);
6657     }
6658 }
6659 
6660 /* We don't know until after realize whether there's a GICv3
6661  * attached, and that is what registers the gicv3 sysregs.
6662  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6663  * at runtime.
6664  */
6665 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6666 {
6667     ARMCPU *cpu = env_archcpu(env);
6668     uint64_t pfr1 = cpu->isar.id_pfr1;
6669 
6670     if (env->gicv3state) {
6671         pfr1 |= 1 << 28;
6672     }
6673     return pfr1;
6674 }
6675 
6676 #ifndef CONFIG_USER_ONLY
6677 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6678 {
6679     ARMCPU *cpu = env_archcpu(env);
6680     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6681 
6682     if (env->gicv3state) {
6683         pfr0 |= 1 << 24;
6684     }
6685     return pfr0;
6686 }
6687 #endif
6688 
6689 /* Shared logic between LORID and the rest of the LOR* registers.
6690  * Secure state exclusion has already been dealt with.
6691  */
6692 static CPAccessResult access_lor_ns(CPUARMState *env,
6693                                     const ARMCPRegInfo *ri, bool isread)
6694 {
6695     int el = arm_current_el(env);
6696 
6697     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6698         return CP_ACCESS_TRAP_EL2;
6699     }
6700     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6701         return CP_ACCESS_TRAP_EL3;
6702     }
6703     return CP_ACCESS_OK;
6704 }
6705 
6706 static CPAccessResult access_lor_other(CPUARMState *env,
6707                                        const ARMCPRegInfo *ri, bool isread)
6708 {
6709     if (arm_is_secure_below_el3(env)) {
6710         /* Access denied in secure mode.  */
6711         return CP_ACCESS_TRAP;
6712     }
6713     return access_lor_ns(env, ri, isread);
6714 }
6715 
6716 /*
6717  * A trivial implementation of ARMv8.1-LOR leaves all of these
6718  * registers fixed at 0, which indicates that there are zero
6719  * supported Limited Ordering regions.
6720  */
6721 static const ARMCPRegInfo lor_reginfo[] = {
6722     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6723       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6724       .access = PL1_RW, .accessfn = access_lor_other,
6725       .type = ARM_CP_CONST, .resetvalue = 0 },
6726     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6727       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6728       .access = PL1_RW, .accessfn = access_lor_other,
6729       .type = ARM_CP_CONST, .resetvalue = 0 },
6730     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6731       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6732       .access = PL1_RW, .accessfn = access_lor_other,
6733       .type = ARM_CP_CONST, .resetvalue = 0 },
6734     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6735       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6736       .access = PL1_RW, .accessfn = access_lor_other,
6737       .type = ARM_CP_CONST, .resetvalue = 0 },
6738     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6739       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6740       .access = PL1_R, .accessfn = access_lor_ns,
6741       .type = ARM_CP_CONST, .resetvalue = 0 },
6742 };
6743 
6744 #ifdef TARGET_AARCH64
6745 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6746                                    bool isread)
6747 {
6748     int el = arm_current_el(env);
6749 
6750     if (el < 2 &&
6751         arm_feature(env, ARM_FEATURE_EL2) &&
6752         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6753         return CP_ACCESS_TRAP_EL2;
6754     }
6755     if (el < 3 &&
6756         arm_feature(env, ARM_FEATURE_EL3) &&
6757         !(env->cp15.scr_el3 & SCR_APK)) {
6758         return CP_ACCESS_TRAP_EL3;
6759     }
6760     return CP_ACCESS_OK;
6761 }
6762 
6763 static const ARMCPRegInfo pauth_reginfo[] = {
6764     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6765       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6766       .access = PL1_RW, .accessfn = access_pauth,
6767       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6768     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6769       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6770       .access = PL1_RW, .accessfn = access_pauth,
6771       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6772     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6773       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6774       .access = PL1_RW, .accessfn = access_pauth,
6775       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6776     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6777       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6778       .access = PL1_RW, .accessfn = access_pauth,
6779       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6780     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6781       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6782       .access = PL1_RW, .accessfn = access_pauth,
6783       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6784     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6785       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6786       .access = PL1_RW, .accessfn = access_pauth,
6787       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6788     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6789       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6790       .access = PL1_RW, .accessfn = access_pauth,
6791       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6792     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6793       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6794       .access = PL1_RW, .accessfn = access_pauth,
6795       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6796     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6797       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6798       .access = PL1_RW, .accessfn = access_pauth,
6799       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6800     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6801       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6802       .access = PL1_RW, .accessfn = access_pauth,
6803       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6804 };
6805 
6806 static const ARMCPRegInfo tlbirange_reginfo[] = {
6807     { .name = "TLBI_RVAE1IS", .state = ARM_CP_STATE_AA64,
6808       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 1,
6809       .access = PL1_W, .type = ARM_CP_NO_RAW,
6810       .writefn = tlbi_aa64_rvae1is_write },
6811     { .name = "TLBI_RVAAE1IS", .state = ARM_CP_STATE_AA64,
6812       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 3,
6813       .access = PL1_W, .type = ARM_CP_NO_RAW,
6814       .writefn = tlbi_aa64_rvae1is_write },
6815    { .name = "TLBI_RVALE1IS", .state = ARM_CP_STATE_AA64,
6816       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 5,
6817       .access = PL1_W, .type = ARM_CP_NO_RAW,
6818       .writefn = tlbi_aa64_rvae1is_write },
6819     { .name = "TLBI_RVAALE1IS", .state = ARM_CP_STATE_AA64,
6820       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 7,
6821       .access = PL1_W, .type = ARM_CP_NO_RAW,
6822       .writefn = tlbi_aa64_rvae1is_write },
6823     { .name = "TLBI_RVAE1OS", .state = ARM_CP_STATE_AA64,
6824       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
6825       .access = PL1_W, .type = ARM_CP_NO_RAW,
6826       .writefn = tlbi_aa64_rvae1is_write },
6827     { .name = "TLBI_RVAAE1OS", .state = ARM_CP_STATE_AA64,
6828       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 3,
6829       .access = PL1_W, .type = ARM_CP_NO_RAW,
6830       .writefn = tlbi_aa64_rvae1is_write },
6831    { .name = "TLBI_RVALE1OS", .state = ARM_CP_STATE_AA64,
6832       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 5,
6833       .access = PL1_W, .type = ARM_CP_NO_RAW,
6834       .writefn = tlbi_aa64_rvae1is_write },
6835     { .name = "TLBI_RVAALE1OS", .state = ARM_CP_STATE_AA64,
6836       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 7,
6837       .access = PL1_W, .type = ARM_CP_NO_RAW,
6838       .writefn = tlbi_aa64_rvae1is_write },
6839     { .name = "TLBI_RVAE1", .state = ARM_CP_STATE_AA64,
6840       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
6841       .access = PL1_W, .type = ARM_CP_NO_RAW,
6842       .writefn = tlbi_aa64_rvae1_write },
6843     { .name = "TLBI_RVAAE1", .state = ARM_CP_STATE_AA64,
6844       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 3,
6845       .access = PL1_W, .type = ARM_CP_NO_RAW,
6846       .writefn = tlbi_aa64_rvae1_write },
6847    { .name = "TLBI_RVALE1", .state = ARM_CP_STATE_AA64,
6848       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 5,
6849       .access = PL1_W, .type = ARM_CP_NO_RAW,
6850       .writefn = tlbi_aa64_rvae1_write },
6851     { .name = "TLBI_RVAALE1", .state = ARM_CP_STATE_AA64,
6852       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 7,
6853       .access = PL1_W, .type = ARM_CP_NO_RAW,
6854       .writefn = tlbi_aa64_rvae1_write },
6855     { .name = "TLBI_RIPAS2E1IS", .state = ARM_CP_STATE_AA64,
6856       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 2,
6857       .access = PL2_W, .type = ARM_CP_NOP },
6858     { .name = "TLBI_RIPAS2LE1IS", .state = ARM_CP_STATE_AA64,
6859       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 6,
6860       .access = PL2_W, .type = ARM_CP_NOP },
6861     { .name = "TLBI_RVAE2IS", .state = ARM_CP_STATE_AA64,
6862       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 1,
6863       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6864       .writefn = tlbi_aa64_rvae2is_write },
6865    { .name = "TLBI_RVALE2IS", .state = ARM_CP_STATE_AA64,
6866       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 5,
6867       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6868       .writefn = tlbi_aa64_rvae2is_write },
6869     { .name = "TLBI_RIPAS2E1", .state = ARM_CP_STATE_AA64,
6870       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 2,
6871       .access = PL2_W, .type = ARM_CP_NOP },
6872    { .name = "TLBI_RIPAS2LE1", .state = ARM_CP_STATE_AA64,
6873       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 6,
6874       .access = PL2_W, .type = ARM_CP_NOP },
6875    { .name = "TLBI_RVAE2OS", .state = ARM_CP_STATE_AA64,
6876       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 1,
6877       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6878       .writefn = tlbi_aa64_rvae2is_write },
6879    { .name = "TLBI_RVALE2OS", .state = ARM_CP_STATE_AA64,
6880       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 5,
6881       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6882       .writefn = tlbi_aa64_rvae2is_write },
6883     { .name = "TLBI_RVAE2", .state = ARM_CP_STATE_AA64,
6884       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 1,
6885       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6886       .writefn = tlbi_aa64_rvae2_write },
6887    { .name = "TLBI_RVALE2", .state = ARM_CP_STATE_AA64,
6888       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 5,
6889       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6890       .writefn = tlbi_aa64_rvae2_write },
6891    { .name = "TLBI_RVAE3IS", .state = ARM_CP_STATE_AA64,
6892       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 1,
6893       .access = PL3_W, .type = ARM_CP_NO_RAW,
6894       .writefn = tlbi_aa64_rvae3is_write },
6895    { .name = "TLBI_RVALE3IS", .state = ARM_CP_STATE_AA64,
6896       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 5,
6897       .access = PL3_W, .type = ARM_CP_NO_RAW,
6898       .writefn = tlbi_aa64_rvae3is_write },
6899    { .name = "TLBI_RVAE3OS", .state = ARM_CP_STATE_AA64,
6900       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 1,
6901       .access = PL3_W, .type = ARM_CP_NO_RAW,
6902       .writefn = tlbi_aa64_rvae3is_write },
6903    { .name = "TLBI_RVALE3OS", .state = ARM_CP_STATE_AA64,
6904       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 5,
6905       .access = PL3_W, .type = ARM_CP_NO_RAW,
6906       .writefn = tlbi_aa64_rvae3is_write },
6907    { .name = "TLBI_RVAE3", .state = ARM_CP_STATE_AA64,
6908       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 1,
6909       .access = PL3_W, .type = ARM_CP_NO_RAW,
6910       .writefn = tlbi_aa64_rvae3_write },
6911    { .name = "TLBI_RVALE3", .state = ARM_CP_STATE_AA64,
6912       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 5,
6913       .access = PL3_W, .type = ARM_CP_NO_RAW,
6914       .writefn = tlbi_aa64_rvae3_write },
6915 };
6916 
6917 static const ARMCPRegInfo tlbios_reginfo[] = {
6918     { .name = "TLBI_VMALLE1OS", .state = ARM_CP_STATE_AA64,
6919       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 0,
6920       .access = PL1_W, .type = ARM_CP_NO_RAW,
6921       .writefn = tlbi_aa64_vmalle1is_write },
6922     { .name = "TLBI_VAE1OS", .state = ARM_CP_STATE_AA64,
6923       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 1,
6924       .access = PL1_W, .type = ARM_CP_NO_RAW,
6925       .writefn = tlbi_aa64_vae1is_write },
6926     { .name = "TLBI_ASIDE1OS", .state = ARM_CP_STATE_AA64,
6927       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 2,
6928       .access = PL1_W, .type = ARM_CP_NO_RAW,
6929       .writefn = tlbi_aa64_vmalle1is_write },
6930     { .name = "TLBI_VAAE1OS", .state = ARM_CP_STATE_AA64,
6931       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 3,
6932       .access = PL1_W, .type = ARM_CP_NO_RAW,
6933       .writefn = tlbi_aa64_vae1is_write },
6934     { .name = "TLBI_VALE1OS", .state = ARM_CP_STATE_AA64,
6935       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 5,
6936       .access = PL1_W, .type = ARM_CP_NO_RAW,
6937       .writefn = tlbi_aa64_vae1is_write },
6938     { .name = "TLBI_VAALE1OS", .state = ARM_CP_STATE_AA64,
6939       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 7,
6940       .access = PL1_W, .type = ARM_CP_NO_RAW,
6941       .writefn = tlbi_aa64_vae1is_write },
6942     { .name = "TLBI_ALLE2OS", .state = ARM_CP_STATE_AA64,
6943       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 0,
6944       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6945       .writefn = tlbi_aa64_alle2is_write },
6946     { .name = "TLBI_VAE2OS", .state = ARM_CP_STATE_AA64,
6947       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 1,
6948       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6949       .writefn = tlbi_aa64_vae2is_write },
6950    { .name = "TLBI_ALLE1OS", .state = ARM_CP_STATE_AA64,
6951       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 4,
6952       .access = PL2_W, .type = ARM_CP_NO_RAW,
6953       .writefn = tlbi_aa64_alle1is_write },
6954     { .name = "TLBI_VALE2OS", .state = ARM_CP_STATE_AA64,
6955       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 5,
6956       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_EL3_NO_EL2_UNDEF,
6957       .writefn = tlbi_aa64_vae2is_write },
6958     { .name = "TLBI_VMALLS12E1OS", .state = ARM_CP_STATE_AA64,
6959       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 6,
6960       .access = PL2_W, .type = ARM_CP_NO_RAW,
6961       .writefn = tlbi_aa64_alle1is_write },
6962     { .name = "TLBI_IPAS2E1OS", .state = ARM_CP_STATE_AA64,
6963       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 0,
6964       .access = PL2_W, .type = ARM_CP_NOP },
6965     { .name = "TLBI_RIPAS2E1OS", .state = ARM_CP_STATE_AA64,
6966       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 3,
6967       .access = PL2_W, .type = ARM_CP_NOP },
6968     { .name = "TLBI_IPAS2LE1OS", .state = ARM_CP_STATE_AA64,
6969       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 4,
6970       .access = PL2_W, .type = ARM_CP_NOP },
6971     { .name = "TLBI_RIPAS2LE1OS", .state = ARM_CP_STATE_AA64,
6972       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 7,
6973       .access = PL2_W, .type = ARM_CP_NOP },
6974     { .name = "TLBI_ALLE3OS", .state = ARM_CP_STATE_AA64,
6975       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 0,
6976       .access = PL3_W, .type = ARM_CP_NO_RAW,
6977       .writefn = tlbi_aa64_alle3is_write },
6978     { .name = "TLBI_VAE3OS", .state = ARM_CP_STATE_AA64,
6979       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 1,
6980       .access = PL3_W, .type = ARM_CP_NO_RAW,
6981       .writefn = tlbi_aa64_vae3is_write },
6982     { .name = "TLBI_VALE3OS", .state = ARM_CP_STATE_AA64,
6983       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 5,
6984       .access = PL3_W, .type = ARM_CP_NO_RAW,
6985       .writefn = tlbi_aa64_vae3is_write },
6986 };
6987 
6988 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
6989 {
6990     Error *err = NULL;
6991     uint64_t ret;
6992 
6993     /* Success sets NZCV = 0000.  */
6994     env->NF = env->CF = env->VF = 0, env->ZF = 1;
6995 
6996     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
6997         /*
6998          * ??? Failed, for unknown reasons in the crypto subsystem.
6999          * The best we can do is log the reason and return the
7000          * timed-out indication to the guest.  There is no reason
7001          * we know to expect this failure to be transitory, so the
7002          * guest may well hang retrying the operation.
7003          */
7004         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
7005                       ri->name, error_get_pretty(err));
7006         error_free(err);
7007 
7008         env->ZF = 0; /* NZCF = 0100 */
7009         return 0;
7010     }
7011     return ret;
7012 }
7013 
7014 /* We do not support re-seeding, so the two registers operate the same.  */
7015 static const ARMCPRegInfo rndr_reginfo[] = {
7016     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
7017       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7018       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
7019       .access = PL0_R, .readfn = rndr_readfn },
7020     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
7021       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7022       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
7023       .access = PL0_R, .readfn = rndr_readfn },
7024 };
7025 
7026 #ifndef CONFIG_USER_ONLY
7027 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
7028                           uint64_t value)
7029 {
7030     ARMCPU *cpu = env_archcpu(env);
7031     /* CTR_EL0 System register -> DminLine, bits [19:16] */
7032     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
7033     uint64_t vaddr_in = (uint64_t) value;
7034     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
7035     void *haddr;
7036     int mem_idx = cpu_mmu_index(env, false);
7037 
7038     /* This won't be crossing page boundaries */
7039     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
7040     if (haddr) {
7041 
7042         ram_addr_t offset;
7043         MemoryRegion *mr;
7044 
7045         /* RCU lock is already being held */
7046         mr = memory_region_from_host(haddr, &offset);
7047 
7048         if (mr) {
7049             memory_region_writeback(mr, offset, dline_size);
7050         }
7051     }
7052 }
7053 
7054 static const ARMCPRegInfo dcpop_reg[] = {
7055     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
7056       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
7057       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7058       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7059 };
7060 
7061 static const ARMCPRegInfo dcpodp_reg[] = {
7062     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
7063       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
7064       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7065       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7066 };
7067 #endif /*CONFIG_USER_ONLY*/
7068 
7069 static CPAccessResult access_aa64_tid5(CPUARMState *env, const ARMCPRegInfo *ri,
7070                                        bool isread)
7071 {
7072     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID5)) {
7073         return CP_ACCESS_TRAP_EL2;
7074     }
7075 
7076     return CP_ACCESS_OK;
7077 }
7078 
7079 static CPAccessResult access_mte(CPUARMState *env, const ARMCPRegInfo *ri,
7080                                  bool isread)
7081 {
7082     int el = arm_current_el(env);
7083 
7084     if (el < 2 && arm_is_el2_enabled(env)) {
7085         uint64_t hcr = arm_hcr_el2_eff(env);
7086         if (!(hcr & HCR_ATA) && (!(hcr & HCR_E2H) || !(hcr & HCR_TGE))) {
7087             return CP_ACCESS_TRAP_EL2;
7088         }
7089     }
7090     if (el < 3 &&
7091         arm_feature(env, ARM_FEATURE_EL3) &&
7092         !(env->cp15.scr_el3 & SCR_ATA)) {
7093         return CP_ACCESS_TRAP_EL3;
7094     }
7095     return CP_ACCESS_OK;
7096 }
7097 
7098 static uint64_t tco_read(CPUARMState *env, const ARMCPRegInfo *ri)
7099 {
7100     return env->pstate & PSTATE_TCO;
7101 }
7102 
7103 static void tco_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
7104 {
7105     env->pstate = (env->pstate & ~PSTATE_TCO) | (val & PSTATE_TCO);
7106 }
7107 
7108 static const ARMCPRegInfo mte_reginfo[] = {
7109     { .name = "TFSRE0_EL1", .state = ARM_CP_STATE_AA64,
7110       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 1,
7111       .access = PL1_RW, .accessfn = access_mte,
7112       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[0]) },
7113     { .name = "TFSR_EL1", .state = ARM_CP_STATE_AA64,
7114       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 0,
7115       .access = PL1_RW, .accessfn = access_mte,
7116       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[1]) },
7117     { .name = "TFSR_EL2", .state = ARM_CP_STATE_AA64,
7118       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 6, .opc2 = 0,
7119       .access = PL2_RW, .accessfn = access_mte,
7120       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[2]) },
7121     { .name = "TFSR_EL3", .state = ARM_CP_STATE_AA64,
7122       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 6, .opc2 = 0,
7123       .access = PL3_RW,
7124       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[3]) },
7125     { .name = "RGSR_EL1", .state = ARM_CP_STATE_AA64,
7126       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 5,
7127       .access = PL1_RW, .accessfn = access_mte,
7128       .fieldoffset = offsetof(CPUARMState, cp15.rgsr_el1) },
7129     { .name = "GCR_EL1", .state = ARM_CP_STATE_AA64,
7130       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 6,
7131       .access = PL1_RW, .accessfn = access_mte,
7132       .fieldoffset = offsetof(CPUARMState, cp15.gcr_el1) },
7133     { .name = "GMID_EL1", .state = ARM_CP_STATE_AA64,
7134       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 4,
7135       .access = PL1_R, .accessfn = access_aa64_tid5,
7136       .type = ARM_CP_CONST, .resetvalue = GMID_EL1_BS },
7137     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7138       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7139       .type = ARM_CP_NO_RAW,
7140       .access = PL0_RW, .readfn = tco_read, .writefn = tco_write },
7141     { .name = "DC_IGVAC", .state = ARM_CP_STATE_AA64,
7142       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 3,
7143       .type = ARM_CP_NOP, .access = PL1_W,
7144       .accessfn = aa64_cacheop_poc_access },
7145     { .name = "DC_IGSW", .state = ARM_CP_STATE_AA64,
7146       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 4,
7147       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7148     { .name = "DC_IGDVAC", .state = ARM_CP_STATE_AA64,
7149       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 5,
7150       .type = ARM_CP_NOP, .access = PL1_W,
7151       .accessfn = aa64_cacheop_poc_access },
7152     { .name = "DC_IGDSW", .state = ARM_CP_STATE_AA64,
7153       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 6,
7154       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7155     { .name = "DC_CGSW", .state = ARM_CP_STATE_AA64,
7156       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 4,
7157       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7158     { .name = "DC_CGDSW", .state = ARM_CP_STATE_AA64,
7159       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 6,
7160       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7161     { .name = "DC_CIGSW", .state = ARM_CP_STATE_AA64,
7162       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 4,
7163       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7164     { .name = "DC_CIGDSW", .state = ARM_CP_STATE_AA64,
7165       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 6,
7166       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7167 };
7168 
7169 static const ARMCPRegInfo mte_tco_ro_reginfo[] = {
7170     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7171       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7172       .type = ARM_CP_CONST, .access = PL0_RW, },
7173 };
7174 
7175 static const ARMCPRegInfo mte_el0_cacheop_reginfo[] = {
7176     { .name = "DC_CGVAC", .state = ARM_CP_STATE_AA64,
7177       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 3,
7178       .type = ARM_CP_NOP, .access = PL0_W,
7179       .accessfn = aa64_cacheop_poc_access },
7180     { .name = "DC_CGDVAC", .state = ARM_CP_STATE_AA64,
7181       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 5,
7182       .type = ARM_CP_NOP, .access = PL0_W,
7183       .accessfn = aa64_cacheop_poc_access },
7184     { .name = "DC_CGVAP", .state = ARM_CP_STATE_AA64,
7185       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 3,
7186       .type = ARM_CP_NOP, .access = PL0_W,
7187       .accessfn = aa64_cacheop_poc_access },
7188     { .name = "DC_CGDVAP", .state = ARM_CP_STATE_AA64,
7189       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 5,
7190       .type = ARM_CP_NOP, .access = PL0_W,
7191       .accessfn = aa64_cacheop_poc_access },
7192     { .name = "DC_CGVADP", .state = ARM_CP_STATE_AA64,
7193       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 3,
7194       .type = ARM_CP_NOP, .access = PL0_W,
7195       .accessfn = aa64_cacheop_poc_access },
7196     { .name = "DC_CGDVADP", .state = ARM_CP_STATE_AA64,
7197       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 5,
7198       .type = ARM_CP_NOP, .access = PL0_W,
7199       .accessfn = aa64_cacheop_poc_access },
7200     { .name = "DC_CIGVAC", .state = ARM_CP_STATE_AA64,
7201       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 3,
7202       .type = ARM_CP_NOP, .access = PL0_W,
7203       .accessfn = aa64_cacheop_poc_access },
7204     { .name = "DC_CIGDVAC", .state = ARM_CP_STATE_AA64,
7205       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 5,
7206       .type = ARM_CP_NOP, .access = PL0_W,
7207       .accessfn = aa64_cacheop_poc_access },
7208     { .name = "DC_GVA", .state = ARM_CP_STATE_AA64,
7209       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 3,
7210       .access = PL0_W, .type = ARM_CP_DC_GVA,
7211 #ifndef CONFIG_USER_ONLY
7212       /* Avoid overhead of an access check that always passes in user-mode */
7213       .accessfn = aa64_zva_access,
7214 #endif
7215     },
7216     { .name = "DC_GZVA", .state = ARM_CP_STATE_AA64,
7217       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 4,
7218       .access = PL0_W, .type = ARM_CP_DC_GZVA,
7219 #ifndef CONFIG_USER_ONLY
7220       /* Avoid overhead of an access check that always passes in user-mode */
7221       .accessfn = aa64_zva_access,
7222 #endif
7223     },
7224 };
7225 
7226 #endif
7227 
7228 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
7229                                      bool isread)
7230 {
7231     int el = arm_current_el(env);
7232 
7233     if (el == 0) {
7234         uint64_t sctlr = arm_sctlr(env, el);
7235         if (!(sctlr & SCTLR_EnRCTX)) {
7236             return CP_ACCESS_TRAP;
7237         }
7238     } else if (el == 1) {
7239         uint64_t hcr = arm_hcr_el2_eff(env);
7240         if (hcr & HCR_NV) {
7241             return CP_ACCESS_TRAP_EL2;
7242         }
7243     }
7244     return CP_ACCESS_OK;
7245 }
7246 
7247 static const ARMCPRegInfo predinv_reginfo[] = {
7248     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
7249       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
7250       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7251     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
7252       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
7253       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7254     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
7255       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
7256       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7257     /*
7258      * Note the AArch32 opcodes have a different OPC1.
7259      */
7260     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
7261       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
7262       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7263     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
7264       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
7265       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7266     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
7267       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
7268       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7269 };
7270 
7271 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
7272 {
7273     /* Read the high 32 bits of the current CCSIDR */
7274     return extract64(ccsidr_read(env, ri), 32, 32);
7275 }
7276 
7277 static const ARMCPRegInfo ccsidr2_reginfo[] = {
7278     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
7279       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
7280       .access = PL1_R,
7281       .accessfn = access_aa64_tid2,
7282       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7283 };
7284 
7285 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7286                                        bool isread)
7287 {
7288     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7289         return CP_ACCESS_TRAP_EL2;
7290     }
7291 
7292     return CP_ACCESS_OK;
7293 }
7294 
7295 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7296                                        bool isread)
7297 {
7298     if (arm_feature(env, ARM_FEATURE_V8)) {
7299         return access_aa64_tid3(env, ri, isread);
7300     }
7301 
7302     return CP_ACCESS_OK;
7303 }
7304 
7305 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7306                                      bool isread)
7307 {
7308     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7309         return CP_ACCESS_TRAP_EL2;
7310     }
7311 
7312     return CP_ACCESS_OK;
7313 }
7314 
7315 static CPAccessResult access_joscr_jmcr(CPUARMState *env,
7316                                         const ARMCPRegInfo *ri, bool isread)
7317 {
7318     /*
7319      * HSTR.TJDBX traps JOSCR and JMCR accesses, but it exists only
7320      * in v7A, not in v8A.
7321      */
7322     if (!arm_feature(env, ARM_FEATURE_V8) &&
7323         arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
7324         (env->cp15.hstr_el2 & HSTR_TJDBX)) {
7325         return CP_ACCESS_TRAP_EL2;
7326     }
7327     return CP_ACCESS_OK;
7328 }
7329 
7330 static const ARMCPRegInfo jazelle_regs[] = {
7331     { .name = "JIDR",
7332       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7333       .access = PL1_R, .accessfn = access_jazelle,
7334       .type = ARM_CP_CONST, .resetvalue = 0 },
7335     { .name = "JOSCR",
7336       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7337       .accessfn = access_joscr_jmcr,
7338       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7339     { .name = "JMCR",
7340       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7341       .accessfn = access_joscr_jmcr,
7342       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7343 };
7344 
7345 static const ARMCPRegInfo contextidr_el2 = {
7346     .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7347     .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7348     .access = PL2_RW,
7349     .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2])
7350 };
7351 
7352 static const ARMCPRegInfo vhe_reginfo[] = {
7353     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7354       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7355       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7356       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7357 #ifndef CONFIG_USER_ONLY
7358     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7359       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7360       .fieldoffset =
7361         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7362       .type = ARM_CP_IO, .access = PL2_RW,
7363       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7364     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7365       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7366       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7367       .resetfn = gt_hv_timer_reset,
7368       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7369     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7370       .type = ARM_CP_IO,
7371       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7372       .access = PL2_RW,
7373       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7374       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7375     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7376       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7377       .type = ARM_CP_IO | ARM_CP_ALIAS,
7378       .access = PL2_RW, .accessfn = e2h_access,
7379       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7380       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7381     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7382       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7383       .type = ARM_CP_IO | ARM_CP_ALIAS,
7384       .access = PL2_RW, .accessfn = e2h_access,
7385       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7386       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7387     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7388       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7389       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7390       .access = PL2_RW, .accessfn = e2h_access,
7391       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7392     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7393       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7394       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7395       .access = PL2_RW, .accessfn = e2h_access,
7396       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7397     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7398       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7399       .type = ARM_CP_IO | ARM_CP_ALIAS,
7400       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7401       .access = PL2_RW, .accessfn = e2h_access,
7402       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7403     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7404       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7405       .type = ARM_CP_IO | ARM_CP_ALIAS,
7406       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7407       .access = PL2_RW, .accessfn = e2h_access,
7408       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7409 #endif
7410 };
7411 
7412 #ifndef CONFIG_USER_ONLY
7413 static const ARMCPRegInfo ats1e1_reginfo[] = {
7414     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7415       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7416       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7417       .writefn = ats_write64 },
7418     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7419       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7420       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7421       .writefn = ats_write64 },
7422 };
7423 
7424 static const ARMCPRegInfo ats1cp_reginfo[] = {
7425     { .name = "ATS1CPRP",
7426       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7427       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7428       .writefn = ats_write },
7429     { .name = "ATS1CPWP",
7430       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7431       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7432       .writefn = ats_write },
7433 };
7434 #endif
7435 
7436 /*
7437  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7438  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7439  * is non-zero, which is never for ARMv7, optionally in ARMv8
7440  * and mandatorily for ARMv8.2 and up.
7441  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7442  * implementation is RAZ/WI we can ignore this detail, as we
7443  * do for ACTLR.
7444  */
7445 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7446     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7447       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7448       .access = PL1_RW, .accessfn = access_tacr,
7449       .type = ARM_CP_CONST, .resetvalue = 0 },
7450     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7451       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7452       .access = PL2_RW, .type = ARM_CP_CONST,
7453       .resetvalue = 0 },
7454 };
7455 
7456 void register_cp_regs_for_features(ARMCPU *cpu)
7457 {
7458     /* Register all the coprocessor registers based on feature bits */
7459     CPUARMState *env = &cpu->env;
7460     if (arm_feature(env, ARM_FEATURE_M)) {
7461         /* M profile has no coprocessor registers */
7462         return;
7463     }
7464 
7465     define_arm_cp_regs(cpu, cp_reginfo);
7466     if (!arm_feature(env, ARM_FEATURE_V8)) {
7467         /* Must go early as it is full of wildcards that may be
7468          * overridden by later definitions.
7469          */
7470         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7471     }
7472 
7473     if (arm_feature(env, ARM_FEATURE_V6)) {
7474         /* The ID registers all have impdef reset values */
7475         ARMCPRegInfo v6_idregs[] = {
7476             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7477               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7478               .access = PL1_R, .type = ARM_CP_CONST,
7479               .accessfn = access_aa32_tid3,
7480               .resetvalue = cpu->isar.id_pfr0 },
7481             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7482              * the value of the GIC field until after we define these regs.
7483              */
7484             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7485               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7486               .access = PL1_R, .type = ARM_CP_NO_RAW,
7487               .accessfn = access_aa32_tid3,
7488               .readfn = id_pfr1_read,
7489               .writefn = arm_cp_write_ignore },
7490             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7491               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7492               .access = PL1_R, .type = ARM_CP_CONST,
7493               .accessfn = access_aa32_tid3,
7494               .resetvalue = cpu->isar.id_dfr0 },
7495             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7496               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7497               .access = PL1_R, .type = ARM_CP_CONST,
7498               .accessfn = access_aa32_tid3,
7499               .resetvalue = cpu->id_afr0 },
7500             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7501               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7502               .access = PL1_R, .type = ARM_CP_CONST,
7503               .accessfn = access_aa32_tid3,
7504               .resetvalue = cpu->isar.id_mmfr0 },
7505             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7506               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7507               .access = PL1_R, .type = ARM_CP_CONST,
7508               .accessfn = access_aa32_tid3,
7509               .resetvalue = cpu->isar.id_mmfr1 },
7510             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7511               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7512               .access = PL1_R, .type = ARM_CP_CONST,
7513               .accessfn = access_aa32_tid3,
7514               .resetvalue = cpu->isar.id_mmfr2 },
7515             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7516               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7517               .access = PL1_R, .type = ARM_CP_CONST,
7518               .accessfn = access_aa32_tid3,
7519               .resetvalue = cpu->isar.id_mmfr3 },
7520             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7521               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7522               .access = PL1_R, .type = ARM_CP_CONST,
7523               .accessfn = access_aa32_tid3,
7524               .resetvalue = cpu->isar.id_isar0 },
7525             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7526               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7527               .access = PL1_R, .type = ARM_CP_CONST,
7528               .accessfn = access_aa32_tid3,
7529               .resetvalue = cpu->isar.id_isar1 },
7530             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7531               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7532               .access = PL1_R, .type = ARM_CP_CONST,
7533               .accessfn = access_aa32_tid3,
7534               .resetvalue = cpu->isar.id_isar2 },
7535             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7536               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7537               .access = PL1_R, .type = ARM_CP_CONST,
7538               .accessfn = access_aa32_tid3,
7539               .resetvalue = cpu->isar.id_isar3 },
7540             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7541               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7542               .access = PL1_R, .type = ARM_CP_CONST,
7543               .accessfn = access_aa32_tid3,
7544               .resetvalue = cpu->isar.id_isar4 },
7545             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7546               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7547               .access = PL1_R, .type = ARM_CP_CONST,
7548               .accessfn = access_aa32_tid3,
7549               .resetvalue = cpu->isar.id_isar5 },
7550             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7551               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7552               .access = PL1_R, .type = ARM_CP_CONST,
7553               .accessfn = access_aa32_tid3,
7554               .resetvalue = cpu->isar.id_mmfr4 },
7555             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7556               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7557               .access = PL1_R, .type = ARM_CP_CONST,
7558               .accessfn = access_aa32_tid3,
7559               .resetvalue = cpu->isar.id_isar6 },
7560         };
7561         define_arm_cp_regs(cpu, v6_idregs);
7562         define_arm_cp_regs(cpu, v6_cp_reginfo);
7563     } else {
7564         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7565     }
7566     if (arm_feature(env, ARM_FEATURE_V6K)) {
7567         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7568     }
7569     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7570         !arm_feature(env, ARM_FEATURE_PMSA)) {
7571         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7572     }
7573     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7574         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7575     }
7576     if (arm_feature(env, ARM_FEATURE_V7)) {
7577         ARMCPRegInfo clidr = {
7578             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7579             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7580             .access = PL1_R, .type = ARM_CP_CONST,
7581             .accessfn = access_aa64_tid2,
7582             .resetvalue = cpu->clidr
7583         };
7584         define_one_arm_cp_reg(cpu, &clidr);
7585         define_arm_cp_regs(cpu, v7_cp_reginfo);
7586         define_debug_regs(cpu);
7587         define_pmu_regs(cpu);
7588     } else {
7589         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7590     }
7591     if (arm_feature(env, ARM_FEATURE_V8)) {
7592         /* AArch64 ID registers, which all have impdef reset values.
7593          * Note that within the ID register ranges the unused slots
7594          * must all RAZ, not UNDEF; future architecture versions may
7595          * define new registers here.
7596          */
7597         ARMCPRegInfo v8_idregs[] = {
7598             /*
7599              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7600              * emulation because we don't know the right value for the
7601              * GIC field until after we define these regs.
7602              */
7603             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7604               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7605               .access = PL1_R,
7606 #ifdef CONFIG_USER_ONLY
7607               .type = ARM_CP_CONST,
7608               .resetvalue = cpu->isar.id_aa64pfr0
7609 #else
7610               .type = ARM_CP_NO_RAW,
7611               .accessfn = access_aa64_tid3,
7612               .readfn = id_aa64pfr0_read,
7613               .writefn = arm_cp_write_ignore
7614 #endif
7615             },
7616             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7617               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7618               .access = PL1_R, .type = ARM_CP_CONST,
7619               .accessfn = access_aa64_tid3,
7620               .resetvalue = cpu->isar.id_aa64pfr1},
7621             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7622               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7623               .access = PL1_R, .type = ARM_CP_CONST,
7624               .accessfn = access_aa64_tid3,
7625               .resetvalue = 0 },
7626             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7627               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7628               .access = PL1_R, .type = ARM_CP_CONST,
7629               .accessfn = access_aa64_tid3,
7630               .resetvalue = 0 },
7631             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7632               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7633               .access = PL1_R, .type = ARM_CP_CONST,
7634               .accessfn = access_aa64_tid3,
7635               .resetvalue = cpu->isar.id_aa64zfr0 },
7636             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7637               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7638               .access = PL1_R, .type = ARM_CP_CONST,
7639               .accessfn = access_aa64_tid3,
7640               .resetvalue = 0 },
7641             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7642               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7643               .access = PL1_R, .type = ARM_CP_CONST,
7644               .accessfn = access_aa64_tid3,
7645               .resetvalue = 0 },
7646             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7647               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7648               .access = PL1_R, .type = ARM_CP_CONST,
7649               .accessfn = access_aa64_tid3,
7650               .resetvalue = 0 },
7651             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7652               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7653               .access = PL1_R, .type = ARM_CP_CONST,
7654               .accessfn = access_aa64_tid3,
7655               .resetvalue = cpu->isar.id_aa64dfr0 },
7656             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7657               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7658               .access = PL1_R, .type = ARM_CP_CONST,
7659               .accessfn = access_aa64_tid3,
7660               .resetvalue = cpu->isar.id_aa64dfr1 },
7661             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7662               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7663               .access = PL1_R, .type = ARM_CP_CONST,
7664               .accessfn = access_aa64_tid3,
7665               .resetvalue = 0 },
7666             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7667               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7668               .access = PL1_R, .type = ARM_CP_CONST,
7669               .accessfn = access_aa64_tid3,
7670               .resetvalue = 0 },
7671             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7672               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7673               .access = PL1_R, .type = ARM_CP_CONST,
7674               .accessfn = access_aa64_tid3,
7675               .resetvalue = cpu->id_aa64afr0 },
7676             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7677               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7678               .access = PL1_R, .type = ARM_CP_CONST,
7679               .accessfn = access_aa64_tid3,
7680               .resetvalue = cpu->id_aa64afr1 },
7681             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7682               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7683               .access = PL1_R, .type = ARM_CP_CONST,
7684               .accessfn = access_aa64_tid3,
7685               .resetvalue = 0 },
7686             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7687               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7688               .access = PL1_R, .type = ARM_CP_CONST,
7689               .accessfn = access_aa64_tid3,
7690               .resetvalue = 0 },
7691             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7692               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7693               .access = PL1_R, .type = ARM_CP_CONST,
7694               .accessfn = access_aa64_tid3,
7695               .resetvalue = cpu->isar.id_aa64isar0 },
7696             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7697               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7698               .access = PL1_R, .type = ARM_CP_CONST,
7699               .accessfn = access_aa64_tid3,
7700               .resetvalue = cpu->isar.id_aa64isar1 },
7701             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7702               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7703               .access = PL1_R, .type = ARM_CP_CONST,
7704               .accessfn = access_aa64_tid3,
7705               .resetvalue = 0 },
7706             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7707               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7708               .access = PL1_R, .type = ARM_CP_CONST,
7709               .accessfn = access_aa64_tid3,
7710               .resetvalue = 0 },
7711             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7712               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7713               .access = PL1_R, .type = ARM_CP_CONST,
7714               .accessfn = access_aa64_tid3,
7715               .resetvalue = 0 },
7716             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7717               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7718               .access = PL1_R, .type = ARM_CP_CONST,
7719               .accessfn = access_aa64_tid3,
7720               .resetvalue = 0 },
7721             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7722               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7723               .access = PL1_R, .type = ARM_CP_CONST,
7724               .accessfn = access_aa64_tid3,
7725               .resetvalue = 0 },
7726             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7727               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7728               .access = PL1_R, .type = ARM_CP_CONST,
7729               .accessfn = access_aa64_tid3,
7730               .resetvalue = 0 },
7731             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7732               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7733               .access = PL1_R, .type = ARM_CP_CONST,
7734               .accessfn = access_aa64_tid3,
7735               .resetvalue = cpu->isar.id_aa64mmfr0 },
7736             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7737               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7738               .access = PL1_R, .type = ARM_CP_CONST,
7739               .accessfn = access_aa64_tid3,
7740               .resetvalue = cpu->isar.id_aa64mmfr1 },
7741             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7742               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7743               .access = PL1_R, .type = ARM_CP_CONST,
7744               .accessfn = access_aa64_tid3,
7745               .resetvalue = cpu->isar.id_aa64mmfr2 },
7746             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7747               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7748               .access = PL1_R, .type = ARM_CP_CONST,
7749               .accessfn = access_aa64_tid3,
7750               .resetvalue = 0 },
7751             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7752               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7753               .access = PL1_R, .type = ARM_CP_CONST,
7754               .accessfn = access_aa64_tid3,
7755               .resetvalue = 0 },
7756             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7757               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7758               .access = PL1_R, .type = ARM_CP_CONST,
7759               .accessfn = access_aa64_tid3,
7760               .resetvalue = 0 },
7761             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7762               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7763               .access = PL1_R, .type = ARM_CP_CONST,
7764               .accessfn = access_aa64_tid3,
7765               .resetvalue = 0 },
7766             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7767               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7768               .access = PL1_R, .type = ARM_CP_CONST,
7769               .accessfn = access_aa64_tid3,
7770               .resetvalue = 0 },
7771             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7772               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7773               .access = PL1_R, .type = ARM_CP_CONST,
7774               .accessfn = access_aa64_tid3,
7775               .resetvalue = cpu->isar.mvfr0 },
7776             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7777               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7778               .access = PL1_R, .type = ARM_CP_CONST,
7779               .accessfn = access_aa64_tid3,
7780               .resetvalue = cpu->isar.mvfr1 },
7781             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7782               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7783               .access = PL1_R, .type = ARM_CP_CONST,
7784               .accessfn = access_aa64_tid3,
7785               .resetvalue = cpu->isar.mvfr2 },
7786             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7787               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7788               .access = PL1_R, .type = ARM_CP_CONST,
7789               .accessfn = access_aa64_tid3,
7790               .resetvalue = 0 },
7791             { .name = "ID_PFR2", .state = ARM_CP_STATE_BOTH,
7792               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7793               .access = PL1_R, .type = ARM_CP_CONST,
7794               .accessfn = access_aa64_tid3,
7795               .resetvalue = cpu->isar.id_pfr2 },
7796             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7797               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7798               .access = PL1_R, .type = ARM_CP_CONST,
7799               .accessfn = access_aa64_tid3,
7800               .resetvalue = 0 },
7801             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7802               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7803               .access = PL1_R, .type = ARM_CP_CONST,
7804               .accessfn = access_aa64_tid3,
7805               .resetvalue = 0 },
7806             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7807               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7808               .access = PL1_R, .type = ARM_CP_CONST,
7809               .accessfn = access_aa64_tid3,
7810               .resetvalue = 0 },
7811             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7812               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7813               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7814               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7815             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7816               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7817               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7818               .resetvalue = cpu->pmceid0 },
7819             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7820               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7821               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7822               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7823             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7824               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7825               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7826               .resetvalue = cpu->pmceid1 },
7827         };
7828 #ifdef CONFIG_USER_ONLY
7829         static const ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7830             { .name = "ID_AA64PFR0_EL1",
7831               .exported_bits = 0x000f000f00ff0000,
7832               .fixed_bits    = 0x0000000000000011 },
7833             { .name = "ID_AA64PFR1_EL1",
7834               .exported_bits = 0x00000000000000f0 },
7835             { .name = "ID_AA64PFR*_EL1_RESERVED",
7836               .is_glob = true                     },
7837             { .name = "ID_AA64ZFR0_EL1"           },
7838             { .name = "ID_AA64MMFR0_EL1",
7839               .fixed_bits    = 0x00000000ff000000 },
7840             { .name = "ID_AA64MMFR1_EL1"          },
7841             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7842               .is_glob = true                     },
7843             { .name = "ID_AA64DFR0_EL1",
7844               .fixed_bits    = 0x0000000000000006 },
7845             { .name = "ID_AA64DFR1_EL1"           },
7846             { .name = "ID_AA64DFR*_EL1_RESERVED",
7847               .is_glob = true                     },
7848             { .name = "ID_AA64AFR*",
7849               .is_glob = true                     },
7850             { .name = "ID_AA64ISAR0_EL1",
7851               .exported_bits = 0x00fffffff0fffff0 },
7852             { .name = "ID_AA64ISAR1_EL1",
7853               .exported_bits = 0x000000f0ffffffff },
7854             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7855               .is_glob = true                     },
7856         };
7857         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7858 #endif
7859         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7860         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7861             !arm_feature(env, ARM_FEATURE_EL2)) {
7862             ARMCPRegInfo rvbar = {
7863                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7864                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7865                 .access = PL1_R,
7866                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7867             };
7868             define_one_arm_cp_reg(cpu, &rvbar);
7869         }
7870         define_arm_cp_regs(cpu, v8_idregs);
7871         define_arm_cp_regs(cpu, v8_cp_reginfo);
7872     }
7873 
7874     /*
7875      * Register the base EL2 cpregs.
7876      * Pre v8, these registers are implemented only as part of the
7877      * Virtualization Extensions (EL2 present).  Beginning with v8,
7878      * if EL2 is missing but EL3 is enabled, mostly these become
7879      * RES0 from EL3, with some specific exceptions.
7880      */
7881     if (arm_feature(env, ARM_FEATURE_EL2)
7882         || (arm_feature(env, ARM_FEATURE_EL3)
7883             && arm_feature(env, ARM_FEATURE_V8))) {
7884         uint64_t vmpidr_def = mpidr_read_val(env);
7885         ARMCPRegInfo vpidr_regs[] = {
7886             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7887               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7888               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7889               .resetvalue = cpu->midr,
7890               .type = ARM_CP_ALIAS | ARM_CP_EL3_NO_EL2_C_NZ,
7891               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7892             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7893               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7894               .access = PL2_RW, .resetvalue = cpu->midr,
7895               .type = ARM_CP_EL3_NO_EL2_C_NZ,
7896               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7897             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7898               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7899               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7900               .resetvalue = vmpidr_def,
7901               .type = ARM_CP_ALIAS | ARM_CP_EL3_NO_EL2_C_NZ,
7902               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7903             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7904               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7905               .access = PL2_RW, .resetvalue = vmpidr_def,
7906               .type = ARM_CP_EL3_NO_EL2_C_NZ,
7907               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7908         };
7909         define_arm_cp_regs(cpu, vpidr_regs);
7910         define_arm_cp_regs(cpu, el2_cp_reginfo);
7911         if (arm_feature(env, ARM_FEATURE_V8)) {
7912             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
7913         }
7914         if (cpu_isar_feature(aa64_sel2, cpu)) {
7915             define_arm_cp_regs(cpu, el2_sec_cp_reginfo);
7916         }
7917         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
7918         if (!arm_feature(env, ARM_FEATURE_EL3)) {
7919             ARMCPRegInfo rvbar = {
7920                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
7921                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
7922                 .access = PL2_R,
7923                 .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7924             };
7925             define_one_arm_cp_reg(cpu, &rvbar);
7926         }
7927     }
7928 
7929     /* Register the base EL3 cpregs. */
7930     if (arm_feature(env, ARM_FEATURE_EL3)) {
7931         define_arm_cp_regs(cpu, el3_cp_reginfo);
7932         ARMCPRegInfo el3_regs[] = {
7933             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
7934               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
7935               .access = PL3_R,
7936               .fieldoffset = offsetof(CPUARMState, cp15.rvbar),
7937             },
7938             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
7939               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
7940               .access = PL3_RW,
7941               .raw_writefn = raw_write, .writefn = sctlr_write,
7942               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
7943               .resetvalue = cpu->reset_sctlr },
7944         };
7945 
7946         define_arm_cp_regs(cpu, el3_regs);
7947     }
7948     /* The behaviour of NSACR is sufficiently various that we don't
7949      * try to describe it in a single reginfo:
7950      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
7951      *     reads as constant 0xc00 from NS EL1 and NS EL2
7952      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
7953      *  if v7 without EL3, register doesn't exist
7954      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
7955      */
7956     if (arm_feature(env, ARM_FEATURE_EL3)) {
7957         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7958             static const ARMCPRegInfo nsacr = {
7959                 .name = "NSACR", .type = ARM_CP_CONST,
7960                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7961                 .access = PL1_RW, .accessfn = nsacr_access,
7962                 .resetvalue = 0xc00
7963             };
7964             define_one_arm_cp_reg(cpu, &nsacr);
7965         } else {
7966             static const ARMCPRegInfo nsacr = {
7967                 .name = "NSACR",
7968                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7969                 .access = PL3_RW | PL1_R,
7970                 .resetvalue = 0,
7971                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
7972             };
7973             define_one_arm_cp_reg(cpu, &nsacr);
7974         }
7975     } else {
7976         if (arm_feature(env, ARM_FEATURE_V8)) {
7977             static const ARMCPRegInfo nsacr = {
7978                 .name = "NSACR", .type = ARM_CP_CONST,
7979                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7980                 .access = PL1_R,
7981                 .resetvalue = 0xc00
7982             };
7983             define_one_arm_cp_reg(cpu, &nsacr);
7984         }
7985     }
7986 
7987     if (arm_feature(env, ARM_FEATURE_PMSA)) {
7988         if (arm_feature(env, ARM_FEATURE_V6)) {
7989             /* PMSAv6 not implemented */
7990             assert(arm_feature(env, ARM_FEATURE_V7));
7991             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7992             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
7993         } else {
7994             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
7995         }
7996     } else {
7997         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7998         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
7999         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
8000         if (cpu_isar_feature(aa32_hpd, cpu)) {
8001             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
8002         }
8003     }
8004     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
8005         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
8006     }
8007     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
8008         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
8009     }
8010     if (arm_feature(env, ARM_FEATURE_VAPA)) {
8011         define_arm_cp_regs(cpu, vapa_cp_reginfo);
8012     }
8013     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
8014         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
8015     }
8016     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
8017         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
8018     }
8019     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
8020         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
8021     }
8022     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
8023         define_arm_cp_regs(cpu, omap_cp_reginfo);
8024     }
8025     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
8026         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
8027     }
8028     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8029         define_arm_cp_regs(cpu, xscale_cp_reginfo);
8030     }
8031     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
8032         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
8033     }
8034     if (arm_feature(env, ARM_FEATURE_LPAE)) {
8035         define_arm_cp_regs(cpu, lpae_cp_reginfo);
8036     }
8037     if (cpu_isar_feature(aa32_jazelle, cpu)) {
8038         define_arm_cp_regs(cpu, jazelle_regs);
8039     }
8040     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
8041      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
8042      * be read-only (ie write causes UNDEF exception).
8043      */
8044     {
8045         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
8046             /* Pre-v8 MIDR space.
8047              * Note that the MIDR isn't a simple constant register because
8048              * of the TI925 behaviour where writes to another register can
8049              * cause the MIDR value to change.
8050              *
8051              * Unimplemented registers in the c15 0 0 0 space default to
8052              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
8053              * and friends override accordingly.
8054              */
8055             { .name = "MIDR",
8056               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
8057               .access = PL1_R, .resetvalue = cpu->midr,
8058               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
8059               .readfn = midr_read,
8060               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8061               .type = ARM_CP_OVERRIDE },
8062             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
8063             { .name = "DUMMY",
8064               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
8065               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8066             { .name = "DUMMY",
8067               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
8068               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8069             { .name = "DUMMY",
8070               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
8071               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8072             { .name = "DUMMY",
8073               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
8074               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8075             { .name = "DUMMY",
8076               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
8077               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8078         };
8079         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
8080             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
8081               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
8082               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
8083               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8084               .readfn = midr_read },
8085             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
8086             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8087               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8088               .access = PL1_R, .resetvalue = cpu->midr },
8089             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8090               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
8091               .access = PL1_R, .resetvalue = cpu->midr },
8092             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
8093               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
8094               .access = PL1_R,
8095               .accessfn = access_aa64_tid1,
8096               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
8097         };
8098         ARMCPRegInfo id_cp_reginfo[] = {
8099             /* These are common to v8 and pre-v8 */
8100             { .name = "CTR",
8101               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
8102               .access = PL1_R, .accessfn = ctr_el0_access,
8103               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8104             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
8105               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
8106               .access = PL0_R, .accessfn = ctr_el0_access,
8107               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8108             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
8109             { .name = "TCMTR",
8110               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
8111               .access = PL1_R,
8112               .accessfn = access_aa32_tid1,
8113               .type = ARM_CP_CONST, .resetvalue = 0 },
8114         };
8115         /* TLBTR is specific to VMSA */
8116         ARMCPRegInfo id_tlbtr_reginfo = {
8117               .name = "TLBTR",
8118               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
8119               .access = PL1_R,
8120               .accessfn = access_aa32_tid1,
8121               .type = ARM_CP_CONST, .resetvalue = 0,
8122         };
8123         /* MPUIR is specific to PMSA V6+ */
8124         ARMCPRegInfo id_mpuir_reginfo = {
8125               .name = "MPUIR",
8126               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8127               .access = PL1_R, .type = ARM_CP_CONST,
8128               .resetvalue = cpu->pmsav7_dregion << 8
8129         };
8130         static const ARMCPRegInfo crn0_wi_reginfo = {
8131             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
8132             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
8133             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
8134         };
8135 #ifdef CONFIG_USER_ONLY
8136         static const ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
8137             { .name = "MIDR_EL1",
8138               .exported_bits = 0x00000000ffffffff },
8139             { .name = "REVIDR_EL1"                },
8140         };
8141         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
8142 #endif
8143         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
8144             arm_feature(env, ARM_FEATURE_STRONGARM)) {
8145             size_t i;
8146             /* Register the blanket "writes ignored" value first to cover the
8147              * whole space. Then update the specific ID registers to allow write
8148              * access, so that they ignore writes rather than causing them to
8149              * UNDEF.
8150              */
8151             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
8152             for (i = 0; i < ARRAY_SIZE(id_pre_v8_midr_cp_reginfo); ++i) {
8153                 id_pre_v8_midr_cp_reginfo[i].access = PL1_RW;
8154             }
8155             for (i = 0; i < ARRAY_SIZE(id_cp_reginfo); ++i) {
8156                 id_cp_reginfo[i].access = PL1_RW;
8157             }
8158             id_mpuir_reginfo.access = PL1_RW;
8159             id_tlbtr_reginfo.access = PL1_RW;
8160         }
8161         if (arm_feature(env, ARM_FEATURE_V8)) {
8162             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
8163         } else {
8164             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
8165         }
8166         define_arm_cp_regs(cpu, id_cp_reginfo);
8167         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
8168             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
8169         } else if (arm_feature(env, ARM_FEATURE_V7)) {
8170             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
8171         }
8172     }
8173 
8174     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
8175         ARMCPRegInfo mpidr_cp_reginfo[] = {
8176             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
8177               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
8178               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
8179         };
8180 #ifdef CONFIG_USER_ONLY
8181         static const ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
8182             { .name = "MPIDR_EL1",
8183               .fixed_bits = 0x0000000080000000 },
8184         };
8185         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
8186 #endif
8187         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
8188     }
8189 
8190     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
8191         ARMCPRegInfo auxcr_reginfo[] = {
8192             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
8193               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
8194               .access = PL1_RW, .accessfn = access_tacr,
8195               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
8196             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
8197               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
8198               .access = PL2_RW, .type = ARM_CP_CONST,
8199               .resetvalue = 0 },
8200             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
8201               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
8202               .access = PL3_RW, .type = ARM_CP_CONST,
8203               .resetvalue = 0 },
8204         };
8205         define_arm_cp_regs(cpu, auxcr_reginfo);
8206         if (cpu_isar_feature(aa32_ac2, cpu)) {
8207             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
8208         }
8209     }
8210 
8211     if (arm_feature(env, ARM_FEATURE_CBAR)) {
8212         /*
8213          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
8214          * There are two flavours:
8215          *  (1) older 32-bit only cores have a simple 32-bit CBAR
8216          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
8217          *      32-bit register visible to AArch32 at a different encoding
8218          *      to the "flavour 1" register and with the bits rearranged to
8219          *      be able to squash a 64-bit address into the 32-bit view.
8220          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
8221          * in future if we support AArch32-only configs of some of the
8222          * AArch64 cores we might need to add a specific feature flag
8223          * to indicate cores with "flavour 2" CBAR.
8224          */
8225         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8226             /* 32 bit view is [31:18] 0...0 [43:32]. */
8227             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
8228                 | extract64(cpu->reset_cbar, 32, 12);
8229             ARMCPRegInfo cbar_reginfo[] = {
8230                 { .name = "CBAR",
8231                   .type = ARM_CP_CONST,
8232                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
8233                   .access = PL1_R, .resetvalue = cbar32 },
8234                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
8235                   .type = ARM_CP_CONST,
8236                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
8237                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
8238             };
8239             /* We don't implement a r/w 64 bit CBAR currently */
8240             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
8241             define_arm_cp_regs(cpu, cbar_reginfo);
8242         } else {
8243             ARMCPRegInfo cbar = {
8244                 .name = "CBAR",
8245                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
8246                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
8247                 .fieldoffset = offsetof(CPUARMState,
8248                                         cp15.c15_config_base_address)
8249             };
8250             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
8251                 cbar.access = PL1_R;
8252                 cbar.fieldoffset = 0;
8253                 cbar.type = ARM_CP_CONST;
8254             }
8255             define_one_arm_cp_reg(cpu, &cbar);
8256         }
8257     }
8258 
8259     if (arm_feature(env, ARM_FEATURE_VBAR)) {
8260         static const ARMCPRegInfo vbar_cp_reginfo[] = {
8261             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
8262               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
8263               .access = PL1_RW, .writefn = vbar_write,
8264               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
8265                                      offsetof(CPUARMState, cp15.vbar_ns) },
8266               .resetvalue = 0 },
8267         };
8268         define_arm_cp_regs(cpu, vbar_cp_reginfo);
8269     }
8270 
8271     /* Generic registers whose values depend on the implementation */
8272     {
8273         ARMCPRegInfo sctlr = {
8274             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8275             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8276             .access = PL1_RW, .accessfn = access_tvm_trvm,
8277             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8278                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8279             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8280             .raw_writefn = raw_write,
8281         };
8282         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8283             /* Normally we would always end the TB on an SCTLR write, but Linux
8284              * arch/arm/mach-pxa/sleep.S expects two instructions following
8285              * an MMU enable to execute from cache.  Imitate this behaviour.
8286              */
8287             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8288         }
8289         define_one_arm_cp_reg(cpu, &sctlr);
8290     }
8291 
8292     if (cpu_isar_feature(aa64_lor, cpu)) {
8293         define_arm_cp_regs(cpu, lor_reginfo);
8294     }
8295     if (cpu_isar_feature(aa64_pan, cpu)) {
8296         define_one_arm_cp_reg(cpu, &pan_reginfo);
8297     }
8298 #ifndef CONFIG_USER_ONLY
8299     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8300         define_arm_cp_regs(cpu, ats1e1_reginfo);
8301     }
8302     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8303         define_arm_cp_regs(cpu, ats1cp_reginfo);
8304     }
8305 #endif
8306     if (cpu_isar_feature(aa64_uao, cpu)) {
8307         define_one_arm_cp_reg(cpu, &uao_reginfo);
8308     }
8309 
8310     if (cpu_isar_feature(aa64_dit, cpu)) {
8311         define_one_arm_cp_reg(cpu, &dit_reginfo);
8312     }
8313     if (cpu_isar_feature(aa64_ssbs, cpu)) {
8314         define_one_arm_cp_reg(cpu, &ssbs_reginfo);
8315     }
8316     if (cpu_isar_feature(any_ras, cpu)) {
8317         define_arm_cp_regs(cpu, minimal_ras_reginfo);
8318     }
8319 
8320     if (cpu_isar_feature(aa64_vh, cpu) ||
8321         cpu_isar_feature(aa64_debugv8p2, cpu)) {
8322         define_one_arm_cp_reg(cpu, &contextidr_el2);
8323     }
8324     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8325         define_arm_cp_regs(cpu, vhe_reginfo);
8326     }
8327 
8328     if (cpu_isar_feature(aa64_sve, cpu)) {
8329         define_arm_cp_regs(cpu, zcr_reginfo);
8330     }
8331 
8332 #ifdef TARGET_AARCH64
8333     if (cpu_isar_feature(aa64_pauth, cpu)) {
8334         define_arm_cp_regs(cpu, pauth_reginfo);
8335     }
8336     if (cpu_isar_feature(aa64_rndr, cpu)) {
8337         define_arm_cp_regs(cpu, rndr_reginfo);
8338     }
8339     if (cpu_isar_feature(aa64_tlbirange, cpu)) {
8340         define_arm_cp_regs(cpu, tlbirange_reginfo);
8341     }
8342     if (cpu_isar_feature(aa64_tlbios, cpu)) {
8343         define_arm_cp_regs(cpu, tlbios_reginfo);
8344     }
8345 #ifndef CONFIG_USER_ONLY
8346     /* Data Cache clean instructions up to PoP */
8347     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8348         define_one_arm_cp_reg(cpu, dcpop_reg);
8349 
8350         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8351             define_one_arm_cp_reg(cpu, dcpodp_reg);
8352         }
8353     }
8354 #endif /*CONFIG_USER_ONLY*/
8355 
8356     /*
8357      * If full MTE is enabled, add all of the system registers.
8358      * If only "instructions available at EL0" are enabled,
8359      * then define only a RAZ/WI version of PSTATE.TCO.
8360      */
8361     if (cpu_isar_feature(aa64_mte, cpu)) {
8362         define_arm_cp_regs(cpu, mte_reginfo);
8363         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8364     } else if (cpu_isar_feature(aa64_mte_insn_reg, cpu)) {
8365         define_arm_cp_regs(cpu, mte_tco_ro_reginfo);
8366         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8367     }
8368 #endif
8369 
8370     if (cpu_isar_feature(any_predinv, cpu)) {
8371         define_arm_cp_regs(cpu, predinv_reginfo);
8372     }
8373 
8374     if (cpu_isar_feature(any_ccidx, cpu)) {
8375         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8376     }
8377 
8378 #ifndef CONFIG_USER_ONLY
8379     /*
8380      * Register redirections and aliases must be done last,
8381      * after the registers from the other extensions have been defined.
8382      */
8383     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8384         define_arm_vh_e2h_redirects_aliases(cpu);
8385     }
8386 #endif
8387 }
8388 
8389 /* Sort alphabetically by type name, except for "any". */
8390 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8391 {
8392     ObjectClass *class_a = (ObjectClass *)a;
8393     ObjectClass *class_b = (ObjectClass *)b;
8394     const char *name_a, *name_b;
8395 
8396     name_a = object_class_get_name(class_a);
8397     name_b = object_class_get_name(class_b);
8398     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8399         return 1;
8400     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8401         return -1;
8402     } else {
8403         return strcmp(name_a, name_b);
8404     }
8405 }
8406 
8407 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8408 {
8409     ObjectClass *oc = data;
8410     const char *typename;
8411     char *name;
8412 
8413     typename = object_class_get_name(oc);
8414     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8415     qemu_printf("  %s\n", name);
8416     g_free(name);
8417 }
8418 
8419 void arm_cpu_list(void)
8420 {
8421     GSList *list;
8422 
8423     list = object_class_get_list(TYPE_ARM_CPU, false);
8424     list = g_slist_sort(list, arm_cpu_list_compare);
8425     qemu_printf("Available CPUs:\n");
8426     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8427     g_slist_free(list);
8428 }
8429 
8430 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8431 {
8432     ObjectClass *oc = data;
8433     CpuDefinitionInfoList **cpu_list = user_data;
8434     CpuDefinitionInfo *info;
8435     const char *typename;
8436 
8437     typename = object_class_get_name(oc);
8438     info = g_malloc0(sizeof(*info));
8439     info->name = g_strndup(typename,
8440                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8441     info->q_typename = g_strdup(typename);
8442 
8443     QAPI_LIST_PREPEND(*cpu_list, info);
8444 }
8445 
8446 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8447 {
8448     CpuDefinitionInfoList *cpu_list = NULL;
8449     GSList *list;
8450 
8451     list = object_class_get_list(TYPE_ARM_CPU, false);
8452     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8453     g_slist_free(list);
8454 
8455     return cpu_list;
8456 }
8457 
8458 /*
8459  * Private utility function for define_one_arm_cp_reg_with_opaque():
8460  * add a single reginfo struct to the hash table.
8461  */
8462 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8463                                    void *opaque, CPState state,
8464                                    CPSecureState secstate,
8465                                    int crm, int opc1, int opc2,
8466                                    const char *name)
8467 {
8468     CPUARMState *env = &cpu->env;
8469     uint32_t key;
8470     ARMCPRegInfo *r2;
8471     bool is64 = r->type & ARM_CP_64BIT;
8472     bool ns = secstate & ARM_CP_SECSTATE_NS;
8473     int cp = r->cp;
8474     size_t name_len;
8475     bool make_const;
8476 
8477     switch (state) {
8478     case ARM_CP_STATE_AA32:
8479         /* We assume it is a cp15 register if the .cp field is left unset. */
8480         if (cp == 0 && r->state == ARM_CP_STATE_BOTH) {
8481             cp = 15;
8482         }
8483         key = ENCODE_CP_REG(cp, is64, ns, r->crn, crm, opc1, opc2);
8484         break;
8485     case ARM_CP_STATE_AA64:
8486         /*
8487          * To allow abbreviation of ARMCPRegInfo definitions, we treat
8488          * cp == 0 as equivalent to the value for "standard guest-visible
8489          * sysreg".  STATE_BOTH definitions are also always "standard sysreg"
8490          * in their AArch64 view (the .cp value may be non-zero for the
8491          * benefit of the AArch32 view).
8492          */
8493         if (cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8494             cp = CP_REG_ARM64_SYSREG_CP;
8495         }
8496         key = ENCODE_AA64_CP_REG(cp, r->crn, crm, r->opc0, opc1, opc2);
8497         break;
8498     default:
8499         g_assert_not_reached();
8500     }
8501 
8502     /* Overriding of an existing definition must be explicitly requested. */
8503     if (!(r->type & ARM_CP_OVERRIDE)) {
8504         const ARMCPRegInfo *oldreg = get_arm_cp_reginfo(cpu->cp_regs, key);
8505         if (oldreg) {
8506             assert(oldreg->type & ARM_CP_OVERRIDE);
8507         }
8508     }
8509 
8510     /*
8511      * Eliminate registers that are not present because the EL is missing.
8512      * Doing this here makes it easier to put all registers for a given
8513      * feature into the same ARMCPRegInfo array and define them all at once.
8514      */
8515     make_const = false;
8516     if (arm_feature(env, ARM_FEATURE_EL3)) {
8517         /*
8518          * An EL2 register without EL2 but with EL3 is (usually) RES0.
8519          * See rule RJFFP in section D1.1.3 of DDI0487H.a.
8520          */
8521         int min_el = ctz32(r->access) / 2;
8522         if (min_el == 2 && !arm_feature(env, ARM_FEATURE_EL2)) {
8523             if (r->type & ARM_CP_EL3_NO_EL2_UNDEF) {
8524                 return;
8525             }
8526             make_const = !(r->type & ARM_CP_EL3_NO_EL2_KEEP);
8527         }
8528     } else {
8529         CPAccessRights max_el = (arm_feature(env, ARM_FEATURE_EL2)
8530                                  ? PL2_RW : PL1_RW);
8531         if ((r->access & max_el) == 0) {
8532             return;
8533         }
8534     }
8535 
8536     /* Combine cpreg and name into one allocation. */
8537     name_len = strlen(name) + 1;
8538     r2 = g_malloc(sizeof(*r2) + name_len);
8539     *r2 = *r;
8540     r2->name = memcpy(r2 + 1, name, name_len);
8541 
8542     /*
8543      * Update fields to match the instantiation, overwiting wildcards
8544      * such as CP_ANY, ARM_CP_STATE_BOTH, or ARM_CP_SECSTATE_BOTH.
8545      */
8546     r2->cp = cp;
8547     r2->crm = crm;
8548     r2->opc1 = opc1;
8549     r2->opc2 = opc2;
8550     r2->state = state;
8551     r2->secure = secstate;
8552     if (opaque) {
8553         r2->opaque = opaque;
8554     }
8555 
8556     if (make_const) {
8557         /* This should not have been a very special register to begin. */
8558         int old_special = r2->type & ARM_CP_SPECIAL_MASK;
8559         assert(old_special == 0 || old_special == ARM_CP_NOP);
8560         /*
8561          * Set the special function to CONST, retaining the other flags.
8562          * This is important for e.g. ARM_CP_SVE so that we still
8563          * take the SVE trap if CPTR_EL3.EZ == 0.
8564          */
8565         r2->type = (r2->type & ~ARM_CP_SPECIAL_MASK) | ARM_CP_CONST;
8566         /*
8567          * Usually, these registers become RES0, but there are a few
8568          * special cases like VPIDR_EL2 which have a constant non-zero
8569          * value with writes ignored.
8570          */
8571         if (!(r->type & ARM_CP_EL3_NO_EL2_C_NZ)) {
8572             r2->resetvalue = 0;
8573         }
8574         /*
8575          * ARM_CP_CONST has precedence, so removing the callbacks and
8576          * offsets are not strictly necessary, but it is potentially
8577          * less confusing to debug later.
8578          */
8579         r2->readfn = NULL;
8580         r2->writefn = NULL;
8581         r2->raw_readfn = NULL;
8582         r2->raw_writefn = NULL;
8583         r2->resetfn = NULL;
8584         r2->fieldoffset = 0;
8585         r2->bank_fieldoffsets[0] = 0;
8586         r2->bank_fieldoffsets[1] = 0;
8587     } else {
8588         bool isbanked = r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1];
8589 
8590         if (isbanked) {
8591             /*
8592              * Register is banked (using both entries in array).
8593              * Overwriting fieldoffset as the array is only used to define
8594              * banked registers but later only fieldoffset is used.
8595              */
8596             r2->fieldoffset = r->bank_fieldoffsets[ns];
8597         }
8598         if (state == ARM_CP_STATE_AA32) {
8599             if (isbanked) {
8600                 /*
8601                  * If the register is banked then we don't need to migrate or
8602                  * reset the 32-bit instance in certain cases:
8603                  *
8604                  * 1) If the register has both 32-bit and 64-bit instances
8605                  *    then we can count on the 64-bit instance taking care
8606                  *    of the non-secure bank.
8607                  * 2) If ARMv8 is enabled then we can count on a 64-bit
8608                  *    version taking care of the secure bank.  This requires
8609                  *    that separate 32 and 64-bit definitions are provided.
8610                  */
8611                 if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8612                     (arm_feature(env, ARM_FEATURE_V8) && !ns)) {
8613                     r2->type |= ARM_CP_ALIAS;
8614                 }
8615             } else if ((secstate != r->secure) && !ns) {
8616                 /*
8617                  * The register is not banked so we only want to allow
8618                  * migration of the non-secure instance.
8619                  */
8620                 r2->type |= ARM_CP_ALIAS;
8621             }
8622 
8623             if (HOST_BIG_ENDIAN &&
8624                 r->state == ARM_CP_STATE_BOTH && r2->fieldoffset) {
8625                 r2->fieldoffset += sizeof(uint32_t);
8626             }
8627         }
8628     }
8629 
8630     /*
8631      * By convention, for wildcarded registers only the first
8632      * entry is used for migration; the others are marked as
8633      * ALIAS so we don't try to transfer the register
8634      * multiple times. Special registers (ie NOP/WFI) are
8635      * never migratable and not even raw-accessible.
8636      */
8637     if (r2->type & ARM_CP_SPECIAL_MASK) {
8638         r2->type |= ARM_CP_NO_RAW;
8639     }
8640     if (((r->crm == CP_ANY) && crm != 0) ||
8641         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8642         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8643         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8644     }
8645 
8646     /*
8647      * Check that raw accesses are either forbidden or handled. Note that
8648      * we can't assert this earlier because the setup of fieldoffset for
8649      * banked registers has to be done first.
8650      */
8651     if (!(r2->type & ARM_CP_NO_RAW)) {
8652         assert(!raw_accessors_invalid(r2));
8653     }
8654 
8655     g_hash_table_insert(cpu->cp_regs, (gpointer)(uintptr_t)key, r2);
8656 }
8657 
8658 
8659 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8660                                        const ARMCPRegInfo *r, void *opaque)
8661 {
8662     /* Define implementations of coprocessor registers.
8663      * We store these in a hashtable because typically
8664      * there are less than 150 registers in a space which
8665      * is 16*16*16*8*8 = 262144 in size.
8666      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8667      * If a register is defined twice then the second definition is
8668      * used, so this can be used to define some generic registers and
8669      * then override them with implementation specific variations.
8670      * At least one of the original and the second definition should
8671      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8672      * against accidental use.
8673      *
8674      * The state field defines whether the register is to be
8675      * visible in the AArch32 or AArch64 execution state. If the
8676      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8677      * reginfo structure for the AArch32 view, which sees the lower
8678      * 32 bits of the 64 bit register.
8679      *
8680      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8681      * be wildcarded. AArch64 registers are always considered to be 64
8682      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8683      * the register, if any.
8684      */
8685     int crm, opc1, opc2;
8686     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8687     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8688     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8689     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8690     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8691     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8692     CPState state;
8693 
8694     /* 64 bit registers have only CRm and Opc1 fields */
8695     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8696     /* op0 only exists in the AArch64 encodings */
8697     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8698     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8699     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8700     /*
8701      * This API is only for Arm's system coprocessors (14 and 15) or
8702      * (M-profile or v7A-and-earlier only) for implementation defined
8703      * coprocessors in the range 0..7.  Our decode assumes this, since
8704      * 8..13 can be used for other insns including VFP and Neon. See
8705      * valid_cp() in translate.c.  Assert here that we haven't tried
8706      * to use an invalid coprocessor number.
8707      */
8708     switch (r->state) {
8709     case ARM_CP_STATE_BOTH:
8710         /* 0 has a special meaning, but otherwise the same rules as AA32. */
8711         if (r->cp == 0) {
8712             break;
8713         }
8714         /* fall through */
8715     case ARM_CP_STATE_AA32:
8716         if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
8717             !arm_feature(&cpu->env, ARM_FEATURE_M)) {
8718             assert(r->cp >= 14 && r->cp <= 15);
8719         } else {
8720             assert(r->cp < 8 || (r->cp >= 14 && r->cp <= 15));
8721         }
8722         break;
8723     case ARM_CP_STATE_AA64:
8724         assert(r->cp == 0 || r->cp == CP_REG_ARM64_SYSREG_CP);
8725         break;
8726     default:
8727         g_assert_not_reached();
8728     }
8729     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8730      * encodes a minimum access level for the register. We roll this
8731      * runtime check into our general permission check code, so check
8732      * here that the reginfo's specified permissions are strict enough
8733      * to encompass the generic architectural permission check.
8734      */
8735     if (r->state != ARM_CP_STATE_AA32) {
8736         CPAccessRights mask;
8737         switch (r->opc1) {
8738         case 0:
8739             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8740             mask = PL0U_R | PL1_RW;
8741             break;
8742         case 1: case 2:
8743             /* min_EL EL1 */
8744             mask = PL1_RW;
8745             break;
8746         case 3:
8747             /* min_EL EL0 */
8748             mask = PL0_RW;
8749             break;
8750         case 4:
8751         case 5:
8752             /* min_EL EL2 */
8753             mask = PL2_RW;
8754             break;
8755         case 6:
8756             /* min_EL EL3 */
8757             mask = PL3_RW;
8758             break;
8759         case 7:
8760             /* min_EL EL1, secure mode only (we don't check the latter) */
8761             mask = PL1_RW;
8762             break;
8763         default:
8764             /* broken reginfo with out-of-range opc1 */
8765             g_assert_not_reached();
8766         }
8767         /* assert our permissions are not too lax (stricter is fine) */
8768         assert((r->access & ~mask) == 0);
8769     }
8770 
8771     /* Check that the register definition has enough info to handle
8772      * reads and writes if they are permitted.
8773      */
8774     if (!(r->type & (ARM_CP_SPECIAL_MASK | ARM_CP_CONST))) {
8775         if (r->access & PL3_R) {
8776             assert((r->fieldoffset ||
8777                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8778                    r->readfn);
8779         }
8780         if (r->access & PL3_W) {
8781             assert((r->fieldoffset ||
8782                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8783                    r->writefn);
8784         }
8785     }
8786 
8787     for (crm = crmmin; crm <= crmmax; crm++) {
8788         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8789             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8790                 for (state = ARM_CP_STATE_AA32;
8791                      state <= ARM_CP_STATE_AA64; state++) {
8792                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8793                         continue;
8794                     }
8795                     if (state == ARM_CP_STATE_AA32) {
8796                         /* Under AArch32 CP registers can be common
8797                          * (same for secure and non-secure world) or banked.
8798                          */
8799                         char *name;
8800 
8801                         switch (r->secure) {
8802                         case ARM_CP_SECSTATE_S:
8803                         case ARM_CP_SECSTATE_NS:
8804                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8805                                                    r->secure, crm, opc1, opc2,
8806                                                    r->name);
8807                             break;
8808                         case ARM_CP_SECSTATE_BOTH:
8809                             name = g_strdup_printf("%s_S", r->name);
8810                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8811                                                    ARM_CP_SECSTATE_S,
8812                                                    crm, opc1, opc2, name);
8813                             g_free(name);
8814                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8815                                                    ARM_CP_SECSTATE_NS,
8816                                                    crm, opc1, opc2, r->name);
8817                             break;
8818                         default:
8819                             g_assert_not_reached();
8820                         }
8821                     } else {
8822                         /* AArch64 registers get mapped to non-secure instance
8823                          * of AArch32 */
8824                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8825                                                ARM_CP_SECSTATE_NS,
8826                                                crm, opc1, opc2, r->name);
8827                     }
8828                 }
8829             }
8830         }
8831     }
8832 }
8833 
8834 /* Define a whole list of registers */
8835 void define_arm_cp_regs_with_opaque_len(ARMCPU *cpu, const ARMCPRegInfo *regs,
8836                                         void *opaque, size_t len)
8837 {
8838     size_t i;
8839     for (i = 0; i < len; ++i) {
8840         define_one_arm_cp_reg_with_opaque(cpu, regs + i, opaque);
8841     }
8842 }
8843 
8844 /*
8845  * Modify ARMCPRegInfo for access from userspace.
8846  *
8847  * This is a data driven modification directed by
8848  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8849  * user-space cannot alter any values and dynamic values pertaining to
8850  * execution state are hidden from user space view anyway.
8851  */
8852 void modify_arm_cp_regs_with_len(ARMCPRegInfo *regs, size_t regs_len,
8853                                  const ARMCPRegUserSpaceInfo *mods,
8854                                  size_t mods_len)
8855 {
8856     for (size_t mi = 0; mi < mods_len; ++mi) {
8857         const ARMCPRegUserSpaceInfo *m = mods + mi;
8858         GPatternSpec *pat = NULL;
8859 
8860         if (m->is_glob) {
8861             pat = g_pattern_spec_new(m->name);
8862         }
8863         for (size_t ri = 0; ri < regs_len; ++ri) {
8864             ARMCPRegInfo *r = regs + ri;
8865 
8866             if (pat && g_pattern_match_string(pat, r->name)) {
8867                 r->type = ARM_CP_CONST;
8868                 r->access = PL0U_R;
8869                 r->resetvalue = 0;
8870                 /* continue */
8871             } else if (strcmp(r->name, m->name) == 0) {
8872                 r->type = ARM_CP_CONST;
8873                 r->access = PL0U_R;
8874                 r->resetvalue &= m->exported_bits;
8875                 r->resetvalue |= m->fixed_bits;
8876                 break;
8877             }
8878         }
8879         if (pat) {
8880             g_pattern_spec_free(pat);
8881         }
8882     }
8883 }
8884 
8885 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8886 {
8887     return g_hash_table_lookup(cpregs, (gpointer)(uintptr_t)encoded_cp);
8888 }
8889 
8890 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8891                          uint64_t value)
8892 {
8893     /* Helper coprocessor write function for write-ignore registers */
8894 }
8895 
8896 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8897 {
8898     /* Helper coprocessor write function for read-as-zero registers */
8899     return 0;
8900 }
8901 
8902 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8903 {
8904     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8905 }
8906 
8907 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8908 {
8909     /* Return true if it is not valid for us to switch to
8910      * this CPU mode (ie all the UNPREDICTABLE cases in
8911      * the ARM ARM CPSRWriteByInstr pseudocode).
8912      */
8913 
8914     /* Changes to or from Hyp via MSR and CPS are illegal. */
8915     if (write_type == CPSRWriteByInstr &&
8916         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8917          mode == ARM_CPU_MODE_HYP)) {
8918         return 1;
8919     }
8920 
8921     switch (mode) {
8922     case ARM_CPU_MODE_USR:
8923         return 0;
8924     case ARM_CPU_MODE_SYS:
8925     case ARM_CPU_MODE_SVC:
8926     case ARM_CPU_MODE_ABT:
8927     case ARM_CPU_MODE_UND:
8928     case ARM_CPU_MODE_IRQ:
8929     case ARM_CPU_MODE_FIQ:
8930         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
8931          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
8932          */
8933         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
8934          * and CPS are treated as illegal mode changes.
8935          */
8936         if (write_type == CPSRWriteByInstr &&
8937             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
8938             (arm_hcr_el2_eff(env) & HCR_TGE)) {
8939             return 1;
8940         }
8941         return 0;
8942     case ARM_CPU_MODE_HYP:
8943         return !arm_is_el2_enabled(env) || arm_current_el(env) < 2;
8944     case ARM_CPU_MODE_MON:
8945         return arm_current_el(env) < 3;
8946     default:
8947         return 1;
8948     }
8949 }
8950 
8951 uint32_t cpsr_read(CPUARMState *env)
8952 {
8953     int ZF;
8954     ZF = (env->ZF == 0);
8955     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
8956         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
8957         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
8958         | ((env->condexec_bits & 0xfc) << 8)
8959         | (env->GE << 16) | (env->daif & CPSR_AIF);
8960 }
8961 
8962 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
8963                 CPSRWriteType write_type)
8964 {
8965     uint32_t changed_daif;
8966     bool rebuild_hflags = (write_type != CPSRWriteRaw) &&
8967         (mask & (CPSR_M | CPSR_E | CPSR_IL));
8968 
8969     if (mask & CPSR_NZCV) {
8970         env->ZF = (~val) & CPSR_Z;
8971         env->NF = val;
8972         env->CF = (val >> 29) & 1;
8973         env->VF = (val << 3) & 0x80000000;
8974     }
8975     if (mask & CPSR_Q)
8976         env->QF = ((val & CPSR_Q) != 0);
8977     if (mask & CPSR_T)
8978         env->thumb = ((val & CPSR_T) != 0);
8979     if (mask & CPSR_IT_0_1) {
8980         env->condexec_bits &= ~3;
8981         env->condexec_bits |= (val >> 25) & 3;
8982     }
8983     if (mask & CPSR_IT_2_7) {
8984         env->condexec_bits &= 3;
8985         env->condexec_bits |= (val >> 8) & 0xfc;
8986     }
8987     if (mask & CPSR_GE) {
8988         env->GE = (val >> 16) & 0xf;
8989     }
8990 
8991     /* In a V7 implementation that includes the security extensions but does
8992      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
8993      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
8994      * bits respectively.
8995      *
8996      * In a V8 implementation, it is permitted for privileged software to
8997      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
8998      */
8999     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
9000         arm_feature(env, ARM_FEATURE_EL3) &&
9001         !arm_feature(env, ARM_FEATURE_EL2) &&
9002         !arm_is_secure(env)) {
9003 
9004         changed_daif = (env->daif ^ val) & mask;
9005 
9006         if (changed_daif & CPSR_A) {
9007             /* Check to see if we are allowed to change the masking of async
9008              * abort exceptions from a non-secure state.
9009              */
9010             if (!(env->cp15.scr_el3 & SCR_AW)) {
9011                 qemu_log_mask(LOG_GUEST_ERROR,
9012                               "Ignoring attempt to switch CPSR_A flag from "
9013                               "non-secure world with SCR.AW bit clear\n");
9014                 mask &= ~CPSR_A;
9015             }
9016         }
9017 
9018         if (changed_daif & CPSR_F) {
9019             /* Check to see if we are allowed to change the masking of FIQ
9020              * exceptions from a non-secure state.
9021              */
9022             if (!(env->cp15.scr_el3 & SCR_FW)) {
9023                 qemu_log_mask(LOG_GUEST_ERROR,
9024                               "Ignoring attempt to switch CPSR_F flag from "
9025                               "non-secure world with SCR.FW bit clear\n");
9026                 mask &= ~CPSR_F;
9027             }
9028 
9029             /* Check whether non-maskable FIQ (NMFI) support is enabled.
9030              * If this bit is set software is not allowed to mask
9031              * FIQs, but is allowed to set CPSR_F to 0.
9032              */
9033             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
9034                 (val & CPSR_F)) {
9035                 qemu_log_mask(LOG_GUEST_ERROR,
9036                               "Ignoring attempt to enable CPSR_F flag "
9037                               "(non-maskable FIQ [NMFI] support enabled)\n");
9038                 mask &= ~CPSR_F;
9039             }
9040         }
9041     }
9042 
9043     env->daif &= ~(CPSR_AIF & mask);
9044     env->daif |= val & CPSR_AIF & mask;
9045 
9046     if (write_type != CPSRWriteRaw &&
9047         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
9048         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
9049             /* Note that we can only get here in USR mode if this is a
9050              * gdb stub write; for this case we follow the architectural
9051              * behaviour for guest writes in USR mode of ignoring an attempt
9052              * to switch mode. (Those are caught by translate.c for writes
9053              * triggered by guest instructions.)
9054              */
9055             mask &= ~CPSR_M;
9056         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
9057             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
9058              * v7, and has defined behaviour in v8:
9059              *  + leave CPSR.M untouched
9060              *  + allow changes to the other CPSR fields
9061              *  + set PSTATE.IL
9062              * For user changes via the GDB stub, we don't set PSTATE.IL,
9063              * as this would be unnecessarily harsh for a user error.
9064              */
9065             mask &= ~CPSR_M;
9066             if (write_type != CPSRWriteByGDBStub &&
9067                 arm_feature(env, ARM_FEATURE_V8)) {
9068                 mask |= CPSR_IL;
9069                 val |= CPSR_IL;
9070             }
9071             qemu_log_mask(LOG_GUEST_ERROR,
9072                           "Illegal AArch32 mode switch attempt from %s to %s\n",
9073                           aarch32_mode_name(env->uncached_cpsr),
9074                           aarch32_mode_name(val));
9075         } else {
9076             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
9077                           write_type == CPSRWriteExceptionReturn ?
9078                           "Exception return from AArch32" :
9079                           "AArch32 mode switch from",
9080                           aarch32_mode_name(env->uncached_cpsr),
9081                           aarch32_mode_name(val), env->regs[15]);
9082             switch_mode(env, val & CPSR_M);
9083         }
9084     }
9085     mask &= ~CACHED_CPSR_BITS;
9086     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
9087     if (rebuild_hflags) {
9088         arm_rebuild_hflags(env);
9089     }
9090 }
9091 
9092 /* Sign/zero extend */
9093 uint32_t HELPER(sxtb16)(uint32_t x)
9094 {
9095     uint32_t res;
9096     res = (uint16_t)(int8_t)x;
9097     res |= (uint32_t)(int8_t)(x >> 16) << 16;
9098     return res;
9099 }
9100 
9101 static void handle_possible_div0_trap(CPUARMState *env, uintptr_t ra)
9102 {
9103     /*
9104      * Take a division-by-zero exception if necessary; otherwise return
9105      * to get the usual non-trapping division behaviour (result of 0)
9106      */
9107     if (arm_feature(env, ARM_FEATURE_M)
9108         && (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_DIV_0_TRP_MASK)) {
9109         raise_exception_ra(env, EXCP_DIVBYZERO, 0, 1, ra);
9110     }
9111 }
9112 
9113 uint32_t HELPER(uxtb16)(uint32_t x)
9114 {
9115     uint32_t res;
9116     res = (uint16_t)(uint8_t)x;
9117     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
9118     return res;
9119 }
9120 
9121 int32_t HELPER(sdiv)(CPUARMState *env, int32_t num, int32_t den)
9122 {
9123     if (den == 0) {
9124         handle_possible_div0_trap(env, GETPC());
9125         return 0;
9126     }
9127     if (num == INT_MIN && den == -1) {
9128         return INT_MIN;
9129     }
9130     return num / den;
9131 }
9132 
9133 uint32_t HELPER(udiv)(CPUARMState *env, uint32_t num, uint32_t den)
9134 {
9135     if (den == 0) {
9136         handle_possible_div0_trap(env, GETPC());
9137         return 0;
9138     }
9139     return num / den;
9140 }
9141 
9142 uint32_t HELPER(rbit)(uint32_t x)
9143 {
9144     return revbit32(x);
9145 }
9146 
9147 #ifdef CONFIG_USER_ONLY
9148 
9149 static void switch_mode(CPUARMState *env, int mode)
9150 {
9151     ARMCPU *cpu = env_archcpu(env);
9152 
9153     if (mode != ARM_CPU_MODE_USR) {
9154         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
9155     }
9156 }
9157 
9158 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9159                                  uint32_t cur_el, bool secure)
9160 {
9161     return 1;
9162 }
9163 
9164 void aarch64_sync_64_to_32(CPUARMState *env)
9165 {
9166     g_assert_not_reached();
9167 }
9168 
9169 #else
9170 
9171 static void switch_mode(CPUARMState *env, int mode)
9172 {
9173     int old_mode;
9174     int i;
9175 
9176     old_mode = env->uncached_cpsr & CPSR_M;
9177     if (mode == old_mode)
9178         return;
9179 
9180     if (old_mode == ARM_CPU_MODE_FIQ) {
9181         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
9182         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
9183     } else if (mode == ARM_CPU_MODE_FIQ) {
9184         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
9185         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
9186     }
9187 
9188     i = bank_number(old_mode);
9189     env->banked_r13[i] = env->regs[13];
9190     env->banked_spsr[i] = env->spsr;
9191 
9192     i = bank_number(mode);
9193     env->regs[13] = env->banked_r13[i];
9194     env->spsr = env->banked_spsr[i];
9195 
9196     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
9197     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
9198 }
9199 
9200 /* Physical Interrupt Target EL Lookup Table
9201  *
9202  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
9203  *
9204  * The below multi-dimensional table is used for looking up the target
9205  * exception level given numerous condition criteria.  Specifically, the
9206  * target EL is based on SCR and HCR routing controls as well as the
9207  * currently executing EL and secure state.
9208  *
9209  *    Dimensions:
9210  *    target_el_table[2][2][2][2][2][4]
9211  *                    |  |  |  |  |  +--- Current EL
9212  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
9213  *                    |  |  |  +--------- HCR mask override
9214  *                    |  |  +------------ SCR exec state control
9215  *                    |  +--------------- SCR mask override
9216  *                    +------------------ 32-bit(0)/64-bit(1) EL3
9217  *
9218  *    The table values are as such:
9219  *    0-3 = EL0-EL3
9220  *     -1 = Cannot occur
9221  *
9222  * The ARM ARM target EL table includes entries indicating that an "exception
9223  * is not taken".  The two cases where this is applicable are:
9224  *    1) An exception is taken from EL3 but the SCR does not have the exception
9225  *    routed to EL3.
9226  *    2) An exception is taken from EL2 but the HCR does not have the exception
9227  *    routed to EL2.
9228  * In these two cases, the below table contain a target of EL1.  This value is
9229  * returned as it is expected that the consumer of the table data will check
9230  * for "target EL >= current EL" to ensure the exception is not taken.
9231  *
9232  *            SCR     HCR
9233  *         64  EA     AMO                 From
9234  *        BIT IRQ     IMO      Non-secure         Secure
9235  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
9236  */
9237 static const int8_t target_el_table[2][2][2][2][2][4] = {
9238     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9239        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
9240       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9241        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
9242      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9243        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
9244       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9245        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
9246     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
9247        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 2,  2, -1,  1 },},},
9248       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1,  1,  1 },},
9249        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 2,  2,  2,  1 },},},},
9250      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
9251        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
9252       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},
9253        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},},},},
9254 };
9255 
9256 /*
9257  * Determine the target EL for physical exceptions
9258  */
9259 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9260                                  uint32_t cur_el, bool secure)
9261 {
9262     CPUARMState *env = cs->env_ptr;
9263     bool rw;
9264     bool scr;
9265     bool hcr;
9266     int target_el;
9267     /* Is the highest EL AArch64? */
9268     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
9269     uint64_t hcr_el2;
9270 
9271     if (arm_feature(env, ARM_FEATURE_EL3)) {
9272         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
9273     } else {
9274         /* Either EL2 is the highest EL (and so the EL2 register width
9275          * is given by is64); or there is no EL2 or EL3, in which case
9276          * the value of 'rw' does not affect the table lookup anyway.
9277          */
9278         rw = is64;
9279     }
9280 
9281     hcr_el2 = arm_hcr_el2_eff(env);
9282     switch (excp_idx) {
9283     case EXCP_IRQ:
9284         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
9285         hcr = hcr_el2 & HCR_IMO;
9286         break;
9287     case EXCP_FIQ:
9288         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
9289         hcr = hcr_el2 & HCR_FMO;
9290         break;
9291     default:
9292         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
9293         hcr = hcr_el2 & HCR_AMO;
9294         break;
9295     };
9296 
9297     /*
9298      * For these purposes, TGE and AMO/IMO/FMO both force the
9299      * interrupt to EL2.  Fold TGE into the bit extracted above.
9300      */
9301     hcr |= (hcr_el2 & HCR_TGE) != 0;
9302 
9303     /* Perform a table-lookup for the target EL given the current state */
9304     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
9305 
9306     assert(target_el > 0);
9307 
9308     return target_el;
9309 }
9310 
9311 void arm_log_exception(CPUState *cs)
9312 {
9313     int idx = cs->exception_index;
9314 
9315     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9316         const char *exc = NULL;
9317         static const char * const excnames[] = {
9318             [EXCP_UDEF] = "Undefined Instruction",
9319             [EXCP_SWI] = "SVC",
9320             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9321             [EXCP_DATA_ABORT] = "Data Abort",
9322             [EXCP_IRQ] = "IRQ",
9323             [EXCP_FIQ] = "FIQ",
9324             [EXCP_BKPT] = "Breakpoint",
9325             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9326             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9327             [EXCP_HVC] = "Hypervisor Call",
9328             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9329             [EXCP_SMC] = "Secure Monitor Call",
9330             [EXCP_VIRQ] = "Virtual IRQ",
9331             [EXCP_VFIQ] = "Virtual FIQ",
9332             [EXCP_SEMIHOST] = "Semihosting call",
9333             [EXCP_NOCP] = "v7M NOCP UsageFault",
9334             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9335             [EXCP_STKOF] = "v8M STKOF UsageFault",
9336             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9337             [EXCP_LSERR] = "v8M LSERR UsageFault",
9338             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9339             [EXCP_DIVBYZERO] = "v7M DIVBYZERO UsageFault",
9340             [EXCP_VSERR] = "Virtual SERR",
9341         };
9342 
9343         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9344             exc = excnames[idx];
9345         }
9346         if (!exc) {
9347             exc = "unknown";
9348         }
9349         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s] on CPU %d\n",
9350                       idx, exc, cs->cpu_index);
9351     }
9352 }
9353 
9354 /*
9355  * Function used to synchronize QEMU's AArch64 register set with AArch32
9356  * register set.  This is necessary when switching between AArch32 and AArch64
9357  * execution state.
9358  */
9359 void aarch64_sync_32_to_64(CPUARMState *env)
9360 {
9361     int i;
9362     uint32_t mode = env->uncached_cpsr & CPSR_M;
9363 
9364     /* We can blanket copy R[0:7] to X[0:7] */
9365     for (i = 0; i < 8; i++) {
9366         env->xregs[i] = env->regs[i];
9367     }
9368 
9369     /*
9370      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9371      * Otherwise, they come from the banked user regs.
9372      */
9373     if (mode == ARM_CPU_MODE_FIQ) {
9374         for (i = 8; i < 13; i++) {
9375             env->xregs[i] = env->usr_regs[i - 8];
9376         }
9377     } else {
9378         for (i = 8; i < 13; i++) {
9379             env->xregs[i] = env->regs[i];
9380         }
9381     }
9382 
9383     /*
9384      * Registers x13-x23 are the various mode SP and FP registers. Registers
9385      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9386      * from the mode banked register.
9387      */
9388     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9389         env->xregs[13] = env->regs[13];
9390         env->xregs[14] = env->regs[14];
9391     } else {
9392         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9393         /* HYP is an exception in that it is copied from r14 */
9394         if (mode == ARM_CPU_MODE_HYP) {
9395             env->xregs[14] = env->regs[14];
9396         } else {
9397             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9398         }
9399     }
9400 
9401     if (mode == ARM_CPU_MODE_HYP) {
9402         env->xregs[15] = env->regs[13];
9403     } else {
9404         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9405     }
9406 
9407     if (mode == ARM_CPU_MODE_IRQ) {
9408         env->xregs[16] = env->regs[14];
9409         env->xregs[17] = env->regs[13];
9410     } else {
9411         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9412         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9413     }
9414 
9415     if (mode == ARM_CPU_MODE_SVC) {
9416         env->xregs[18] = env->regs[14];
9417         env->xregs[19] = env->regs[13];
9418     } else {
9419         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9420         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9421     }
9422 
9423     if (mode == ARM_CPU_MODE_ABT) {
9424         env->xregs[20] = env->regs[14];
9425         env->xregs[21] = env->regs[13];
9426     } else {
9427         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9428         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9429     }
9430 
9431     if (mode == ARM_CPU_MODE_UND) {
9432         env->xregs[22] = env->regs[14];
9433         env->xregs[23] = env->regs[13];
9434     } else {
9435         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9436         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9437     }
9438 
9439     /*
9440      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9441      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9442      * FIQ bank for r8-r14.
9443      */
9444     if (mode == ARM_CPU_MODE_FIQ) {
9445         for (i = 24; i < 31; i++) {
9446             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9447         }
9448     } else {
9449         for (i = 24; i < 29; i++) {
9450             env->xregs[i] = env->fiq_regs[i - 24];
9451         }
9452         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9453         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9454     }
9455 
9456     env->pc = env->regs[15];
9457 }
9458 
9459 /*
9460  * Function used to synchronize QEMU's AArch32 register set with AArch64
9461  * register set.  This is necessary when switching between AArch32 and AArch64
9462  * execution state.
9463  */
9464 void aarch64_sync_64_to_32(CPUARMState *env)
9465 {
9466     int i;
9467     uint32_t mode = env->uncached_cpsr & CPSR_M;
9468 
9469     /* We can blanket copy X[0:7] to R[0:7] */
9470     for (i = 0; i < 8; i++) {
9471         env->regs[i] = env->xregs[i];
9472     }
9473 
9474     /*
9475      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9476      * Otherwise, we copy x8-x12 into the banked user regs.
9477      */
9478     if (mode == ARM_CPU_MODE_FIQ) {
9479         for (i = 8; i < 13; i++) {
9480             env->usr_regs[i - 8] = env->xregs[i];
9481         }
9482     } else {
9483         for (i = 8; i < 13; i++) {
9484             env->regs[i] = env->xregs[i];
9485         }
9486     }
9487 
9488     /*
9489      * Registers r13 & r14 depend on the current mode.
9490      * If we are in a given mode, we copy the corresponding x registers to r13
9491      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9492      * for the mode.
9493      */
9494     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9495         env->regs[13] = env->xregs[13];
9496         env->regs[14] = env->xregs[14];
9497     } else {
9498         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9499 
9500         /*
9501          * HYP is an exception in that it does not have its own banked r14 but
9502          * shares the USR r14
9503          */
9504         if (mode == ARM_CPU_MODE_HYP) {
9505             env->regs[14] = env->xregs[14];
9506         } else {
9507             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9508         }
9509     }
9510 
9511     if (mode == ARM_CPU_MODE_HYP) {
9512         env->regs[13] = env->xregs[15];
9513     } else {
9514         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9515     }
9516 
9517     if (mode == ARM_CPU_MODE_IRQ) {
9518         env->regs[14] = env->xregs[16];
9519         env->regs[13] = env->xregs[17];
9520     } else {
9521         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9522         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9523     }
9524 
9525     if (mode == ARM_CPU_MODE_SVC) {
9526         env->regs[14] = env->xregs[18];
9527         env->regs[13] = env->xregs[19];
9528     } else {
9529         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9530         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9531     }
9532 
9533     if (mode == ARM_CPU_MODE_ABT) {
9534         env->regs[14] = env->xregs[20];
9535         env->regs[13] = env->xregs[21];
9536     } else {
9537         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9538         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9539     }
9540 
9541     if (mode == ARM_CPU_MODE_UND) {
9542         env->regs[14] = env->xregs[22];
9543         env->regs[13] = env->xregs[23];
9544     } else {
9545         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9546         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9547     }
9548 
9549     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9550      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9551      * FIQ bank for r8-r14.
9552      */
9553     if (mode == ARM_CPU_MODE_FIQ) {
9554         for (i = 24; i < 31; i++) {
9555             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9556         }
9557     } else {
9558         for (i = 24; i < 29; i++) {
9559             env->fiq_regs[i - 24] = env->xregs[i];
9560         }
9561         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9562         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9563     }
9564 
9565     env->regs[15] = env->pc;
9566 }
9567 
9568 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9569                                    uint32_t mask, uint32_t offset,
9570                                    uint32_t newpc)
9571 {
9572     int new_el;
9573 
9574     /* Change the CPU state so as to actually take the exception. */
9575     switch_mode(env, new_mode);
9576 
9577     /*
9578      * For exceptions taken to AArch32 we must clear the SS bit in both
9579      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9580      */
9581     env->pstate &= ~PSTATE_SS;
9582     env->spsr = cpsr_read(env);
9583     /* Clear IT bits.  */
9584     env->condexec_bits = 0;
9585     /* Switch to the new mode, and to the correct instruction set.  */
9586     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9587 
9588     /* This must be after mode switching. */
9589     new_el = arm_current_el(env);
9590 
9591     /* Set new mode endianness */
9592     env->uncached_cpsr &= ~CPSR_E;
9593     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9594         env->uncached_cpsr |= CPSR_E;
9595     }
9596     /* J and IL must always be cleared for exception entry */
9597     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9598     env->daif |= mask;
9599 
9600     if (cpu_isar_feature(aa32_ssbs, env_archcpu(env))) {
9601         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_32) {
9602             env->uncached_cpsr |= CPSR_SSBS;
9603         } else {
9604             env->uncached_cpsr &= ~CPSR_SSBS;
9605         }
9606     }
9607 
9608     if (new_mode == ARM_CPU_MODE_HYP) {
9609         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9610         env->elr_el[2] = env->regs[15];
9611     } else {
9612         /* CPSR.PAN is normally preserved preserved unless...  */
9613         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9614             switch (new_el) {
9615             case 3:
9616                 if (!arm_is_secure_below_el3(env)) {
9617                     /* ... the target is EL3, from non-secure state.  */
9618                     env->uncached_cpsr &= ~CPSR_PAN;
9619                     break;
9620                 }
9621                 /* ... the target is EL3, from secure state ... */
9622                 /* fall through */
9623             case 1:
9624                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9625                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9626                     env->uncached_cpsr |= CPSR_PAN;
9627                 }
9628                 break;
9629             }
9630         }
9631         /*
9632          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9633          * and we should just guard the thumb mode on V4
9634          */
9635         if (arm_feature(env, ARM_FEATURE_V4T)) {
9636             env->thumb =
9637                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9638         }
9639         env->regs[14] = env->regs[15] + offset;
9640     }
9641     env->regs[15] = newpc;
9642     arm_rebuild_hflags(env);
9643 }
9644 
9645 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9646 {
9647     /*
9648      * Handle exception entry to Hyp mode; this is sufficiently
9649      * different to entry to other AArch32 modes that we handle it
9650      * separately here.
9651      *
9652      * The vector table entry used is always the 0x14 Hyp mode entry point,
9653      * unless this is an UNDEF/SVC/HVC/abort taken from Hyp to Hyp.
9654      * The offset applied to the preferred return address is always zero
9655      * (see DDI0487C.a section G1.12.3).
9656      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9657      */
9658     uint32_t addr, mask;
9659     ARMCPU *cpu = ARM_CPU(cs);
9660     CPUARMState *env = &cpu->env;
9661 
9662     switch (cs->exception_index) {
9663     case EXCP_UDEF:
9664         addr = 0x04;
9665         break;
9666     case EXCP_SWI:
9667         addr = 0x08;
9668         break;
9669     case EXCP_BKPT:
9670         /* Fall through to prefetch abort.  */
9671     case EXCP_PREFETCH_ABORT:
9672         env->cp15.ifar_s = env->exception.vaddress;
9673         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9674                       (uint32_t)env->exception.vaddress);
9675         addr = 0x0c;
9676         break;
9677     case EXCP_DATA_ABORT:
9678         env->cp15.dfar_s = env->exception.vaddress;
9679         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9680                       (uint32_t)env->exception.vaddress);
9681         addr = 0x10;
9682         break;
9683     case EXCP_IRQ:
9684         addr = 0x18;
9685         break;
9686     case EXCP_FIQ:
9687         addr = 0x1c;
9688         break;
9689     case EXCP_HVC:
9690         addr = 0x08;
9691         break;
9692     case EXCP_HYP_TRAP:
9693         addr = 0x14;
9694         break;
9695     default:
9696         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9697     }
9698 
9699     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9700         if (!arm_feature(env, ARM_FEATURE_V8)) {
9701             /*
9702              * QEMU syndrome values are v8-style. v7 has the IL bit
9703              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9704              * If this is a v7 CPU, squash the IL bit in those cases.
9705              */
9706             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9707                 (cs->exception_index == EXCP_DATA_ABORT &&
9708                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9709                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9710                 env->exception.syndrome &= ~ARM_EL_IL;
9711             }
9712         }
9713         env->cp15.esr_el[2] = env->exception.syndrome;
9714     }
9715 
9716     if (arm_current_el(env) != 2 && addr < 0x14) {
9717         addr = 0x14;
9718     }
9719 
9720     mask = 0;
9721     if (!(env->cp15.scr_el3 & SCR_EA)) {
9722         mask |= CPSR_A;
9723     }
9724     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9725         mask |= CPSR_I;
9726     }
9727     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9728         mask |= CPSR_F;
9729     }
9730 
9731     addr += env->cp15.hvbar;
9732 
9733     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9734 }
9735 
9736 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9737 {
9738     ARMCPU *cpu = ARM_CPU(cs);
9739     CPUARMState *env = &cpu->env;
9740     uint32_t addr;
9741     uint32_t mask;
9742     int new_mode;
9743     uint32_t offset;
9744     uint32_t moe;
9745 
9746     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9747     switch (syn_get_ec(env->exception.syndrome)) {
9748     case EC_BREAKPOINT:
9749     case EC_BREAKPOINT_SAME_EL:
9750         moe = 1;
9751         break;
9752     case EC_WATCHPOINT:
9753     case EC_WATCHPOINT_SAME_EL:
9754         moe = 10;
9755         break;
9756     case EC_AA32_BKPT:
9757         moe = 3;
9758         break;
9759     case EC_VECTORCATCH:
9760         moe = 5;
9761         break;
9762     default:
9763         moe = 0;
9764         break;
9765     }
9766 
9767     if (moe) {
9768         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9769     }
9770 
9771     if (env->exception.target_el == 2) {
9772         arm_cpu_do_interrupt_aarch32_hyp(cs);
9773         return;
9774     }
9775 
9776     switch (cs->exception_index) {
9777     case EXCP_UDEF:
9778         new_mode = ARM_CPU_MODE_UND;
9779         addr = 0x04;
9780         mask = CPSR_I;
9781         if (env->thumb)
9782             offset = 2;
9783         else
9784             offset = 4;
9785         break;
9786     case EXCP_SWI:
9787         new_mode = ARM_CPU_MODE_SVC;
9788         addr = 0x08;
9789         mask = CPSR_I;
9790         /* The PC already points to the next instruction.  */
9791         offset = 0;
9792         break;
9793     case EXCP_BKPT:
9794         /* Fall through to prefetch abort.  */
9795     case EXCP_PREFETCH_ABORT:
9796         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9797         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9798         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9799                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9800         new_mode = ARM_CPU_MODE_ABT;
9801         addr = 0x0c;
9802         mask = CPSR_A | CPSR_I;
9803         offset = 4;
9804         break;
9805     case EXCP_DATA_ABORT:
9806         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9807         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9808         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9809                       env->exception.fsr,
9810                       (uint32_t)env->exception.vaddress);
9811         new_mode = ARM_CPU_MODE_ABT;
9812         addr = 0x10;
9813         mask = CPSR_A | CPSR_I;
9814         offset = 8;
9815         break;
9816     case EXCP_IRQ:
9817         new_mode = ARM_CPU_MODE_IRQ;
9818         addr = 0x18;
9819         /* Disable IRQ and imprecise data aborts.  */
9820         mask = CPSR_A | CPSR_I;
9821         offset = 4;
9822         if (env->cp15.scr_el3 & SCR_IRQ) {
9823             /* IRQ routed to monitor mode */
9824             new_mode = ARM_CPU_MODE_MON;
9825             mask |= CPSR_F;
9826         }
9827         break;
9828     case EXCP_FIQ:
9829         new_mode = ARM_CPU_MODE_FIQ;
9830         addr = 0x1c;
9831         /* Disable FIQ, IRQ and imprecise data aborts.  */
9832         mask = CPSR_A | CPSR_I | CPSR_F;
9833         if (env->cp15.scr_el3 & SCR_FIQ) {
9834             /* FIQ routed to monitor mode */
9835             new_mode = ARM_CPU_MODE_MON;
9836         }
9837         offset = 4;
9838         break;
9839     case EXCP_VIRQ:
9840         new_mode = ARM_CPU_MODE_IRQ;
9841         addr = 0x18;
9842         /* Disable IRQ and imprecise data aborts.  */
9843         mask = CPSR_A | CPSR_I;
9844         offset = 4;
9845         break;
9846     case EXCP_VFIQ:
9847         new_mode = ARM_CPU_MODE_FIQ;
9848         addr = 0x1c;
9849         /* Disable FIQ, IRQ and imprecise data aborts.  */
9850         mask = CPSR_A | CPSR_I | CPSR_F;
9851         offset = 4;
9852         break;
9853     case EXCP_VSERR:
9854         {
9855             /*
9856              * Note that this is reported as a data abort, but the DFAR
9857              * has an UNKNOWN value.  Construct the SError syndrome from
9858              * AET and ExT fields.
9859              */
9860             ARMMMUFaultInfo fi = { .type = ARMFault_AsyncExternal, };
9861 
9862             if (extended_addresses_enabled(env)) {
9863                 env->exception.fsr = arm_fi_to_lfsc(&fi);
9864             } else {
9865                 env->exception.fsr = arm_fi_to_sfsc(&fi);
9866             }
9867             env->exception.fsr |= env->cp15.vsesr_el2 & 0xd000;
9868             A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9869             qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x\n",
9870                           env->exception.fsr);
9871 
9872             new_mode = ARM_CPU_MODE_ABT;
9873             addr = 0x10;
9874             mask = CPSR_A | CPSR_I;
9875             offset = 8;
9876         }
9877         break;
9878     case EXCP_SMC:
9879         new_mode = ARM_CPU_MODE_MON;
9880         addr = 0x08;
9881         mask = CPSR_A | CPSR_I | CPSR_F;
9882         offset = 0;
9883         break;
9884     default:
9885         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9886         return; /* Never happens.  Keep compiler happy.  */
9887     }
9888 
9889     if (new_mode == ARM_CPU_MODE_MON) {
9890         addr += env->cp15.mvbar;
9891     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9892         /* High vectors. When enabled, base address cannot be remapped. */
9893         addr += 0xffff0000;
9894     } else {
9895         /* ARM v7 architectures provide a vector base address register to remap
9896          * the interrupt vector table.
9897          * This register is only followed in non-monitor mode, and is banked.
9898          * Note: only bits 31:5 are valid.
9899          */
9900         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9901     }
9902 
9903     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9904         env->cp15.scr_el3 &= ~SCR_NS;
9905     }
9906 
9907     take_aarch32_exception(env, new_mode, mask, offset, addr);
9908 }
9909 
9910 static int aarch64_regnum(CPUARMState *env, int aarch32_reg)
9911 {
9912     /*
9913      * Return the register number of the AArch64 view of the AArch32
9914      * register @aarch32_reg. The CPUARMState CPSR is assumed to still
9915      * be that of the AArch32 mode the exception came from.
9916      */
9917     int mode = env->uncached_cpsr & CPSR_M;
9918 
9919     switch (aarch32_reg) {
9920     case 0 ... 7:
9921         return aarch32_reg;
9922     case 8 ... 12:
9923         return mode == ARM_CPU_MODE_FIQ ? aarch32_reg + 16 : aarch32_reg;
9924     case 13:
9925         switch (mode) {
9926         case ARM_CPU_MODE_USR:
9927         case ARM_CPU_MODE_SYS:
9928             return 13;
9929         case ARM_CPU_MODE_HYP:
9930             return 15;
9931         case ARM_CPU_MODE_IRQ:
9932             return 17;
9933         case ARM_CPU_MODE_SVC:
9934             return 19;
9935         case ARM_CPU_MODE_ABT:
9936             return 21;
9937         case ARM_CPU_MODE_UND:
9938             return 23;
9939         case ARM_CPU_MODE_FIQ:
9940             return 29;
9941         default:
9942             g_assert_not_reached();
9943         }
9944     case 14:
9945         switch (mode) {
9946         case ARM_CPU_MODE_USR:
9947         case ARM_CPU_MODE_SYS:
9948         case ARM_CPU_MODE_HYP:
9949             return 14;
9950         case ARM_CPU_MODE_IRQ:
9951             return 16;
9952         case ARM_CPU_MODE_SVC:
9953             return 18;
9954         case ARM_CPU_MODE_ABT:
9955             return 20;
9956         case ARM_CPU_MODE_UND:
9957             return 22;
9958         case ARM_CPU_MODE_FIQ:
9959             return 30;
9960         default:
9961             g_assert_not_reached();
9962         }
9963     case 15:
9964         return 31;
9965     default:
9966         g_assert_not_reached();
9967     }
9968 }
9969 
9970 static uint32_t cpsr_read_for_spsr_elx(CPUARMState *env)
9971 {
9972     uint32_t ret = cpsr_read(env);
9973 
9974     /* Move DIT to the correct location for SPSR_ELx */
9975     if (ret & CPSR_DIT) {
9976         ret &= ~CPSR_DIT;
9977         ret |= PSTATE_DIT;
9978     }
9979     /* Merge PSTATE.SS into SPSR_ELx */
9980     ret |= env->pstate & PSTATE_SS;
9981 
9982     return ret;
9983 }
9984 
9985 /* Handle exception entry to a target EL which is using AArch64 */
9986 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
9987 {
9988     ARMCPU *cpu = ARM_CPU(cs);
9989     CPUARMState *env = &cpu->env;
9990     unsigned int new_el = env->exception.target_el;
9991     target_ulong addr = env->cp15.vbar_el[new_el];
9992     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
9993     unsigned int old_mode;
9994     unsigned int cur_el = arm_current_el(env);
9995     int rt;
9996 
9997     /*
9998      * Note that new_el can never be 0.  If cur_el is 0, then
9999      * el0_a64 is is_a64(), else el0_a64 is ignored.
10000      */
10001     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
10002 
10003     if (cur_el < new_el) {
10004         /* Entry vector offset depends on whether the implemented EL
10005          * immediately lower than the target level is using AArch32 or AArch64
10006          */
10007         bool is_aa64;
10008         uint64_t hcr;
10009 
10010         switch (new_el) {
10011         case 3:
10012             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
10013             break;
10014         case 2:
10015             hcr = arm_hcr_el2_eff(env);
10016             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
10017                 is_aa64 = (hcr & HCR_RW) != 0;
10018                 break;
10019             }
10020             /* fall through */
10021         case 1:
10022             is_aa64 = is_a64(env);
10023             break;
10024         default:
10025             g_assert_not_reached();
10026         }
10027 
10028         if (is_aa64) {
10029             addr += 0x400;
10030         } else {
10031             addr += 0x600;
10032         }
10033     } else if (pstate_read(env) & PSTATE_SP) {
10034         addr += 0x200;
10035     }
10036 
10037     switch (cs->exception_index) {
10038     case EXCP_PREFETCH_ABORT:
10039     case EXCP_DATA_ABORT:
10040         env->cp15.far_el[new_el] = env->exception.vaddress;
10041         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
10042                       env->cp15.far_el[new_el]);
10043         /* fall through */
10044     case EXCP_BKPT:
10045     case EXCP_UDEF:
10046     case EXCP_SWI:
10047     case EXCP_HVC:
10048     case EXCP_HYP_TRAP:
10049     case EXCP_SMC:
10050         switch (syn_get_ec(env->exception.syndrome)) {
10051         case EC_ADVSIMDFPACCESSTRAP:
10052             /*
10053              * QEMU internal FP/SIMD syndromes from AArch32 include the
10054              * TA and coproc fields which are only exposed if the exception
10055              * is taken to AArch32 Hyp mode. Mask them out to get a valid
10056              * AArch64 format syndrome.
10057              */
10058             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
10059             break;
10060         case EC_CP14RTTRAP:
10061         case EC_CP15RTTRAP:
10062         case EC_CP14DTTRAP:
10063             /*
10064              * For a trap on AArch32 MRC/MCR/LDC/STC the Rt field is currently
10065              * the raw register field from the insn; when taking this to
10066              * AArch64 we must convert it to the AArch64 view of the register
10067              * number. Notice that we read a 4-bit AArch32 register number and
10068              * write back a 5-bit AArch64 one.
10069              */
10070             rt = extract32(env->exception.syndrome, 5, 4);
10071             rt = aarch64_regnum(env, rt);
10072             env->exception.syndrome = deposit32(env->exception.syndrome,
10073                                                 5, 5, rt);
10074             break;
10075         case EC_CP15RRTTRAP:
10076         case EC_CP14RRTTRAP:
10077             /* Similarly for MRRC/MCRR traps for Rt and Rt2 fields */
10078             rt = extract32(env->exception.syndrome, 5, 4);
10079             rt = aarch64_regnum(env, rt);
10080             env->exception.syndrome = deposit32(env->exception.syndrome,
10081                                                 5, 5, rt);
10082             rt = extract32(env->exception.syndrome, 10, 4);
10083             rt = aarch64_regnum(env, rt);
10084             env->exception.syndrome = deposit32(env->exception.syndrome,
10085                                                 10, 5, rt);
10086             break;
10087         }
10088         env->cp15.esr_el[new_el] = env->exception.syndrome;
10089         break;
10090     case EXCP_IRQ:
10091     case EXCP_VIRQ:
10092         addr += 0x80;
10093         break;
10094     case EXCP_FIQ:
10095     case EXCP_VFIQ:
10096         addr += 0x100;
10097         break;
10098     case EXCP_VSERR:
10099         addr += 0x180;
10100         /* Construct the SError syndrome from IDS and ISS fields. */
10101         env->exception.syndrome = syn_serror(env->cp15.vsesr_el2 & 0x1ffffff);
10102         env->cp15.esr_el[new_el] = env->exception.syndrome;
10103         break;
10104     default:
10105         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10106     }
10107 
10108     if (is_a64(env)) {
10109         old_mode = pstate_read(env);
10110         aarch64_save_sp(env, arm_current_el(env));
10111         env->elr_el[new_el] = env->pc;
10112     } else {
10113         old_mode = cpsr_read_for_spsr_elx(env);
10114         env->elr_el[new_el] = env->regs[15];
10115 
10116         aarch64_sync_32_to_64(env);
10117 
10118         env->condexec_bits = 0;
10119     }
10120     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
10121 
10122     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
10123                   env->elr_el[new_el]);
10124 
10125     if (cpu_isar_feature(aa64_pan, cpu)) {
10126         /* The value of PSTATE.PAN is normally preserved, except when ... */
10127         new_mode |= old_mode & PSTATE_PAN;
10128         switch (new_el) {
10129         case 2:
10130             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
10131             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
10132                 != (HCR_E2H | HCR_TGE)) {
10133                 break;
10134             }
10135             /* fall through */
10136         case 1:
10137             /* ... the target is EL1 ... */
10138             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
10139             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
10140                 new_mode |= PSTATE_PAN;
10141             }
10142             break;
10143         }
10144     }
10145     if (cpu_isar_feature(aa64_mte, cpu)) {
10146         new_mode |= PSTATE_TCO;
10147     }
10148 
10149     if (cpu_isar_feature(aa64_ssbs, cpu)) {
10150         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_64) {
10151             new_mode |= PSTATE_SSBS;
10152         } else {
10153             new_mode &= ~PSTATE_SSBS;
10154         }
10155     }
10156 
10157     pstate_write(env, PSTATE_DAIF | new_mode);
10158     env->aarch64 = true;
10159     aarch64_restore_sp(env, new_el);
10160     helper_rebuild_hflags_a64(env, new_el);
10161 
10162     env->pc = addr;
10163 
10164     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10165                   new_el, env->pc, pstate_read(env));
10166 }
10167 
10168 /*
10169  * Do semihosting call and set the appropriate return value. All the
10170  * permission and validity checks have been done at translate time.
10171  *
10172  * We only see semihosting exceptions in TCG only as they are not
10173  * trapped to the hypervisor in KVM.
10174  */
10175 #ifdef CONFIG_TCG
10176 static void handle_semihosting(CPUState *cs)
10177 {
10178     ARMCPU *cpu = ARM_CPU(cs);
10179     CPUARMState *env = &cpu->env;
10180 
10181     if (is_a64(env)) {
10182         qemu_log_mask(CPU_LOG_INT,
10183                       "...handling as semihosting call 0x%" PRIx64 "\n",
10184                       env->xregs[0]);
10185         env->xregs[0] = do_common_semihosting(cs);
10186         env->pc += 4;
10187     } else {
10188         qemu_log_mask(CPU_LOG_INT,
10189                       "...handling as semihosting call 0x%x\n",
10190                       env->regs[0]);
10191         env->regs[0] = do_common_semihosting(cs);
10192         env->regs[15] += env->thumb ? 2 : 4;
10193     }
10194 }
10195 #endif
10196 
10197 /* Handle a CPU exception for A and R profile CPUs.
10198  * Do any appropriate logging, handle PSCI calls, and then hand off
10199  * to the AArch64-entry or AArch32-entry function depending on the
10200  * target exception level's register width.
10201  *
10202  * Note: this is used for both TCG (as the do_interrupt tcg op),
10203  *       and KVM to re-inject guest debug exceptions, and to
10204  *       inject a Synchronous-External-Abort.
10205  */
10206 void arm_cpu_do_interrupt(CPUState *cs)
10207 {
10208     ARMCPU *cpu = ARM_CPU(cs);
10209     CPUARMState *env = &cpu->env;
10210     unsigned int new_el = env->exception.target_el;
10211 
10212     assert(!arm_feature(env, ARM_FEATURE_M));
10213 
10214     arm_log_exception(cs);
10215     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10216                   new_el);
10217     if (qemu_loglevel_mask(CPU_LOG_INT)
10218         && !excp_is_internal(cs->exception_index)) {
10219         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10220                       syn_get_ec(env->exception.syndrome),
10221                       env->exception.syndrome);
10222     }
10223 
10224     if (arm_is_psci_call(cpu, cs->exception_index)) {
10225         arm_handle_psci_call(cpu);
10226         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10227         return;
10228     }
10229 
10230     /*
10231      * Semihosting semantics depend on the register width of the code
10232      * that caused the exception, not the target exception level, so
10233      * must be handled here.
10234      */
10235 #ifdef CONFIG_TCG
10236     if (cs->exception_index == EXCP_SEMIHOST) {
10237         handle_semihosting(cs);
10238         return;
10239     }
10240 #endif
10241 
10242     /* Hooks may change global state so BQL should be held, also the
10243      * BQL needs to be held for any modification of
10244      * cs->interrupt_request.
10245      */
10246     g_assert(qemu_mutex_iothread_locked());
10247 
10248     arm_call_pre_el_change_hook(cpu);
10249 
10250     assert(!excp_is_internal(cs->exception_index));
10251     if (arm_el_is_aa64(env, new_el)) {
10252         arm_cpu_do_interrupt_aarch64(cs);
10253     } else {
10254         arm_cpu_do_interrupt_aarch32(cs);
10255     }
10256 
10257     arm_call_el_change_hook(cpu);
10258 
10259     if (!kvm_enabled()) {
10260         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10261     }
10262 }
10263 #endif /* !CONFIG_USER_ONLY */
10264 
10265 uint64_t arm_sctlr(CPUARMState *env, int el)
10266 {
10267     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
10268     if (el == 0) {
10269         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
10270         el = (mmu_idx == ARMMMUIdx_E20_0 || mmu_idx == ARMMMUIdx_SE20_0)
10271              ? 2 : 1;
10272     }
10273     return env->cp15.sctlr_el[el];
10274 }
10275 
10276 /* Return the SCTLR value which controls this address translation regime */
10277 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10278 {
10279     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10280 }
10281 
10282 #ifndef CONFIG_USER_ONLY
10283 
10284 /* Return true if the specified stage of address translation is disabled */
10285 static inline bool regime_translation_disabled(CPUARMState *env,
10286                                                ARMMMUIdx mmu_idx)
10287 {
10288     uint64_t hcr_el2;
10289 
10290     if (arm_feature(env, ARM_FEATURE_M)) {
10291         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10292                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10293         case R_V7M_MPU_CTRL_ENABLE_MASK:
10294             /* Enabled, but not for HardFault and NMI */
10295             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10296         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10297             /* Enabled for all cases */
10298             return false;
10299         case 0:
10300         default:
10301             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10302              * we warned about that in armv7m_nvic.c when the guest set it.
10303              */
10304             return true;
10305         }
10306     }
10307 
10308     hcr_el2 = arm_hcr_el2_eff(env);
10309 
10310     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10311         /* HCR.DC means HCR.VM behaves as 1 */
10312         return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10313     }
10314 
10315     if (hcr_el2 & HCR_TGE) {
10316         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10317         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10318             return true;
10319         }
10320     }
10321 
10322     if ((hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
10323         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10324         return true;
10325     }
10326 
10327     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10328 }
10329 
10330 static inline bool regime_translation_big_endian(CPUARMState *env,
10331                                                  ARMMMUIdx mmu_idx)
10332 {
10333     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10334 }
10335 
10336 /* Return the TTBR associated with this translation regime */
10337 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10338                                    int ttbrn)
10339 {
10340     if (mmu_idx == ARMMMUIdx_Stage2) {
10341         return env->cp15.vttbr_el2;
10342     }
10343     if (mmu_idx == ARMMMUIdx_Stage2_S) {
10344         return env->cp15.vsttbr_el2;
10345     }
10346     if (ttbrn == 0) {
10347         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10348     } else {
10349         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10350     }
10351 }
10352 
10353 #endif /* !CONFIG_USER_ONLY */
10354 
10355 /* Convert a possible stage1+2 MMU index into the appropriate
10356  * stage 1 MMU index
10357  */
10358 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10359 {
10360     switch (mmu_idx) {
10361     case ARMMMUIdx_SE10_0:
10362         return ARMMMUIdx_Stage1_SE0;
10363     case ARMMMUIdx_SE10_1:
10364         return ARMMMUIdx_Stage1_SE1;
10365     case ARMMMUIdx_SE10_1_PAN:
10366         return ARMMMUIdx_Stage1_SE1_PAN;
10367     case ARMMMUIdx_E10_0:
10368         return ARMMMUIdx_Stage1_E0;
10369     case ARMMMUIdx_E10_1:
10370         return ARMMMUIdx_Stage1_E1;
10371     case ARMMMUIdx_E10_1_PAN:
10372         return ARMMMUIdx_Stage1_E1_PAN;
10373     default:
10374         return mmu_idx;
10375     }
10376 }
10377 
10378 /* Return true if the translation regime is using LPAE format page tables */
10379 static inline bool regime_using_lpae_format(CPUARMState *env,
10380                                             ARMMMUIdx mmu_idx)
10381 {
10382     int el = regime_el(env, mmu_idx);
10383     if (el == 2 || arm_el_is_aa64(env, el)) {
10384         return true;
10385     }
10386     if (arm_feature(env, ARM_FEATURE_LPAE)
10387         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10388         return true;
10389     }
10390     return false;
10391 }
10392 
10393 /* Returns true if the stage 1 translation regime is using LPAE format page
10394  * tables. Used when raising alignment exceptions, whose FSR changes depending
10395  * on whether the long or short descriptor format is in use. */
10396 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10397 {
10398     mmu_idx = stage_1_mmu_idx(mmu_idx);
10399 
10400     return regime_using_lpae_format(env, mmu_idx);
10401 }
10402 
10403 #ifndef CONFIG_USER_ONLY
10404 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10405 {
10406     switch (mmu_idx) {
10407     case ARMMMUIdx_SE10_0:
10408     case ARMMMUIdx_E20_0:
10409     case ARMMMUIdx_SE20_0:
10410     case ARMMMUIdx_Stage1_E0:
10411     case ARMMMUIdx_Stage1_SE0:
10412     case ARMMMUIdx_MUser:
10413     case ARMMMUIdx_MSUser:
10414     case ARMMMUIdx_MUserNegPri:
10415     case ARMMMUIdx_MSUserNegPri:
10416         return true;
10417     default:
10418         return false;
10419     case ARMMMUIdx_E10_0:
10420     case ARMMMUIdx_E10_1:
10421     case ARMMMUIdx_E10_1_PAN:
10422         g_assert_not_reached();
10423     }
10424 }
10425 
10426 /* Translate section/page access permissions to page
10427  * R/W protection flags
10428  *
10429  * @env:         CPUARMState
10430  * @mmu_idx:     MMU index indicating required translation regime
10431  * @ap:          The 3-bit access permissions (AP[2:0])
10432  * @domain_prot: The 2-bit domain access permissions
10433  */
10434 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10435                                 int ap, int domain_prot)
10436 {
10437     bool is_user = regime_is_user(env, mmu_idx);
10438 
10439     if (domain_prot == 3) {
10440         return PAGE_READ | PAGE_WRITE;
10441     }
10442 
10443     switch (ap) {
10444     case 0:
10445         if (arm_feature(env, ARM_FEATURE_V7)) {
10446             return 0;
10447         }
10448         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10449         case SCTLR_S:
10450             return is_user ? 0 : PAGE_READ;
10451         case SCTLR_R:
10452             return PAGE_READ;
10453         default:
10454             return 0;
10455         }
10456     case 1:
10457         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10458     case 2:
10459         if (is_user) {
10460             return PAGE_READ;
10461         } else {
10462             return PAGE_READ | PAGE_WRITE;
10463         }
10464     case 3:
10465         return PAGE_READ | PAGE_WRITE;
10466     case 4: /* Reserved.  */
10467         return 0;
10468     case 5:
10469         return is_user ? 0 : PAGE_READ;
10470     case 6:
10471         return PAGE_READ;
10472     case 7:
10473         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10474             return 0;
10475         }
10476         return PAGE_READ;
10477     default:
10478         g_assert_not_reached();
10479     }
10480 }
10481 
10482 /* Translate section/page access permissions to page
10483  * R/W protection flags.
10484  *
10485  * @ap:      The 2-bit simple AP (AP[2:1])
10486  * @is_user: TRUE if accessing from PL0
10487  */
10488 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10489 {
10490     switch (ap) {
10491     case 0:
10492         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10493     case 1:
10494         return PAGE_READ | PAGE_WRITE;
10495     case 2:
10496         return is_user ? 0 : PAGE_READ;
10497     case 3:
10498         return PAGE_READ;
10499     default:
10500         g_assert_not_reached();
10501     }
10502 }
10503 
10504 static inline int
10505 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10506 {
10507     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10508 }
10509 
10510 /* Translate S2 section/page access permissions to protection flags
10511  *
10512  * @env:     CPUARMState
10513  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10514  * @xn:      XN (execute-never) bits
10515  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
10516  */
10517 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
10518 {
10519     int prot = 0;
10520 
10521     if (s2ap & 1) {
10522         prot |= PAGE_READ;
10523     }
10524     if (s2ap & 2) {
10525         prot |= PAGE_WRITE;
10526     }
10527 
10528     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
10529         switch (xn) {
10530         case 0:
10531             prot |= PAGE_EXEC;
10532             break;
10533         case 1:
10534             if (s1_is_el0) {
10535                 prot |= PAGE_EXEC;
10536             }
10537             break;
10538         case 2:
10539             break;
10540         case 3:
10541             if (!s1_is_el0) {
10542                 prot |= PAGE_EXEC;
10543             }
10544             break;
10545         default:
10546             g_assert_not_reached();
10547         }
10548     } else {
10549         if (!extract32(xn, 1, 1)) {
10550             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10551                 prot |= PAGE_EXEC;
10552             }
10553         }
10554     }
10555     return prot;
10556 }
10557 
10558 /* Translate section/page access permissions to protection flags
10559  *
10560  * @env:     CPUARMState
10561  * @mmu_idx: MMU index indicating required translation regime
10562  * @is_aa64: TRUE if AArch64
10563  * @ap:      The 2-bit simple AP (AP[2:1])
10564  * @ns:      NS (non-secure) bit
10565  * @xn:      XN (execute-never) bit
10566  * @pxn:     PXN (privileged execute-never) bit
10567  */
10568 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10569                       int ap, int ns, int xn, int pxn)
10570 {
10571     bool is_user = regime_is_user(env, mmu_idx);
10572     int prot_rw, user_rw;
10573     bool have_wxn;
10574     int wxn = 0;
10575 
10576     assert(mmu_idx != ARMMMUIdx_Stage2);
10577     assert(mmu_idx != ARMMMUIdx_Stage2_S);
10578 
10579     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10580     if (is_user) {
10581         prot_rw = user_rw;
10582     } else {
10583         if (user_rw && regime_is_pan(env, mmu_idx)) {
10584             /* PAN forbids data accesses but doesn't affect insn fetch */
10585             prot_rw = 0;
10586         } else {
10587             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10588         }
10589     }
10590 
10591     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10592         return prot_rw;
10593     }
10594 
10595     /* TODO have_wxn should be replaced with
10596      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10597      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10598      * compatible processors have EL2, which is required for [U]WXN.
10599      */
10600     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10601 
10602     if (have_wxn) {
10603         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10604     }
10605 
10606     if (is_aa64) {
10607         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10608             xn = pxn || (user_rw & PAGE_WRITE);
10609         }
10610     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10611         switch (regime_el(env, mmu_idx)) {
10612         case 1:
10613         case 3:
10614             if (is_user) {
10615                 xn = xn || !(user_rw & PAGE_READ);
10616             } else {
10617                 int uwxn = 0;
10618                 if (have_wxn) {
10619                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10620                 }
10621                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10622                      (uwxn && (user_rw & PAGE_WRITE));
10623             }
10624             break;
10625         case 2:
10626             break;
10627         }
10628     } else {
10629         xn = wxn = 0;
10630     }
10631 
10632     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10633         return prot_rw;
10634     }
10635     return prot_rw | PAGE_EXEC;
10636 }
10637 
10638 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10639                                      uint32_t *table, uint32_t address)
10640 {
10641     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10642     TCR *tcr = regime_tcr(env, mmu_idx);
10643 
10644     if (address & tcr->mask) {
10645         if (tcr->raw_tcr & TTBCR_PD1) {
10646             /* Translation table walk disabled for TTBR1 */
10647             return false;
10648         }
10649         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10650     } else {
10651         if (tcr->raw_tcr & TTBCR_PD0) {
10652             /* Translation table walk disabled for TTBR0 */
10653             return false;
10654         }
10655         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10656     }
10657     *table |= (address >> 18) & 0x3ffc;
10658     return true;
10659 }
10660 
10661 /* Translate a S1 pagetable walk through S2 if needed.  */
10662 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10663                                hwaddr addr, bool *is_secure,
10664                                ARMMMUFaultInfo *fi)
10665 {
10666     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10667         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10668         target_ulong s2size;
10669         hwaddr s2pa;
10670         int s2prot;
10671         int ret;
10672         ARMMMUIdx s2_mmu_idx = *is_secure ? ARMMMUIdx_Stage2_S
10673                                           : ARMMMUIdx_Stage2;
10674         ARMCacheAttrs cacheattrs = {};
10675         MemTxAttrs txattrs = {};
10676 
10677         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, s2_mmu_idx, false,
10678                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10679                                  &cacheattrs);
10680         if (ret) {
10681             assert(fi->type != ARMFault_None);
10682             fi->s2addr = addr;
10683             fi->stage2 = true;
10684             fi->s1ptw = true;
10685             fi->s1ns = !*is_secure;
10686             return ~0;
10687         }
10688         if ((arm_hcr_el2_eff(env) & HCR_PTW) &&
10689             (cacheattrs.attrs & 0xf0) == 0) {
10690             /*
10691              * PTW set and S1 walk touched S2 Device memory:
10692              * generate Permission fault.
10693              */
10694             fi->type = ARMFault_Permission;
10695             fi->s2addr = addr;
10696             fi->stage2 = true;
10697             fi->s1ptw = true;
10698             fi->s1ns = !*is_secure;
10699             return ~0;
10700         }
10701 
10702         if (arm_is_secure_below_el3(env)) {
10703             /* Check if page table walk is to secure or non-secure PA space. */
10704             if (*is_secure) {
10705                 *is_secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
10706             } else {
10707                 *is_secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
10708             }
10709         } else {
10710             assert(!*is_secure);
10711         }
10712 
10713         addr = s2pa;
10714     }
10715     return addr;
10716 }
10717 
10718 /* All loads done in the course of a page table walk go through here. */
10719 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10720                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10721 {
10722     ARMCPU *cpu = ARM_CPU(cs);
10723     CPUARMState *env = &cpu->env;
10724     MemTxAttrs attrs = {};
10725     MemTxResult result = MEMTX_OK;
10726     AddressSpace *as;
10727     uint32_t data;
10728 
10729     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10730     attrs.secure = is_secure;
10731     as = arm_addressspace(cs, attrs);
10732     if (fi->s1ptw) {
10733         return 0;
10734     }
10735     if (regime_translation_big_endian(env, mmu_idx)) {
10736         data = address_space_ldl_be(as, addr, attrs, &result);
10737     } else {
10738         data = address_space_ldl_le(as, addr, attrs, &result);
10739     }
10740     if (result == MEMTX_OK) {
10741         return data;
10742     }
10743     fi->type = ARMFault_SyncExternalOnWalk;
10744     fi->ea = arm_extabort_type(result);
10745     return 0;
10746 }
10747 
10748 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10749                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10750 {
10751     ARMCPU *cpu = ARM_CPU(cs);
10752     CPUARMState *env = &cpu->env;
10753     MemTxAttrs attrs = {};
10754     MemTxResult result = MEMTX_OK;
10755     AddressSpace *as;
10756     uint64_t data;
10757 
10758     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10759     attrs.secure = is_secure;
10760     as = arm_addressspace(cs, attrs);
10761     if (fi->s1ptw) {
10762         return 0;
10763     }
10764     if (regime_translation_big_endian(env, mmu_idx)) {
10765         data = address_space_ldq_be(as, addr, attrs, &result);
10766     } else {
10767         data = address_space_ldq_le(as, addr, attrs, &result);
10768     }
10769     if (result == MEMTX_OK) {
10770         return data;
10771     }
10772     fi->type = ARMFault_SyncExternalOnWalk;
10773     fi->ea = arm_extabort_type(result);
10774     return 0;
10775 }
10776 
10777 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10778                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10779                              hwaddr *phys_ptr, int *prot,
10780                              target_ulong *page_size,
10781                              ARMMMUFaultInfo *fi)
10782 {
10783     CPUState *cs = env_cpu(env);
10784     int level = 1;
10785     uint32_t table;
10786     uint32_t desc;
10787     int type;
10788     int ap;
10789     int domain = 0;
10790     int domain_prot;
10791     hwaddr phys_addr;
10792     uint32_t dacr;
10793 
10794     /* Pagetable walk.  */
10795     /* Lookup l1 descriptor.  */
10796     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10797         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10798         fi->type = ARMFault_Translation;
10799         goto do_fault;
10800     }
10801     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10802                        mmu_idx, fi);
10803     if (fi->type != ARMFault_None) {
10804         goto do_fault;
10805     }
10806     type = (desc & 3);
10807     domain = (desc >> 5) & 0x0f;
10808     if (regime_el(env, mmu_idx) == 1) {
10809         dacr = env->cp15.dacr_ns;
10810     } else {
10811         dacr = env->cp15.dacr_s;
10812     }
10813     domain_prot = (dacr >> (domain * 2)) & 3;
10814     if (type == 0) {
10815         /* Section translation fault.  */
10816         fi->type = ARMFault_Translation;
10817         goto do_fault;
10818     }
10819     if (type != 2) {
10820         level = 2;
10821     }
10822     if (domain_prot == 0 || domain_prot == 2) {
10823         fi->type = ARMFault_Domain;
10824         goto do_fault;
10825     }
10826     if (type == 2) {
10827         /* 1Mb section.  */
10828         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10829         ap = (desc >> 10) & 3;
10830         *page_size = 1024 * 1024;
10831     } else {
10832         /* Lookup l2 entry.  */
10833         if (type == 1) {
10834             /* Coarse pagetable.  */
10835             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10836         } else {
10837             /* Fine pagetable.  */
10838             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10839         }
10840         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10841                            mmu_idx, fi);
10842         if (fi->type != ARMFault_None) {
10843             goto do_fault;
10844         }
10845         switch (desc & 3) {
10846         case 0: /* Page translation fault.  */
10847             fi->type = ARMFault_Translation;
10848             goto do_fault;
10849         case 1: /* 64k page.  */
10850             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10851             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10852             *page_size = 0x10000;
10853             break;
10854         case 2: /* 4k page.  */
10855             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10856             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10857             *page_size = 0x1000;
10858             break;
10859         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10860             if (type == 1) {
10861                 /* ARMv6/XScale extended small page format */
10862                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10863                     || arm_feature(env, ARM_FEATURE_V6)) {
10864                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10865                     *page_size = 0x1000;
10866                 } else {
10867                     /* UNPREDICTABLE in ARMv5; we choose to take a
10868                      * page translation fault.
10869                      */
10870                     fi->type = ARMFault_Translation;
10871                     goto do_fault;
10872                 }
10873             } else {
10874                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10875                 *page_size = 0x400;
10876             }
10877             ap = (desc >> 4) & 3;
10878             break;
10879         default:
10880             /* Never happens, but compiler isn't smart enough to tell.  */
10881             g_assert_not_reached();
10882         }
10883     }
10884     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10885     *prot |= *prot ? PAGE_EXEC : 0;
10886     if (!(*prot & (1 << access_type))) {
10887         /* Access permission fault.  */
10888         fi->type = ARMFault_Permission;
10889         goto do_fault;
10890     }
10891     *phys_ptr = phys_addr;
10892     return false;
10893 do_fault:
10894     fi->domain = domain;
10895     fi->level = level;
10896     return true;
10897 }
10898 
10899 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10900                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10901                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10902                              target_ulong *page_size, ARMMMUFaultInfo *fi)
10903 {
10904     CPUState *cs = env_cpu(env);
10905     ARMCPU *cpu = env_archcpu(env);
10906     int level = 1;
10907     uint32_t table;
10908     uint32_t desc;
10909     uint32_t xn;
10910     uint32_t pxn = 0;
10911     int type;
10912     int ap;
10913     int domain = 0;
10914     int domain_prot;
10915     hwaddr phys_addr;
10916     uint32_t dacr;
10917     bool ns;
10918 
10919     /* Pagetable walk.  */
10920     /* Lookup l1 descriptor.  */
10921     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10922         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10923         fi->type = ARMFault_Translation;
10924         goto do_fault;
10925     }
10926     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10927                        mmu_idx, fi);
10928     if (fi->type != ARMFault_None) {
10929         goto do_fault;
10930     }
10931     type = (desc & 3);
10932     if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
10933         /* Section translation fault, or attempt to use the encoding
10934          * which is Reserved on implementations without PXN.
10935          */
10936         fi->type = ARMFault_Translation;
10937         goto do_fault;
10938     }
10939     if ((type == 1) || !(desc & (1 << 18))) {
10940         /* Page or Section.  */
10941         domain = (desc >> 5) & 0x0f;
10942     }
10943     if (regime_el(env, mmu_idx) == 1) {
10944         dacr = env->cp15.dacr_ns;
10945     } else {
10946         dacr = env->cp15.dacr_s;
10947     }
10948     if (type == 1) {
10949         level = 2;
10950     }
10951     domain_prot = (dacr >> (domain * 2)) & 3;
10952     if (domain_prot == 0 || domain_prot == 2) {
10953         /* Section or Page domain fault */
10954         fi->type = ARMFault_Domain;
10955         goto do_fault;
10956     }
10957     if (type != 1) {
10958         if (desc & (1 << 18)) {
10959             /* Supersection.  */
10960             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
10961             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
10962             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
10963             *page_size = 0x1000000;
10964         } else {
10965             /* Section.  */
10966             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10967             *page_size = 0x100000;
10968         }
10969         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
10970         xn = desc & (1 << 4);
10971         pxn = desc & 1;
10972         ns = extract32(desc, 19, 1);
10973     } else {
10974         if (cpu_isar_feature(aa32_pxn, cpu)) {
10975             pxn = (desc >> 2) & 1;
10976         }
10977         ns = extract32(desc, 3, 1);
10978         /* Lookup l2 entry.  */
10979         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10980         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10981                            mmu_idx, fi);
10982         if (fi->type != ARMFault_None) {
10983             goto do_fault;
10984         }
10985         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
10986         switch (desc & 3) {
10987         case 0: /* Page translation fault.  */
10988             fi->type = ARMFault_Translation;
10989             goto do_fault;
10990         case 1: /* 64k page.  */
10991             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10992             xn = desc & (1 << 15);
10993             *page_size = 0x10000;
10994             break;
10995         case 2: case 3: /* 4k page.  */
10996             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10997             xn = desc & 1;
10998             *page_size = 0x1000;
10999             break;
11000         default:
11001             /* Never happens, but compiler isn't smart enough to tell.  */
11002             g_assert_not_reached();
11003         }
11004     }
11005     if (domain_prot == 3) {
11006         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11007     } else {
11008         if (pxn && !regime_is_user(env, mmu_idx)) {
11009             xn = 1;
11010         }
11011         if (xn && access_type == MMU_INST_FETCH) {
11012             fi->type = ARMFault_Permission;
11013             goto do_fault;
11014         }
11015 
11016         if (arm_feature(env, ARM_FEATURE_V6K) &&
11017                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
11018             /* The simplified model uses AP[0] as an access control bit.  */
11019             if ((ap & 1) == 0) {
11020                 /* Access flag fault.  */
11021                 fi->type = ARMFault_AccessFlag;
11022                 goto do_fault;
11023             }
11024             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
11025         } else {
11026             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11027         }
11028         if (*prot && !xn) {
11029             *prot |= PAGE_EXEC;
11030         }
11031         if (!(*prot & (1 << access_type))) {
11032             /* Access permission fault.  */
11033             fi->type = ARMFault_Permission;
11034             goto do_fault;
11035         }
11036     }
11037     if (ns) {
11038         /* The NS bit will (as required by the architecture) have no effect if
11039          * the CPU doesn't support TZ or this is a non-secure translation
11040          * regime, because the attribute will already be non-secure.
11041          */
11042         attrs->secure = false;
11043     }
11044     *phys_ptr = phys_addr;
11045     return false;
11046 do_fault:
11047     fi->domain = domain;
11048     fi->level = level;
11049     return true;
11050 }
11051 
11052 /*
11053  * check_s2_mmu_setup
11054  * @cpu:        ARMCPU
11055  * @is_aa64:    True if the translation regime is in AArch64 state
11056  * @startlevel: Suggested starting level
11057  * @inputsize:  Bitsize of IPAs
11058  * @stride:     Page-table stride (See the ARM ARM)
11059  *
11060  * Returns true if the suggested S2 translation parameters are OK and
11061  * false otherwise.
11062  */
11063 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
11064                                int inputsize, int stride, int outputsize)
11065 {
11066     const int grainsize = stride + 3;
11067     int startsizecheck;
11068 
11069     /*
11070      * Negative levels are usually not allowed...
11071      * Except for FEAT_LPA2, 4k page table, 52-bit address space, which
11072      * begins with level -1.  Note that previous feature tests will have
11073      * eliminated this combination if it is not enabled.
11074      */
11075     if (level < (inputsize == 52 && stride == 9 ? -1 : 0)) {
11076         return false;
11077     }
11078 
11079     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
11080     if (startsizecheck < 1 || startsizecheck > stride + 4) {
11081         return false;
11082     }
11083 
11084     if (is_aa64) {
11085         switch (stride) {
11086         case 13: /* 64KB Pages.  */
11087             if (level == 0 || (level == 1 && outputsize <= 42)) {
11088                 return false;
11089             }
11090             break;
11091         case 11: /* 16KB Pages.  */
11092             if (level == 0 || (level == 1 && outputsize <= 40)) {
11093                 return false;
11094             }
11095             break;
11096         case 9: /* 4KB Pages.  */
11097             if (level == 0 && outputsize <= 42) {
11098                 return false;
11099             }
11100             break;
11101         default:
11102             g_assert_not_reached();
11103         }
11104 
11105         /* Inputsize checks.  */
11106         if (inputsize > outputsize &&
11107             (arm_el_is_aa64(&cpu->env, 1) || inputsize > 40)) {
11108             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
11109             return false;
11110         }
11111     } else {
11112         /* AArch32 only supports 4KB pages. Assert on that.  */
11113         assert(stride == 9);
11114 
11115         if (level == 0) {
11116             return false;
11117         }
11118     }
11119     return true;
11120 }
11121 
11122 /* Translate from the 4-bit stage 2 representation of
11123  * memory attributes (without cache-allocation hints) to
11124  * the 8-bit representation of the stage 1 MAIR registers
11125  * (which includes allocation hints).
11126  *
11127  * ref: shared/translation/attrs/S2AttrDecode()
11128  *      .../S2ConvertAttrsHints()
11129  */
11130 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
11131 {
11132     uint8_t hiattr = extract32(s2attrs, 2, 2);
11133     uint8_t loattr = extract32(s2attrs, 0, 2);
11134     uint8_t hihint = 0, lohint = 0;
11135 
11136     if (hiattr != 0) { /* normal memory */
11137         if (arm_hcr_el2_eff(env) & HCR_CD) { /* cache disabled */
11138             hiattr = loattr = 1; /* non-cacheable */
11139         } else {
11140             if (hiattr != 1) { /* Write-through or write-back */
11141                 hihint = 3; /* RW allocate */
11142             }
11143             if (loattr != 1) { /* Write-through or write-back */
11144                 lohint = 3; /* RW allocate */
11145             }
11146         }
11147     }
11148 
11149     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11150 }
11151 #endif /* !CONFIG_USER_ONLY */
11152 
11153 /* This mapping is common between ID_AA64MMFR0.PARANGE and TCR_ELx.{I}PS. */
11154 static const uint8_t pamax_map[] = {
11155     [0] = 32,
11156     [1] = 36,
11157     [2] = 40,
11158     [3] = 42,
11159     [4] = 44,
11160     [5] = 48,
11161     [6] = 52,
11162 };
11163 
11164 /* The cpu-specific constant value of PAMax; also used by hw/arm/virt. */
11165 unsigned int arm_pamax(ARMCPU *cpu)
11166 {
11167     unsigned int parange =
11168         FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11169 
11170     /*
11171      * id_aa64mmfr0 is a read-only register so values outside of the
11172      * supported mappings can be considered an implementation error.
11173      */
11174     assert(parange < ARRAY_SIZE(pamax_map));
11175     return pamax_map[parange];
11176 }
11177 
11178 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
11179 {
11180     if (regime_has_2_ranges(mmu_idx)) {
11181         return extract64(tcr, 37, 2);
11182     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11183         return 0; /* VTCR_EL2 */
11184     } else {
11185         /* Replicate the single TBI bit so we always have 2 bits.  */
11186         return extract32(tcr, 20, 1) * 3;
11187     }
11188 }
11189 
11190 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
11191 {
11192     if (regime_has_2_ranges(mmu_idx)) {
11193         return extract64(tcr, 51, 2);
11194     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11195         return 0; /* VTCR_EL2 */
11196     } else {
11197         /* Replicate the single TBID bit so we always have 2 bits.  */
11198         return extract32(tcr, 29, 1) * 3;
11199     }
11200 }
11201 
11202 static int aa64_va_parameter_tcma(uint64_t tcr, ARMMMUIdx mmu_idx)
11203 {
11204     if (regime_has_2_ranges(mmu_idx)) {
11205         return extract64(tcr, 57, 2);
11206     } else {
11207         /* Replicate the single TCMA bit so we always have 2 bits.  */
11208         return extract32(tcr, 30, 1) * 3;
11209     }
11210 }
11211 
11212 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11213                                    ARMMMUIdx mmu_idx, bool data)
11214 {
11215     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11216     bool epd, hpd, using16k, using64k, tsz_oob, ds;
11217     int select, tsz, tbi, max_tsz, min_tsz, ps, sh;
11218     ARMCPU *cpu = env_archcpu(env);
11219 
11220     if (!regime_has_2_ranges(mmu_idx)) {
11221         select = 0;
11222         tsz = extract32(tcr, 0, 6);
11223         using64k = extract32(tcr, 14, 1);
11224         using16k = extract32(tcr, 15, 1);
11225         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11226             /* VTCR_EL2 */
11227             hpd = false;
11228         } else {
11229             hpd = extract32(tcr, 24, 1);
11230         }
11231         epd = false;
11232         sh = extract32(tcr, 12, 2);
11233         ps = extract32(tcr, 16, 3);
11234         ds = extract64(tcr, 32, 1);
11235     } else {
11236         /*
11237          * Bit 55 is always between the two regions, and is canonical for
11238          * determining if address tagging is enabled.
11239          */
11240         select = extract64(va, 55, 1);
11241         if (!select) {
11242             tsz = extract32(tcr, 0, 6);
11243             epd = extract32(tcr, 7, 1);
11244             sh = extract32(tcr, 12, 2);
11245             using64k = extract32(tcr, 14, 1);
11246             using16k = extract32(tcr, 15, 1);
11247             hpd = extract64(tcr, 41, 1);
11248         } else {
11249             int tg = extract32(tcr, 30, 2);
11250             using16k = tg == 1;
11251             using64k = tg == 3;
11252             tsz = extract32(tcr, 16, 6);
11253             epd = extract32(tcr, 23, 1);
11254             sh = extract32(tcr, 28, 2);
11255             hpd = extract64(tcr, 42, 1);
11256         }
11257         ps = extract64(tcr, 32, 3);
11258         ds = extract64(tcr, 59, 1);
11259     }
11260 
11261     if (cpu_isar_feature(aa64_st, cpu)) {
11262         max_tsz = 48 - using64k;
11263     } else {
11264         max_tsz = 39;
11265     }
11266 
11267     /*
11268      * DS is RES0 unless FEAT_LPA2 is supported for the given page size;
11269      * adjust the effective value of DS, as documented.
11270      */
11271     min_tsz = 16;
11272     if (using64k) {
11273         if (cpu_isar_feature(aa64_lva, cpu)) {
11274             min_tsz = 12;
11275         }
11276         ds = false;
11277     } else if (ds) {
11278         switch (mmu_idx) {
11279         case ARMMMUIdx_Stage2:
11280         case ARMMMUIdx_Stage2_S:
11281             if (using16k) {
11282                 ds = cpu_isar_feature(aa64_tgran16_2_lpa2, cpu);
11283             } else {
11284                 ds = cpu_isar_feature(aa64_tgran4_2_lpa2, cpu);
11285             }
11286             break;
11287         default:
11288             if (using16k) {
11289                 ds = cpu_isar_feature(aa64_tgran16_lpa2, cpu);
11290             } else {
11291                 ds = cpu_isar_feature(aa64_tgran4_lpa2, cpu);
11292             }
11293             break;
11294         }
11295         if (ds) {
11296             min_tsz = 12;
11297         }
11298     }
11299 
11300     if (tsz > max_tsz) {
11301         tsz = max_tsz;
11302         tsz_oob = true;
11303     } else if (tsz < min_tsz) {
11304         tsz = min_tsz;
11305         tsz_oob = true;
11306     } else {
11307         tsz_oob = false;
11308     }
11309 
11310     /* Present TBI as a composite with TBID.  */
11311     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11312     if (!data) {
11313         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11314     }
11315     tbi = (tbi >> select) & 1;
11316 
11317     return (ARMVAParameters) {
11318         .tsz = tsz,
11319         .ps = ps,
11320         .sh = sh,
11321         .select = select,
11322         .tbi = tbi,
11323         .epd = epd,
11324         .hpd = hpd,
11325         .using16k = using16k,
11326         .using64k = using64k,
11327         .tsz_oob = tsz_oob,
11328         .ds = ds,
11329     };
11330 }
11331 
11332 #ifndef CONFIG_USER_ONLY
11333 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11334                                           ARMMMUIdx mmu_idx)
11335 {
11336     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11337     uint32_t el = regime_el(env, mmu_idx);
11338     int select, tsz;
11339     bool epd, hpd;
11340 
11341     assert(mmu_idx != ARMMMUIdx_Stage2_S);
11342 
11343     if (mmu_idx == ARMMMUIdx_Stage2) {
11344         /* VTCR */
11345         bool sext = extract32(tcr, 4, 1);
11346         bool sign = extract32(tcr, 3, 1);
11347 
11348         /*
11349          * If the sign-extend bit is not the same as t0sz[3], the result
11350          * is unpredictable. Flag this as a guest error.
11351          */
11352         if (sign != sext) {
11353             qemu_log_mask(LOG_GUEST_ERROR,
11354                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11355         }
11356         tsz = sextract32(tcr, 0, 4) + 8;
11357         select = 0;
11358         hpd = false;
11359         epd = false;
11360     } else if (el == 2) {
11361         /* HTCR */
11362         tsz = extract32(tcr, 0, 3);
11363         select = 0;
11364         hpd = extract64(tcr, 24, 1);
11365         epd = false;
11366     } else {
11367         int t0sz = extract32(tcr, 0, 3);
11368         int t1sz = extract32(tcr, 16, 3);
11369 
11370         if (t1sz == 0) {
11371             select = va > (0xffffffffu >> t0sz);
11372         } else {
11373             /* Note that we will detect errors later.  */
11374             select = va >= ~(0xffffffffu >> t1sz);
11375         }
11376         if (!select) {
11377             tsz = t0sz;
11378             epd = extract32(tcr, 7, 1);
11379             hpd = extract64(tcr, 41, 1);
11380         } else {
11381             tsz = t1sz;
11382             epd = extract32(tcr, 23, 1);
11383             hpd = extract64(tcr, 42, 1);
11384         }
11385         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11386         hpd &= extract32(tcr, 6, 1);
11387     }
11388 
11389     return (ARMVAParameters) {
11390         .tsz = tsz,
11391         .select = select,
11392         .epd = epd,
11393         .hpd = hpd,
11394     };
11395 }
11396 
11397 /**
11398  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
11399  *
11400  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11401  * prot and page_size may not be filled in, and the populated fsr value provides
11402  * information on why the translation aborted, in the format of a long-format
11403  * DFSR/IFSR fault register, with the following caveats:
11404  *  * the WnR bit is never set (the caller must do this).
11405  *
11406  * @env: CPUARMState
11407  * @address: virtual address to get physical address for
11408  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
11409  * @mmu_idx: MMU index indicating required translation regime
11410  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
11411  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
11412  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
11413  * @phys_ptr: set to the physical address corresponding to the virtual address
11414  * @attrs: set to the memory transaction attributes to use
11415  * @prot: set to the permissions for the page containing phys_ptr
11416  * @page_size_ptr: set to the size of the page containing phys_ptr
11417  * @fi: set to fault info if the translation fails
11418  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11419  */
11420 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
11421                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11422                                bool s1_is_el0,
11423                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11424                                target_ulong *page_size_ptr,
11425                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11426 {
11427     ARMCPU *cpu = env_archcpu(env);
11428     CPUState *cs = CPU(cpu);
11429     /* Read an LPAE long-descriptor translation table. */
11430     ARMFaultType fault_type = ARMFault_Translation;
11431     uint32_t level;
11432     ARMVAParameters param;
11433     uint64_t ttbr;
11434     hwaddr descaddr, indexmask, indexmask_grainsize;
11435     uint32_t tableattrs;
11436     target_ulong page_size;
11437     uint32_t attrs;
11438     int32_t stride;
11439     int addrsize, inputsize, outputsize;
11440     TCR *tcr = regime_tcr(env, mmu_idx);
11441     int ap, ns, xn, pxn;
11442     uint32_t el = regime_el(env, mmu_idx);
11443     uint64_t descaddrmask;
11444     bool aarch64 = arm_el_is_aa64(env, el);
11445     bool guarded = false;
11446 
11447     /* TODO: This code does not support shareability levels. */
11448     if (aarch64) {
11449         int ps;
11450 
11451         param = aa64_va_parameters(env, address, mmu_idx,
11452                                    access_type != MMU_INST_FETCH);
11453         level = 0;
11454 
11455         /*
11456          * If TxSZ is programmed to a value larger than the maximum,
11457          * or smaller than the effective minimum, it is IMPLEMENTATION
11458          * DEFINED whether we behave as if the field were programmed
11459          * within bounds, or if a level 0 Translation fault is generated.
11460          *
11461          * With FEAT_LVA, fault on less than minimum becomes required,
11462          * so our choice is to always raise the fault.
11463          */
11464         if (param.tsz_oob) {
11465             fault_type = ARMFault_Translation;
11466             goto do_fault;
11467         }
11468 
11469         addrsize = 64 - 8 * param.tbi;
11470         inputsize = 64 - param.tsz;
11471 
11472         /*
11473          * Bound PS by PARANGE to find the effective output address size.
11474          * ID_AA64MMFR0 is a read-only register so values outside of the
11475          * supported mappings can be considered an implementation error.
11476          */
11477         ps = FIELD_EX64(cpu->isar.id_aa64mmfr0, ID_AA64MMFR0, PARANGE);
11478         ps = MIN(ps, param.ps);
11479         assert(ps < ARRAY_SIZE(pamax_map));
11480         outputsize = pamax_map[ps];
11481     } else {
11482         param = aa32_va_parameters(env, address, mmu_idx);
11483         level = 1;
11484         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
11485         inputsize = addrsize - param.tsz;
11486         outputsize = 40;
11487     }
11488 
11489     /*
11490      * We determined the region when collecting the parameters, but we
11491      * have not yet validated that the address is valid for the region.
11492      * Extract the top bits and verify that they all match select.
11493      *
11494      * For aa32, if inputsize == addrsize, then we have selected the
11495      * region by exclusion in aa32_va_parameters and there is no more
11496      * validation to do here.
11497      */
11498     if (inputsize < addrsize) {
11499         target_ulong top_bits = sextract64(address, inputsize,
11500                                            addrsize - inputsize);
11501         if (-top_bits != param.select) {
11502             /* The gap between the two regions is a Translation fault */
11503             fault_type = ARMFault_Translation;
11504             goto do_fault;
11505         }
11506     }
11507 
11508     if (param.using64k) {
11509         stride = 13;
11510     } else if (param.using16k) {
11511         stride = 11;
11512     } else {
11513         stride = 9;
11514     }
11515 
11516     /* Note that QEMU ignores shareability and cacheability attributes,
11517      * so we don't need to do anything with the SH, ORGN, IRGN fields
11518      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11519      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11520      * implement any ASID-like capability so we can ignore it (instead
11521      * we will always flush the TLB any time the ASID is changed).
11522      */
11523     ttbr = regime_ttbr(env, mmu_idx, param.select);
11524 
11525     /* Here we should have set up all the parameters for the translation:
11526      * inputsize, ttbr, epd, stride, tbi
11527      */
11528 
11529     if (param.epd) {
11530         /* Translation table walk disabled => Translation fault on TLB miss
11531          * Note: This is always 0 on 64-bit EL2 and EL3.
11532          */
11533         goto do_fault;
11534     }
11535 
11536     if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
11537         /* The starting level depends on the virtual address size (which can
11538          * be up to 48 bits) and the translation granule size. It indicates
11539          * the number of strides (stride bits at a time) needed to
11540          * consume the bits of the input address. In the pseudocode this is:
11541          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11542          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11543          * our 'stride + 3' and 'stride' is our 'stride'.
11544          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11545          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11546          * = 4 - (inputsize - 4) / stride;
11547          */
11548         level = 4 - (inputsize - 4) / stride;
11549     } else {
11550         /* For stage 2 translations the starting level is specified by the
11551          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11552          */
11553         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11554         uint32_t sl2 = extract64(tcr->raw_tcr, 33, 1);
11555         uint32_t startlevel;
11556         bool ok;
11557 
11558         /* SL2 is RES0 unless DS=1 & 4kb granule. */
11559         if (param.ds && stride == 9 && sl2) {
11560             if (sl0 != 0) {
11561                 level = 0;
11562                 fault_type = ARMFault_Translation;
11563                 goto do_fault;
11564             }
11565             startlevel = -1;
11566         } else if (!aarch64 || stride == 9) {
11567             /* AArch32 or 4KB pages */
11568             startlevel = 2 - sl0;
11569 
11570             if (cpu_isar_feature(aa64_st, cpu)) {
11571                 startlevel &= 3;
11572             }
11573         } else {
11574             /* 16KB or 64KB pages */
11575             startlevel = 3 - sl0;
11576         }
11577 
11578         /* Check that the starting level is valid. */
11579         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11580                                 inputsize, stride, outputsize);
11581         if (!ok) {
11582             fault_type = ARMFault_Translation;
11583             goto do_fault;
11584         }
11585         level = startlevel;
11586     }
11587 
11588     indexmask_grainsize = MAKE_64BIT_MASK(0, stride + 3);
11589     indexmask = MAKE_64BIT_MASK(0, inputsize - (stride * (4 - level)));
11590 
11591     /* Now we can extract the actual base address from the TTBR */
11592     descaddr = extract64(ttbr, 0, 48);
11593 
11594     /*
11595      * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [5:2] of TTBR.
11596      *
11597      * Otherwise, if the base address is out of range, raise AddressSizeFault.
11598      * In the pseudocode, this is !IsZero(baseregister<47:outputsize>),
11599      * but we've just cleared the bits above 47, so simplify the test.
11600      */
11601     if (outputsize > 48) {
11602         descaddr |= extract64(ttbr, 2, 4) << 48;
11603     } else if (descaddr >> outputsize) {
11604         level = 0;
11605         fault_type = ARMFault_AddressSize;
11606         goto do_fault;
11607     }
11608 
11609     /*
11610      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
11611      * and also to mask out CnP (bit 0) which could validly be non-zero.
11612      */
11613     descaddr &= ~indexmask;
11614 
11615     /*
11616      * For AArch32, the address field in the descriptor goes up to bit 39
11617      * for both v7 and v8.  However, for v8 the SBZ bits [47:40] must be 0
11618      * or an AddressSize fault is raised.  So for v8 we extract those SBZ
11619      * bits as part of the address, which will be checked via outputsize.
11620      * For AArch64, the address field goes up to bit 47, or 49 with FEAT_LPA2;
11621      * the highest bits of a 52-bit output are placed elsewhere.
11622      */
11623     if (param.ds) {
11624         descaddrmask = MAKE_64BIT_MASK(0, 50);
11625     } else if (arm_feature(env, ARM_FEATURE_V8)) {
11626         descaddrmask = MAKE_64BIT_MASK(0, 48);
11627     } else {
11628         descaddrmask = MAKE_64BIT_MASK(0, 40);
11629     }
11630     descaddrmask &= ~indexmask_grainsize;
11631 
11632     /* Secure accesses start with the page table in secure memory and
11633      * can be downgraded to non-secure at any step. Non-secure accesses
11634      * remain non-secure. We implement this by just ORing in the NSTable/NS
11635      * bits at each step.
11636      */
11637     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11638     for (;;) {
11639         uint64_t descriptor;
11640         bool nstable;
11641 
11642         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11643         descaddr &= ~7ULL;
11644         nstable = extract32(tableattrs, 4, 1);
11645         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11646         if (fi->type != ARMFault_None) {
11647             goto do_fault;
11648         }
11649 
11650         if (!(descriptor & 1) ||
11651             (!(descriptor & 2) && (level == 3))) {
11652             /* Invalid, or the Reserved level 3 encoding */
11653             goto do_fault;
11654         }
11655 
11656         descaddr = descriptor & descaddrmask;
11657 
11658         /*
11659          * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [15:12]
11660          * of descriptor.  For FEAT_LPA2 and effective DS, bits [51:50] of
11661          * descaddr are in [9:8].  Otherwise, if descaddr is out of range,
11662          * raise AddressSizeFault.
11663          */
11664         if (outputsize > 48) {
11665             if (param.ds) {
11666                 descaddr |= extract64(descriptor, 8, 2) << 50;
11667             } else {
11668                 descaddr |= extract64(descriptor, 12, 4) << 48;
11669             }
11670         } else if (descaddr >> outputsize) {
11671             fault_type = ARMFault_AddressSize;
11672             goto do_fault;
11673         }
11674 
11675         if ((descriptor & 2) && (level < 3)) {
11676             /* Table entry. The top five bits are attributes which may
11677              * propagate down through lower levels of the table (and
11678              * which are all arranged so that 0 means "no effect", so
11679              * we can gather them up by ORing in the bits at each level).
11680              */
11681             tableattrs |= extract64(descriptor, 59, 5);
11682             level++;
11683             indexmask = indexmask_grainsize;
11684             continue;
11685         }
11686         /*
11687          * Block entry at level 1 or 2, or page entry at level 3.
11688          * These are basically the same thing, although the number
11689          * of bits we pull in from the vaddr varies. Note that although
11690          * descaddrmask masks enough of the low bits of the descriptor
11691          * to give a correct page or table address, the address field
11692          * in a block descriptor is smaller; so we need to explicitly
11693          * clear the lower bits here before ORing in the low vaddr bits.
11694          */
11695         page_size = (1ULL << ((stride * (4 - level)) + 3));
11696         descaddr &= ~(page_size - 1);
11697         descaddr |= (address & (page_size - 1));
11698         /* Extract attributes from the descriptor */
11699         attrs = extract64(descriptor, 2, 10)
11700             | (extract64(descriptor, 52, 12) << 10);
11701 
11702         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11703             /* Stage 2 table descriptors do not include any attribute fields */
11704             break;
11705         }
11706         /* Merge in attributes from table descriptors */
11707         attrs |= nstable << 3; /* NS */
11708         guarded = extract64(descriptor, 50, 1);  /* GP */
11709         if (param.hpd) {
11710             /* HPD disables all the table attributes except NSTable.  */
11711             break;
11712         }
11713         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11714         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11715          * means "force PL1 access only", which means forcing AP[1] to 0.
11716          */
11717         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11718         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11719         break;
11720     }
11721     /* Here descaddr is the final physical address, and attributes
11722      * are all in attrs.
11723      */
11724     fault_type = ARMFault_AccessFlag;
11725     if ((attrs & (1 << 8)) == 0) {
11726         /* Access flag */
11727         goto do_fault;
11728     }
11729 
11730     ap = extract32(attrs, 4, 2);
11731 
11732     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11733         ns = mmu_idx == ARMMMUIdx_Stage2;
11734         xn = extract32(attrs, 11, 2);
11735         *prot = get_S2prot(env, ap, xn, s1_is_el0);
11736     } else {
11737         ns = extract32(attrs, 3, 1);
11738         xn = extract32(attrs, 12, 1);
11739         pxn = extract32(attrs, 11, 1);
11740         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11741     }
11742 
11743     fault_type = ARMFault_Permission;
11744     if (!(*prot & (1 << access_type))) {
11745         goto do_fault;
11746     }
11747 
11748     if (ns) {
11749         /* The NS bit will (as required by the architecture) have no effect if
11750          * the CPU doesn't support TZ or this is a non-secure translation
11751          * regime, because the attribute will already be non-secure.
11752          */
11753         txattrs->secure = false;
11754     }
11755     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11756     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11757         arm_tlb_bti_gp(txattrs) = true;
11758     }
11759 
11760     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11761         cacheattrs->attrs = convert_stage2_attrs(env, extract32(attrs, 0, 4));
11762     } else {
11763         /* Index into MAIR registers for cache attributes */
11764         uint8_t attrindx = extract32(attrs, 0, 3);
11765         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11766         assert(attrindx <= 7);
11767         cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11768     }
11769 
11770     /*
11771      * For FEAT_LPA2 and effective DS, the SH field in the attributes
11772      * was re-purposed for output address bits.  The SH attribute in
11773      * that case comes from TCR_ELx, which we extracted earlier.
11774      */
11775     if (param.ds) {
11776         cacheattrs->shareability = param.sh;
11777     } else {
11778         cacheattrs->shareability = extract32(attrs, 6, 2);
11779     }
11780 
11781     *phys_ptr = descaddr;
11782     *page_size_ptr = page_size;
11783     return false;
11784 
11785 do_fault:
11786     fi->type = fault_type;
11787     fi->level = level;
11788     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11789     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2 ||
11790                                mmu_idx == ARMMMUIdx_Stage2_S);
11791     fi->s1ns = mmu_idx == ARMMMUIdx_Stage2;
11792     return true;
11793 }
11794 
11795 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11796                                                 ARMMMUIdx mmu_idx,
11797                                                 int32_t address, int *prot)
11798 {
11799     if (!arm_feature(env, ARM_FEATURE_M)) {
11800         *prot = PAGE_READ | PAGE_WRITE;
11801         switch (address) {
11802         case 0xF0000000 ... 0xFFFFFFFF:
11803             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11804                 /* hivecs execing is ok */
11805                 *prot |= PAGE_EXEC;
11806             }
11807             break;
11808         case 0x00000000 ... 0x7FFFFFFF:
11809             *prot |= PAGE_EXEC;
11810             break;
11811         }
11812     } else {
11813         /* Default system address map for M profile cores.
11814          * The architecture specifies which regions are execute-never;
11815          * at the MPU level no other checks are defined.
11816          */
11817         switch (address) {
11818         case 0x00000000 ... 0x1fffffff: /* ROM */
11819         case 0x20000000 ... 0x3fffffff: /* SRAM */
11820         case 0x60000000 ... 0x7fffffff: /* RAM */
11821         case 0x80000000 ... 0x9fffffff: /* RAM */
11822             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11823             break;
11824         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11825         case 0xa0000000 ... 0xbfffffff: /* Device */
11826         case 0xc0000000 ... 0xdfffffff: /* Device */
11827         case 0xe0000000 ... 0xffffffff: /* System */
11828             *prot = PAGE_READ | PAGE_WRITE;
11829             break;
11830         default:
11831             g_assert_not_reached();
11832         }
11833     }
11834 }
11835 
11836 static bool pmsav7_use_background_region(ARMCPU *cpu,
11837                                          ARMMMUIdx mmu_idx, bool is_user)
11838 {
11839     /* Return true if we should use the default memory map as a
11840      * "background" region if there are no hits against any MPU regions.
11841      */
11842     CPUARMState *env = &cpu->env;
11843 
11844     if (is_user) {
11845         return false;
11846     }
11847 
11848     if (arm_feature(env, ARM_FEATURE_M)) {
11849         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11850             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11851     } else {
11852         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11853     }
11854 }
11855 
11856 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11857 {
11858     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11859     return arm_feature(env, ARM_FEATURE_M) &&
11860         extract32(address, 20, 12) == 0xe00;
11861 }
11862 
11863 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11864 {
11865     /* True if address is in the M profile system region
11866      * 0xe0000000 - 0xffffffff
11867      */
11868     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11869 }
11870 
11871 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11872                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11873                                  hwaddr *phys_ptr, int *prot,
11874                                  target_ulong *page_size,
11875                                  ARMMMUFaultInfo *fi)
11876 {
11877     ARMCPU *cpu = env_archcpu(env);
11878     int n;
11879     bool is_user = regime_is_user(env, mmu_idx);
11880 
11881     *phys_ptr = address;
11882     *page_size = TARGET_PAGE_SIZE;
11883     *prot = 0;
11884 
11885     if (regime_translation_disabled(env, mmu_idx) ||
11886         m_is_ppb_region(env, address)) {
11887         /* MPU disabled or M profile PPB access: use default memory map.
11888          * The other case which uses the default memory map in the
11889          * v7M ARM ARM pseudocode is exception vector reads from the vector
11890          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11891          * which always does a direct read using address_space_ldl(), rather
11892          * than going via this function, so we don't need to check that here.
11893          */
11894         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11895     } else { /* MPU enabled */
11896         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11897             /* region search */
11898             uint32_t base = env->pmsav7.drbar[n];
11899             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11900             uint32_t rmask;
11901             bool srdis = false;
11902 
11903             if (!(env->pmsav7.drsr[n] & 0x1)) {
11904                 continue;
11905             }
11906 
11907             if (!rsize) {
11908                 qemu_log_mask(LOG_GUEST_ERROR,
11909                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11910                 continue;
11911             }
11912             rsize++;
11913             rmask = (1ull << rsize) - 1;
11914 
11915             if (base & rmask) {
11916                 qemu_log_mask(LOG_GUEST_ERROR,
11917                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11918                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11919                               n, base, rmask);
11920                 continue;
11921             }
11922 
11923             if (address < base || address > base + rmask) {
11924                 /*
11925                  * Address not in this region. We must check whether the
11926                  * region covers addresses in the same page as our address.
11927                  * In that case we must not report a size that covers the
11928                  * whole page for a subsequent hit against a different MPU
11929                  * region or the background region, because it would result in
11930                  * incorrect TLB hits for subsequent accesses to addresses that
11931                  * are in this MPU region.
11932                  */
11933                 if (ranges_overlap(base, rmask,
11934                                    address & TARGET_PAGE_MASK,
11935                                    TARGET_PAGE_SIZE)) {
11936                     *page_size = 1;
11937                 }
11938                 continue;
11939             }
11940 
11941             /* Region matched */
11942 
11943             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11944                 int i, snd;
11945                 uint32_t srdis_mask;
11946 
11947                 rsize -= 3; /* sub region size (power of 2) */
11948                 snd = ((address - base) >> rsize) & 0x7;
11949                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11950 
11951                 srdis_mask = srdis ? 0x3 : 0x0;
11952                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11953                     /* This will check in groups of 2, 4 and then 8, whether
11954                      * the subregion bits are consistent. rsize is incremented
11955                      * back up to give the region size, considering consistent
11956                      * adjacent subregions as one region. Stop testing if rsize
11957                      * is already big enough for an entire QEMU page.
11958                      */
11959                     int snd_rounded = snd & ~(i - 1);
11960                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11961                                                      snd_rounded + 8, i);
11962                     if (srdis_mask ^ srdis_multi) {
11963                         break;
11964                     }
11965                     srdis_mask = (srdis_mask << i) | srdis_mask;
11966                     rsize++;
11967                 }
11968             }
11969             if (srdis) {
11970                 continue;
11971             }
11972             if (rsize < TARGET_PAGE_BITS) {
11973                 *page_size = 1 << rsize;
11974             }
11975             break;
11976         }
11977 
11978         if (n == -1) { /* no hits */
11979             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11980                 /* background fault */
11981                 fi->type = ARMFault_Background;
11982                 return true;
11983             }
11984             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11985         } else { /* a MPU hit! */
11986             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
11987             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
11988 
11989             if (m_is_system_region(env, address)) {
11990                 /* System space is always execute never */
11991                 xn = 1;
11992             }
11993 
11994             if (is_user) { /* User mode AP bit decoding */
11995                 switch (ap) {
11996                 case 0:
11997                 case 1:
11998                 case 5:
11999                     break; /* no access */
12000                 case 3:
12001                     *prot |= PAGE_WRITE;
12002                     /* fall through */
12003                 case 2:
12004                 case 6:
12005                     *prot |= PAGE_READ | PAGE_EXEC;
12006                     break;
12007                 case 7:
12008                     /* for v7M, same as 6; for R profile a reserved value */
12009                     if (arm_feature(env, ARM_FEATURE_M)) {
12010                         *prot |= PAGE_READ | PAGE_EXEC;
12011                         break;
12012                     }
12013                     /* fall through */
12014                 default:
12015                     qemu_log_mask(LOG_GUEST_ERROR,
12016                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12017                                   PRIx32 "\n", n, ap);
12018                 }
12019             } else { /* Priv. mode AP bits decoding */
12020                 switch (ap) {
12021                 case 0:
12022                     break; /* no access */
12023                 case 1:
12024                 case 2:
12025                 case 3:
12026                     *prot |= PAGE_WRITE;
12027                     /* fall through */
12028                 case 5:
12029                 case 6:
12030                     *prot |= PAGE_READ | PAGE_EXEC;
12031                     break;
12032                 case 7:
12033                     /* for v7M, same as 6; for R profile a reserved value */
12034                     if (arm_feature(env, ARM_FEATURE_M)) {
12035                         *prot |= PAGE_READ | PAGE_EXEC;
12036                         break;
12037                     }
12038                     /* fall through */
12039                 default:
12040                     qemu_log_mask(LOG_GUEST_ERROR,
12041                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12042                                   PRIx32 "\n", n, ap);
12043                 }
12044             }
12045 
12046             /* execute never */
12047             if (xn) {
12048                 *prot &= ~PAGE_EXEC;
12049             }
12050         }
12051     }
12052 
12053     fi->type = ARMFault_Permission;
12054     fi->level = 1;
12055     return !(*prot & (1 << access_type));
12056 }
12057 
12058 static bool v8m_is_sau_exempt(CPUARMState *env,
12059                               uint32_t address, MMUAccessType access_type)
12060 {
12061     /* The architecture specifies that certain address ranges are
12062      * exempt from v8M SAU/IDAU checks.
12063      */
12064     return
12065         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
12066         (address >= 0xe0000000 && address <= 0xe0002fff) ||
12067         (address >= 0xe000e000 && address <= 0xe000efff) ||
12068         (address >= 0xe002e000 && address <= 0xe002efff) ||
12069         (address >= 0xe0040000 && address <= 0xe0041fff) ||
12070         (address >= 0xe00ff000 && address <= 0xe00fffff);
12071 }
12072 
12073 void v8m_security_lookup(CPUARMState *env, uint32_t address,
12074                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
12075                                 V8M_SAttributes *sattrs)
12076 {
12077     /* Look up the security attributes for this address. Compare the
12078      * pseudocode SecurityCheck() function.
12079      * We assume the caller has zero-initialized *sattrs.
12080      */
12081     ARMCPU *cpu = env_archcpu(env);
12082     int r;
12083     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
12084     int idau_region = IREGION_NOTVALID;
12085     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12086     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12087 
12088     if (cpu->idau) {
12089         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
12090         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
12091 
12092         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
12093                    &idau_nsc);
12094     }
12095 
12096     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
12097         /* 0xf0000000..0xffffffff is always S for insn fetches */
12098         return;
12099     }
12100 
12101     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
12102         sattrs->ns = !regime_is_secure(env, mmu_idx);
12103         return;
12104     }
12105 
12106     if (idau_region != IREGION_NOTVALID) {
12107         sattrs->irvalid = true;
12108         sattrs->iregion = idau_region;
12109     }
12110 
12111     switch (env->sau.ctrl & 3) {
12112     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
12113         break;
12114     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
12115         sattrs->ns = true;
12116         break;
12117     default: /* SAU.ENABLE == 1 */
12118         for (r = 0; r < cpu->sau_sregion; r++) {
12119             if (env->sau.rlar[r] & 1) {
12120                 uint32_t base = env->sau.rbar[r] & ~0x1f;
12121                 uint32_t limit = env->sau.rlar[r] | 0x1f;
12122 
12123                 if (base <= address && limit >= address) {
12124                     if (base > addr_page_base || limit < addr_page_limit) {
12125                         sattrs->subpage = true;
12126                     }
12127                     if (sattrs->srvalid) {
12128                         /* If we hit in more than one region then we must report
12129                          * as Secure, not NS-Callable, with no valid region
12130                          * number info.
12131                          */
12132                         sattrs->ns = false;
12133                         sattrs->nsc = false;
12134                         sattrs->sregion = 0;
12135                         sattrs->srvalid = false;
12136                         break;
12137                     } else {
12138                         if (env->sau.rlar[r] & 2) {
12139                             sattrs->nsc = true;
12140                         } else {
12141                             sattrs->ns = true;
12142                         }
12143                         sattrs->srvalid = true;
12144                         sattrs->sregion = r;
12145                     }
12146                 } else {
12147                     /*
12148                      * Address not in this region. We must check whether the
12149                      * region covers addresses in the same page as our address.
12150                      * In that case we must not report a size that covers the
12151                      * whole page for a subsequent hit against a different MPU
12152                      * region or the background region, because it would result
12153                      * in incorrect TLB hits for subsequent accesses to
12154                      * addresses that are in this MPU region.
12155                      */
12156                     if (limit >= base &&
12157                         ranges_overlap(base, limit - base + 1,
12158                                        addr_page_base,
12159                                        TARGET_PAGE_SIZE)) {
12160                         sattrs->subpage = true;
12161                     }
12162                 }
12163             }
12164         }
12165         break;
12166     }
12167 
12168     /*
12169      * The IDAU will override the SAU lookup results if it specifies
12170      * higher security than the SAU does.
12171      */
12172     if (!idau_ns) {
12173         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
12174             sattrs->ns = false;
12175             sattrs->nsc = idau_nsc;
12176         }
12177     }
12178 }
12179 
12180 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
12181                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
12182                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
12183                               int *prot, bool *is_subpage,
12184                               ARMMMUFaultInfo *fi, uint32_t *mregion)
12185 {
12186     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
12187      * that a full phys-to-virt translation does).
12188      * mregion is (if not NULL) set to the region number which matched,
12189      * or -1 if no region number is returned (MPU off, address did not
12190      * hit a region, address hit in multiple regions).
12191      * We set is_subpage to true if the region hit doesn't cover the
12192      * entire TARGET_PAGE the address is within.
12193      */
12194     ARMCPU *cpu = env_archcpu(env);
12195     bool is_user = regime_is_user(env, mmu_idx);
12196     uint32_t secure = regime_is_secure(env, mmu_idx);
12197     int n;
12198     int matchregion = -1;
12199     bool hit = false;
12200     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12201     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12202 
12203     *is_subpage = false;
12204     *phys_ptr = address;
12205     *prot = 0;
12206     if (mregion) {
12207         *mregion = -1;
12208     }
12209 
12210     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
12211      * was an exception vector read from the vector table (which is always
12212      * done using the default system address map), because those accesses
12213      * are done in arm_v7m_load_vector(), which always does a direct
12214      * read using address_space_ldl(), rather than going via this function.
12215      */
12216     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
12217         hit = true;
12218     } else if (m_is_ppb_region(env, address)) {
12219         hit = true;
12220     } else {
12221         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12222             hit = true;
12223         }
12224 
12225         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12226             /* region search */
12227             /* Note that the base address is bits [31:5] from the register
12228              * with bits [4:0] all zeroes, but the limit address is bits
12229              * [31:5] from the register with bits [4:0] all ones.
12230              */
12231             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
12232             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
12233 
12234             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
12235                 /* Region disabled */
12236                 continue;
12237             }
12238 
12239             if (address < base || address > limit) {
12240                 /*
12241                  * Address not in this region. We must check whether the
12242                  * region covers addresses in the same page as our address.
12243                  * In that case we must not report a size that covers the
12244                  * whole page for a subsequent hit against a different MPU
12245                  * region or the background region, because it would result in
12246                  * incorrect TLB hits for subsequent accesses to addresses that
12247                  * are in this MPU region.
12248                  */
12249                 if (limit >= base &&
12250                     ranges_overlap(base, limit - base + 1,
12251                                    addr_page_base,
12252                                    TARGET_PAGE_SIZE)) {
12253                     *is_subpage = true;
12254                 }
12255                 continue;
12256             }
12257 
12258             if (base > addr_page_base || limit < addr_page_limit) {
12259                 *is_subpage = true;
12260             }
12261 
12262             if (matchregion != -1) {
12263                 /* Multiple regions match -- always a failure (unlike
12264                  * PMSAv7 where highest-numbered-region wins)
12265                  */
12266                 fi->type = ARMFault_Permission;
12267                 fi->level = 1;
12268                 return true;
12269             }
12270 
12271             matchregion = n;
12272             hit = true;
12273         }
12274     }
12275 
12276     if (!hit) {
12277         /* background fault */
12278         fi->type = ARMFault_Background;
12279         return true;
12280     }
12281 
12282     if (matchregion == -1) {
12283         /* hit using the background region */
12284         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12285     } else {
12286         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
12287         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
12288         bool pxn = false;
12289 
12290         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
12291             pxn = extract32(env->pmsav8.rlar[secure][matchregion], 4, 1);
12292         }
12293 
12294         if (m_is_system_region(env, address)) {
12295             /* System space is always execute never */
12296             xn = 1;
12297         }
12298 
12299         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
12300         if (*prot && !xn && !(pxn && !is_user)) {
12301             *prot |= PAGE_EXEC;
12302         }
12303         /* We don't need to look the attribute up in the MAIR0/MAIR1
12304          * registers because that only tells us about cacheability.
12305          */
12306         if (mregion) {
12307             *mregion = matchregion;
12308         }
12309     }
12310 
12311     fi->type = ARMFault_Permission;
12312     fi->level = 1;
12313     return !(*prot & (1 << access_type));
12314 }
12315 
12316 
12317 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12318                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12319                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12320                                  int *prot, target_ulong *page_size,
12321                                  ARMMMUFaultInfo *fi)
12322 {
12323     uint32_t secure = regime_is_secure(env, mmu_idx);
12324     V8M_SAttributes sattrs = {};
12325     bool ret;
12326     bool mpu_is_subpage;
12327 
12328     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12329         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12330         if (access_type == MMU_INST_FETCH) {
12331             /* Instruction fetches always use the MMU bank and the
12332              * transaction attribute determined by the fetch address,
12333              * regardless of CPU state. This is painful for QEMU
12334              * to handle, because it would mean we need to encode
12335              * into the mmu_idx not just the (user, negpri) information
12336              * for the current security state but also that for the
12337              * other security state, which would balloon the number
12338              * of mmu_idx values needed alarmingly.
12339              * Fortunately we can avoid this because it's not actually
12340              * possible to arbitrarily execute code from memory with
12341              * the wrong security attribute: it will always generate
12342              * an exception of some kind or another, apart from the
12343              * special case of an NS CPU executing an SG instruction
12344              * in S&NSC memory. So we always just fail the translation
12345              * here and sort things out in the exception handler
12346              * (including possibly emulating an SG instruction).
12347              */
12348             if (sattrs.ns != !secure) {
12349                 if (sattrs.nsc) {
12350                     fi->type = ARMFault_QEMU_NSCExec;
12351                 } else {
12352                     fi->type = ARMFault_QEMU_SFault;
12353                 }
12354                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12355                 *phys_ptr = address;
12356                 *prot = 0;
12357                 return true;
12358             }
12359         } else {
12360             /* For data accesses we always use the MMU bank indicated
12361              * by the current CPU state, but the security attributes
12362              * might downgrade a secure access to nonsecure.
12363              */
12364             if (sattrs.ns) {
12365                 txattrs->secure = false;
12366             } else if (!secure) {
12367                 /* NS access to S memory must fault.
12368                  * Architecturally we should first check whether the
12369                  * MPU information for this address indicates that we
12370                  * are doing an unaligned access to Device memory, which
12371                  * should generate a UsageFault instead. QEMU does not
12372                  * currently check for that kind of unaligned access though.
12373                  * If we added it we would need to do so as a special case
12374                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12375                  */
12376                 fi->type = ARMFault_QEMU_SFault;
12377                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12378                 *phys_ptr = address;
12379                 *prot = 0;
12380                 return true;
12381             }
12382         }
12383     }
12384 
12385     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12386                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12387     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12388     return ret;
12389 }
12390 
12391 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12392                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12393                                  hwaddr *phys_ptr, int *prot,
12394                                  ARMMMUFaultInfo *fi)
12395 {
12396     int n;
12397     uint32_t mask;
12398     uint32_t base;
12399     bool is_user = regime_is_user(env, mmu_idx);
12400 
12401     if (regime_translation_disabled(env, mmu_idx)) {
12402         /* MPU disabled.  */
12403         *phys_ptr = address;
12404         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12405         return false;
12406     }
12407 
12408     *phys_ptr = address;
12409     for (n = 7; n >= 0; n--) {
12410         base = env->cp15.c6_region[n];
12411         if ((base & 1) == 0) {
12412             continue;
12413         }
12414         mask = 1 << ((base >> 1) & 0x1f);
12415         /* Keep this shift separate from the above to avoid an
12416            (undefined) << 32.  */
12417         mask = (mask << 1) - 1;
12418         if (((base ^ address) & ~mask) == 0) {
12419             break;
12420         }
12421     }
12422     if (n < 0) {
12423         fi->type = ARMFault_Background;
12424         return true;
12425     }
12426 
12427     if (access_type == MMU_INST_FETCH) {
12428         mask = env->cp15.pmsav5_insn_ap;
12429     } else {
12430         mask = env->cp15.pmsav5_data_ap;
12431     }
12432     mask = (mask >> (n * 4)) & 0xf;
12433     switch (mask) {
12434     case 0:
12435         fi->type = ARMFault_Permission;
12436         fi->level = 1;
12437         return true;
12438     case 1:
12439         if (is_user) {
12440             fi->type = ARMFault_Permission;
12441             fi->level = 1;
12442             return true;
12443         }
12444         *prot = PAGE_READ | PAGE_WRITE;
12445         break;
12446     case 2:
12447         *prot = PAGE_READ;
12448         if (!is_user) {
12449             *prot |= PAGE_WRITE;
12450         }
12451         break;
12452     case 3:
12453         *prot = PAGE_READ | PAGE_WRITE;
12454         break;
12455     case 5:
12456         if (is_user) {
12457             fi->type = ARMFault_Permission;
12458             fi->level = 1;
12459             return true;
12460         }
12461         *prot = PAGE_READ;
12462         break;
12463     case 6:
12464         *prot = PAGE_READ;
12465         break;
12466     default:
12467         /* Bad permission.  */
12468         fi->type = ARMFault_Permission;
12469         fi->level = 1;
12470         return true;
12471     }
12472     *prot |= PAGE_EXEC;
12473     return false;
12474 }
12475 
12476 /* Combine either inner or outer cacheability attributes for normal
12477  * memory, according to table D4-42 and pseudocode procedure
12478  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12479  *
12480  * NB: only stage 1 includes allocation hints (RW bits), leading to
12481  * some asymmetry.
12482  */
12483 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12484 {
12485     if (s1 == 4 || s2 == 4) {
12486         /* non-cacheable has precedence */
12487         return 4;
12488     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12489         /* stage 1 write-through takes precedence */
12490         return s1;
12491     } else if (extract32(s2, 2, 2) == 2) {
12492         /* stage 2 write-through takes precedence, but the allocation hint
12493          * is still taken from stage 1
12494          */
12495         return (2 << 2) | extract32(s1, 0, 2);
12496     } else { /* write-back */
12497         return s1;
12498     }
12499 }
12500 
12501 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12502  * and CombineS1S2Desc()
12503  *
12504  * @s1:      Attributes from stage 1 walk
12505  * @s2:      Attributes from stage 2 walk
12506  */
12507 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
12508 {
12509     uint8_t s1lo, s2lo, s1hi, s2hi;
12510     ARMCacheAttrs ret;
12511     bool tagged = false;
12512 
12513     if (s1.attrs == 0xf0) {
12514         tagged = true;
12515         s1.attrs = 0xff;
12516     }
12517 
12518     s1lo = extract32(s1.attrs, 0, 4);
12519     s2lo = extract32(s2.attrs, 0, 4);
12520     s1hi = extract32(s1.attrs, 4, 4);
12521     s2hi = extract32(s2.attrs, 4, 4);
12522 
12523     /* Combine shareability attributes (table D4-43) */
12524     if (s1.shareability == 2 || s2.shareability == 2) {
12525         /* if either are outer-shareable, the result is outer-shareable */
12526         ret.shareability = 2;
12527     } else if (s1.shareability == 3 || s2.shareability == 3) {
12528         /* if either are inner-shareable, the result is inner-shareable */
12529         ret.shareability = 3;
12530     } else {
12531         /* both non-shareable */
12532         ret.shareability = 0;
12533     }
12534 
12535     /* Combine memory type and cacheability attributes */
12536     if (s1hi == 0 || s2hi == 0) {
12537         /* Device has precedence over normal */
12538         if (s1lo == 0 || s2lo == 0) {
12539             /* nGnRnE has precedence over anything */
12540             ret.attrs = 0;
12541         } else if (s1lo == 4 || s2lo == 4) {
12542             /* non-Reordering has precedence over Reordering */
12543             ret.attrs = 4;  /* nGnRE */
12544         } else if (s1lo == 8 || s2lo == 8) {
12545             /* non-Gathering has precedence over Gathering */
12546             ret.attrs = 8;  /* nGRE */
12547         } else {
12548             ret.attrs = 0xc; /* GRE */
12549         }
12550 
12551         /* Any location for which the resultant memory type is any
12552          * type of Device memory is always treated as Outer Shareable.
12553          */
12554         ret.shareability = 2;
12555     } else { /* Normal memory */
12556         /* Outer/inner cacheability combine independently */
12557         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12558                   | combine_cacheattr_nibble(s1lo, s2lo);
12559 
12560         if (ret.attrs == 0x44) {
12561             /* Any location for which the resultant memory type is Normal
12562              * Inner Non-cacheable, Outer Non-cacheable is always treated
12563              * as Outer Shareable.
12564              */
12565             ret.shareability = 2;
12566         }
12567     }
12568 
12569     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
12570     if (tagged && ret.attrs == 0xff) {
12571         ret.attrs = 0xf0;
12572     }
12573 
12574     return ret;
12575 }
12576 
12577 
12578 /* get_phys_addr - get the physical address for this virtual address
12579  *
12580  * Find the physical address corresponding to the given virtual address,
12581  * by doing a translation table walk on MMU based systems or using the
12582  * MPU state on MPU based systems.
12583  *
12584  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12585  * prot and page_size may not be filled in, and the populated fsr value provides
12586  * information on why the translation aborted, in the format of a
12587  * DFSR/IFSR fault register, with the following caveats:
12588  *  * we honour the short vs long DFSR format differences.
12589  *  * the WnR bit is never set (the caller must do this).
12590  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12591  *    value.
12592  *
12593  * @env: CPUARMState
12594  * @address: virtual address to get physical address for
12595  * @access_type: 0 for read, 1 for write, 2 for execute
12596  * @mmu_idx: MMU index indicating required translation regime
12597  * @phys_ptr: set to the physical address corresponding to the virtual address
12598  * @attrs: set to the memory transaction attributes to use
12599  * @prot: set to the permissions for the page containing phys_ptr
12600  * @page_size: set to the size of the page containing phys_ptr
12601  * @fi: set to fault info if the translation fails
12602  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12603  */
12604 bool get_phys_addr(CPUARMState *env, target_ulong address,
12605                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12606                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12607                    target_ulong *page_size,
12608                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12609 {
12610     ARMMMUIdx s1_mmu_idx = stage_1_mmu_idx(mmu_idx);
12611 
12612     if (mmu_idx != s1_mmu_idx) {
12613         /* Call ourselves recursively to do the stage 1 and then stage 2
12614          * translations if mmu_idx is a two-stage regime.
12615          */
12616         if (arm_feature(env, ARM_FEATURE_EL2)) {
12617             hwaddr ipa;
12618             int s2_prot;
12619             int ret;
12620             bool ipa_secure;
12621             ARMCacheAttrs cacheattrs2 = {};
12622             ARMMMUIdx s2_mmu_idx;
12623             bool is_el0;
12624 
12625             ret = get_phys_addr(env, address, access_type, s1_mmu_idx, &ipa,
12626                                 attrs, prot, page_size, fi, cacheattrs);
12627 
12628             /* If S1 fails or S2 is disabled, return early.  */
12629             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
12630                 *phys_ptr = ipa;
12631                 return ret;
12632             }
12633 
12634             ipa_secure = attrs->secure;
12635             if (arm_is_secure_below_el3(env)) {
12636                 if (ipa_secure) {
12637                     attrs->secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
12638                 } else {
12639                     attrs->secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
12640                 }
12641             } else {
12642                 assert(!ipa_secure);
12643             }
12644 
12645             s2_mmu_idx = attrs->secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
12646             is_el0 = mmu_idx == ARMMMUIdx_E10_0 || mmu_idx == ARMMMUIdx_SE10_0;
12647 
12648             /* S1 is done. Now do S2 translation.  */
12649             ret = get_phys_addr_lpae(env, ipa, access_type, s2_mmu_idx, is_el0,
12650                                      phys_ptr, attrs, &s2_prot,
12651                                      page_size, fi, &cacheattrs2);
12652             fi->s2addr = ipa;
12653             /* Combine the S1 and S2 perms.  */
12654             *prot &= s2_prot;
12655 
12656             /* If S2 fails, return early.  */
12657             if (ret) {
12658                 return ret;
12659             }
12660 
12661             /* Combine the S1 and S2 cache attributes. */
12662             if (arm_hcr_el2_eff(env) & HCR_DC) {
12663                 /*
12664                  * HCR.DC forces the first stage attributes to
12665                  *  Normal Non-Shareable,
12666                  *  Inner Write-Back Read-Allocate Write-Allocate,
12667                  *  Outer Write-Back Read-Allocate Write-Allocate.
12668                  * Do not overwrite Tagged within attrs.
12669                  */
12670                 if (cacheattrs->attrs != 0xf0) {
12671                     cacheattrs->attrs = 0xff;
12672                 }
12673                 cacheattrs->shareability = 0;
12674             }
12675             *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12676 
12677             /* Check if IPA translates to secure or non-secure PA space. */
12678             if (arm_is_secure_below_el3(env)) {
12679                 if (ipa_secure) {
12680                     attrs->secure =
12681                         !(env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW));
12682                 } else {
12683                     attrs->secure =
12684                         !((env->cp15.vtcr_el2.raw_tcr & (VTCR_NSA | VTCR_NSW))
12685                         || (env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW)));
12686                 }
12687             }
12688             return 0;
12689         } else {
12690             /*
12691              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12692              */
12693             mmu_idx = stage_1_mmu_idx(mmu_idx);
12694         }
12695     }
12696 
12697     /* The page table entries may downgrade secure to non-secure, but
12698      * cannot upgrade an non-secure translation regime's attributes
12699      * to secure.
12700      */
12701     attrs->secure = regime_is_secure(env, mmu_idx);
12702     attrs->user = regime_is_user(env, mmu_idx);
12703 
12704     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12705      * In v7 and earlier it affects all stage 1 translations.
12706      */
12707     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
12708         && !arm_feature(env, ARM_FEATURE_V8)) {
12709         if (regime_el(env, mmu_idx) == 3) {
12710             address += env->cp15.fcseidr_s;
12711         } else {
12712             address += env->cp15.fcseidr_ns;
12713         }
12714     }
12715 
12716     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12717         bool ret;
12718         *page_size = TARGET_PAGE_SIZE;
12719 
12720         if (arm_feature(env, ARM_FEATURE_V8)) {
12721             /* PMSAv8 */
12722             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12723                                        phys_ptr, attrs, prot, page_size, fi);
12724         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12725             /* PMSAv7 */
12726             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12727                                        phys_ptr, prot, page_size, fi);
12728         } else {
12729             /* Pre-v7 MPU */
12730             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12731                                        phys_ptr, prot, fi);
12732         }
12733         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12734                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12735                       access_type == MMU_DATA_LOAD ? "reading" :
12736                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12737                       (uint32_t)address, mmu_idx,
12738                       ret ? "Miss" : "Hit",
12739                       *prot & PAGE_READ ? 'r' : '-',
12740                       *prot & PAGE_WRITE ? 'w' : '-',
12741                       *prot & PAGE_EXEC ? 'x' : '-');
12742 
12743         return ret;
12744     }
12745 
12746     /* Definitely a real MMU, not an MPU */
12747 
12748     if (regime_translation_disabled(env, mmu_idx)) {
12749         uint64_t hcr;
12750         uint8_t memattr;
12751 
12752         /*
12753          * MMU disabled.  S1 addresses within aa64 translation regimes are
12754          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
12755          */
12756         if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
12757             int r_el = regime_el(env, mmu_idx);
12758             if (arm_el_is_aa64(env, r_el)) {
12759                 int pamax = arm_pamax(env_archcpu(env));
12760                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
12761                 int addrtop, tbi;
12762 
12763                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
12764                 if (access_type == MMU_INST_FETCH) {
12765                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
12766                 }
12767                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
12768                 addrtop = (tbi ? 55 : 63);
12769 
12770                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
12771                     fi->type = ARMFault_AddressSize;
12772                     fi->level = 0;
12773                     fi->stage2 = false;
12774                     return 1;
12775                 }
12776 
12777                 /*
12778                  * When TBI is disabled, we've just validated that all of the
12779                  * bits above PAMax are zero, so logically we only need to
12780                  * clear the top byte for TBI.  But it's clearer to follow
12781                  * the pseudocode set of addrdesc.paddress.
12782                  */
12783                 address = extract64(address, 0, 52);
12784             }
12785         }
12786         *phys_ptr = address;
12787         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12788         *page_size = TARGET_PAGE_SIZE;
12789 
12790         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
12791         hcr = arm_hcr_el2_eff(env);
12792         cacheattrs->shareability = 0;
12793         if (hcr & HCR_DC) {
12794             if (hcr & HCR_DCT) {
12795                 memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
12796             } else {
12797                 memattr = 0xff;  /* Normal, WB, RWA */
12798             }
12799         } else if (access_type == MMU_INST_FETCH) {
12800             if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
12801                 memattr = 0xee;  /* Normal, WT, RA, NT */
12802             } else {
12803                 memattr = 0x44;  /* Normal, NC, No */
12804             }
12805             cacheattrs->shareability = 2; /* outer sharable */
12806         } else {
12807             memattr = 0x00;      /* Device, nGnRnE */
12808         }
12809         cacheattrs->attrs = memattr;
12810         return 0;
12811     }
12812 
12813     if (regime_using_lpae_format(env, mmu_idx)) {
12814         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
12815                                   phys_ptr, attrs, prot, page_size,
12816                                   fi, cacheattrs);
12817     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12818         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12819                                 phys_ptr, attrs, prot, page_size, fi);
12820     } else {
12821         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12822                                     phys_ptr, prot, page_size, fi);
12823     }
12824 }
12825 
12826 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12827                                          MemTxAttrs *attrs)
12828 {
12829     ARMCPU *cpu = ARM_CPU(cs);
12830     CPUARMState *env = &cpu->env;
12831     hwaddr phys_addr;
12832     target_ulong page_size;
12833     int prot;
12834     bool ret;
12835     ARMMMUFaultInfo fi = {};
12836     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12837     ARMCacheAttrs cacheattrs = {};
12838 
12839     *attrs = (MemTxAttrs) {};
12840 
12841     ret = get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &phys_addr,
12842                         attrs, &prot, &page_size, &fi, &cacheattrs);
12843 
12844     if (ret) {
12845         return -1;
12846     }
12847     return phys_addr;
12848 }
12849 
12850 #endif
12851 
12852 /* Note that signed overflow is undefined in C.  The following routines are
12853    careful to use unsigned types where modulo arithmetic is required.
12854    Failure to do so _will_ break on newer gcc.  */
12855 
12856 /* Signed saturating arithmetic.  */
12857 
12858 /* Perform 16-bit signed saturating addition.  */
12859 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
12860 {
12861     uint16_t res;
12862 
12863     res = a + b;
12864     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
12865         if (a & 0x8000)
12866             res = 0x8000;
12867         else
12868             res = 0x7fff;
12869     }
12870     return res;
12871 }
12872 
12873 /* Perform 8-bit signed saturating addition.  */
12874 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
12875 {
12876     uint8_t res;
12877 
12878     res = a + b;
12879     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
12880         if (a & 0x80)
12881             res = 0x80;
12882         else
12883             res = 0x7f;
12884     }
12885     return res;
12886 }
12887 
12888 /* Perform 16-bit signed saturating subtraction.  */
12889 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
12890 {
12891     uint16_t res;
12892 
12893     res = a - b;
12894     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
12895         if (a & 0x8000)
12896             res = 0x8000;
12897         else
12898             res = 0x7fff;
12899     }
12900     return res;
12901 }
12902 
12903 /* Perform 8-bit signed saturating subtraction.  */
12904 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
12905 {
12906     uint8_t res;
12907 
12908     res = a - b;
12909     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
12910         if (a & 0x80)
12911             res = 0x80;
12912         else
12913             res = 0x7f;
12914     }
12915     return res;
12916 }
12917 
12918 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
12919 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
12920 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
12921 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
12922 #define PFX q
12923 
12924 #include "op_addsub.h"
12925 
12926 /* Unsigned saturating arithmetic.  */
12927 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
12928 {
12929     uint16_t res;
12930     res = a + b;
12931     if (res < a)
12932         res = 0xffff;
12933     return res;
12934 }
12935 
12936 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
12937 {
12938     if (a > b)
12939         return a - b;
12940     else
12941         return 0;
12942 }
12943 
12944 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
12945 {
12946     uint8_t res;
12947     res = a + b;
12948     if (res < a)
12949         res = 0xff;
12950     return res;
12951 }
12952 
12953 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
12954 {
12955     if (a > b)
12956         return a - b;
12957     else
12958         return 0;
12959 }
12960 
12961 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
12962 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
12963 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
12964 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
12965 #define PFX uq
12966 
12967 #include "op_addsub.h"
12968 
12969 /* Signed modulo arithmetic.  */
12970 #define SARITH16(a, b, n, op) do { \
12971     int32_t sum; \
12972     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
12973     RESULT(sum, n, 16); \
12974     if (sum >= 0) \
12975         ge |= 3 << (n * 2); \
12976     } while(0)
12977 
12978 #define SARITH8(a, b, n, op) do { \
12979     int32_t sum; \
12980     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
12981     RESULT(sum, n, 8); \
12982     if (sum >= 0) \
12983         ge |= 1 << n; \
12984     } while(0)
12985 
12986 
12987 #define ADD16(a, b, n) SARITH16(a, b, n, +)
12988 #define SUB16(a, b, n) SARITH16(a, b, n, -)
12989 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
12990 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
12991 #define PFX s
12992 #define ARITH_GE
12993 
12994 #include "op_addsub.h"
12995 
12996 /* Unsigned modulo arithmetic.  */
12997 #define ADD16(a, b, n) do { \
12998     uint32_t sum; \
12999     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
13000     RESULT(sum, n, 16); \
13001     if ((sum >> 16) == 1) \
13002         ge |= 3 << (n * 2); \
13003     } while(0)
13004 
13005 #define ADD8(a, b, n) do { \
13006     uint32_t sum; \
13007     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
13008     RESULT(sum, n, 8); \
13009     if ((sum >> 8) == 1) \
13010         ge |= 1 << n; \
13011     } while(0)
13012 
13013 #define SUB16(a, b, n) do { \
13014     uint32_t sum; \
13015     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
13016     RESULT(sum, n, 16); \
13017     if ((sum >> 16) == 0) \
13018         ge |= 3 << (n * 2); \
13019     } while(0)
13020 
13021 #define SUB8(a, b, n) do { \
13022     uint32_t sum; \
13023     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
13024     RESULT(sum, n, 8); \
13025     if ((sum >> 8) == 0) \
13026         ge |= 1 << n; \
13027     } while(0)
13028 
13029 #define PFX u
13030 #define ARITH_GE
13031 
13032 #include "op_addsub.h"
13033 
13034 /* Halved signed arithmetic.  */
13035 #define ADD16(a, b, n) \
13036   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
13037 #define SUB16(a, b, n) \
13038   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
13039 #define ADD8(a, b, n) \
13040   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
13041 #define SUB8(a, b, n) \
13042   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
13043 #define PFX sh
13044 
13045 #include "op_addsub.h"
13046 
13047 /* Halved unsigned arithmetic.  */
13048 #define ADD16(a, b, n) \
13049   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13050 #define SUB16(a, b, n) \
13051   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13052 #define ADD8(a, b, n) \
13053   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13054 #define SUB8(a, b, n) \
13055   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13056 #define PFX uh
13057 
13058 #include "op_addsub.h"
13059 
13060 static inline uint8_t do_usad(uint8_t a, uint8_t b)
13061 {
13062     if (a > b)
13063         return a - b;
13064     else
13065         return b - a;
13066 }
13067 
13068 /* Unsigned sum of absolute byte differences.  */
13069 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
13070 {
13071     uint32_t sum;
13072     sum = do_usad(a, b);
13073     sum += do_usad(a >> 8, b >> 8);
13074     sum += do_usad(a >> 16, b >> 16);
13075     sum += do_usad(a >> 24, b >> 24);
13076     return sum;
13077 }
13078 
13079 /* For ARMv6 SEL instruction.  */
13080 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
13081 {
13082     uint32_t mask;
13083 
13084     mask = 0;
13085     if (flags & 1)
13086         mask |= 0xff;
13087     if (flags & 2)
13088         mask |= 0xff00;
13089     if (flags & 4)
13090         mask |= 0xff0000;
13091     if (flags & 8)
13092         mask |= 0xff000000;
13093     return (a & mask) | (b & ~mask);
13094 }
13095 
13096 /* CRC helpers.
13097  * The upper bytes of val (above the number specified by 'bytes') must have
13098  * been zeroed out by the caller.
13099  */
13100 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
13101 {
13102     uint8_t buf[4];
13103 
13104     stl_le_p(buf, val);
13105 
13106     /* zlib crc32 converts the accumulator and output to one's complement.  */
13107     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
13108 }
13109 
13110 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
13111 {
13112     uint8_t buf[4];
13113 
13114     stl_le_p(buf, val);
13115 
13116     /* Linux crc32c converts the output to one's complement.  */
13117     return crc32c(acc, buf, bytes) ^ 0xffffffff;
13118 }
13119 
13120 /* Return the exception level to which FP-disabled exceptions should
13121  * be taken, or 0 if FP is enabled.
13122  */
13123 int fp_exception_el(CPUARMState *env, int cur_el)
13124 {
13125 #ifndef CONFIG_USER_ONLY
13126     uint64_t hcr_el2;
13127 
13128     /* CPACR and the CPTR registers don't exist before v6, so FP is
13129      * always accessible
13130      */
13131     if (!arm_feature(env, ARM_FEATURE_V6)) {
13132         return 0;
13133     }
13134 
13135     if (arm_feature(env, ARM_FEATURE_M)) {
13136         /* CPACR can cause a NOCP UsageFault taken to current security state */
13137         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
13138             return 1;
13139         }
13140 
13141         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
13142             if (!extract32(env->v7m.nsacr, 10, 1)) {
13143                 /* FP insns cause a NOCP UsageFault taken to Secure */
13144                 return 3;
13145             }
13146         }
13147 
13148         return 0;
13149     }
13150 
13151     hcr_el2 = arm_hcr_el2_eff(env);
13152 
13153     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
13154      * 0, 2 : trap EL0 and EL1/PL1 accesses
13155      * 1    : trap only EL0 accesses
13156      * 3    : trap no accesses
13157      * This register is ignored if E2H+TGE are both set.
13158      */
13159     if ((hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13160         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
13161 
13162         switch (fpen) {
13163         case 0:
13164         case 2:
13165             if (cur_el == 0 || cur_el == 1) {
13166                 /* Trap to PL1, which might be EL1 or EL3 */
13167                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
13168                     return 3;
13169                 }
13170                 return 1;
13171             }
13172             if (cur_el == 3 && !is_a64(env)) {
13173                 /* Secure PL1 running at EL3 */
13174                 return 3;
13175             }
13176             break;
13177         case 1:
13178             if (cur_el == 0) {
13179                 return 1;
13180             }
13181             break;
13182         case 3:
13183             break;
13184         }
13185     }
13186 
13187     /*
13188      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
13189      * to control non-secure access to the FPU. It doesn't have any
13190      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
13191      */
13192     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
13193          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
13194         if (!extract32(env->cp15.nsacr, 10, 1)) {
13195             /* FP insns act as UNDEF */
13196             return cur_el == 2 ? 2 : 1;
13197         }
13198     }
13199 
13200     /*
13201      * CPTR_EL2 is present in v7VE or v8, and changes format
13202      * with HCR_EL2.E2H (regardless of TGE).
13203      */
13204     if (cur_el <= 2) {
13205         if (hcr_el2 & HCR_E2H) {
13206             /* Check CPTR_EL2.FPEN.  */
13207             switch (extract32(env->cp15.cptr_el[2], 20, 2)) {
13208             case 1:
13209                 if (cur_el != 0 || !(hcr_el2 & HCR_TGE)) {
13210                     break;
13211                 }
13212                 /* fall through */
13213             case 0:
13214             case 2:
13215                 return 2;
13216             }
13217         } else if (arm_is_el2_enabled(env)) {
13218             if (env->cp15.cptr_el[2] & CPTR_TFP) {
13219                 return 2;
13220             }
13221         }
13222     }
13223 
13224     /* CPTR_EL3 : present in v8 */
13225     if (env->cp15.cptr_el[3] & CPTR_TFP) {
13226         /* Trap all FP ops to EL3 */
13227         return 3;
13228     }
13229 #endif
13230     return 0;
13231 }
13232 
13233 /* Return the exception level we're running at if this is our mmu_idx */
13234 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
13235 {
13236     if (mmu_idx & ARM_MMU_IDX_M) {
13237         return mmu_idx & ARM_MMU_IDX_M_PRIV;
13238     }
13239 
13240     switch (mmu_idx) {
13241     case ARMMMUIdx_E10_0:
13242     case ARMMMUIdx_E20_0:
13243     case ARMMMUIdx_SE10_0:
13244     case ARMMMUIdx_SE20_0:
13245         return 0;
13246     case ARMMMUIdx_E10_1:
13247     case ARMMMUIdx_E10_1_PAN:
13248     case ARMMMUIdx_SE10_1:
13249     case ARMMMUIdx_SE10_1_PAN:
13250         return 1;
13251     case ARMMMUIdx_E2:
13252     case ARMMMUIdx_E20_2:
13253     case ARMMMUIdx_E20_2_PAN:
13254     case ARMMMUIdx_SE2:
13255     case ARMMMUIdx_SE20_2:
13256     case ARMMMUIdx_SE20_2_PAN:
13257         return 2;
13258     case ARMMMUIdx_SE3:
13259         return 3;
13260     default:
13261         g_assert_not_reached();
13262     }
13263 }
13264 
13265 #ifndef CONFIG_TCG
13266 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
13267 {
13268     g_assert_not_reached();
13269 }
13270 #endif
13271 
13272 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
13273 {
13274     ARMMMUIdx idx;
13275     uint64_t hcr;
13276 
13277     if (arm_feature(env, ARM_FEATURE_M)) {
13278         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
13279     }
13280 
13281     /* See ARM pseudo-function ELIsInHost.  */
13282     switch (el) {
13283     case 0:
13284         hcr = arm_hcr_el2_eff(env);
13285         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
13286             idx = ARMMMUIdx_E20_0;
13287         } else {
13288             idx = ARMMMUIdx_E10_0;
13289         }
13290         break;
13291     case 1:
13292         if (env->pstate & PSTATE_PAN) {
13293             idx = ARMMMUIdx_E10_1_PAN;
13294         } else {
13295             idx = ARMMMUIdx_E10_1;
13296         }
13297         break;
13298     case 2:
13299         /* Note that TGE does not apply at EL2.  */
13300         if (arm_hcr_el2_eff(env) & HCR_E2H) {
13301             if (env->pstate & PSTATE_PAN) {
13302                 idx = ARMMMUIdx_E20_2_PAN;
13303             } else {
13304                 idx = ARMMMUIdx_E20_2;
13305             }
13306         } else {
13307             idx = ARMMMUIdx_E2;
13308         }
13309         break;
13310     case 3:
13311         return ARMMMUIdx_SE3;
13312     default:
13313         g_assert_not_reached();
13314     }
13315 
13316     if (arm_is_secure_below_el3(env)) {
13317         idx &= ~ARM_MMU_IDX_A_NS;
13318     }
13319 
13320     return idx;
13321 }
13322 
13323 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
13324 {
13325     return arm_mmu_idx_el(env, arm_current_el(env));
13326 }
13327 
13328 #ifndef CONFIG_USER_ONLY
13329 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
13330 {
13331     return stage_1_mmu_idx(arm_mmu_idx(env));
13332 }
13333 #endif
13334 
13335 static CPUARMTBFlags rebuild_hflags_common(CPUARMState *env, int fp_el,
13336                                            ARMMMUIdx mmu_idx,
13337                                            CPUARMTBFlags flags)
13338 {
13339     DP_TBFLAG_ANY(flags, FPEXC_EL, fp_el);
13340     DP_TBFLAG_ANY(flags, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
13341 
13342     if (arm_singlestep_active(env)) {
13343         DP_TBFLAG_ANY(flags, SS_ACTIVE, 1);
13344     }
13345     return flags;
13346 }
13347 
13348 static CPUARMTBFlags rebuild_hflags_common_32(CPUARMState *env, int fp_el,
13349                                               ARMMMUIdx mmu_idx,
13350                                               CPUARMTBFlags flags)
13351 {
13352     bool sctlr_b = arm_sctlr_b(env);
13353 
13354     if (sctlr_b) {
13355         DP_TBFLAG_A32(flags, SCTLR__B, 1);
13356     }
13357     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
13358         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13359     }
13360     DP_TBFLAG_A32(flags, NS, !access_secure_reg(env));
13361 
13362     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13363 }
13364 
13365 static CPUARMTBFlags rebuild_hflags_m32(CPUARMState *env, int fp_el,
13366                                         ARMMMUIdx mmu_idx)
13367 {
13368     CPUARMTBFlags flags = {};
13369     uint32_t ccr = env->v7m.ccr[env->v7m.secure];
13370 
13371     /* Without HaveMainExt, CCR.UNALIGN_TRP is RES1. */
13372     if (ccr & R_V7M_CCR_UNALIGN_TRP_MASK) {
13373         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13374     }
13375 
13376     if (arm_v7m_is_handler_mode(env)) {
13377         DP_TBFLAG_M32(flags, HANDLER, 1);
13378     }
13379 
13380     /*
13381      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
13382      * is suppressing them because the requested execution priority
13383      * is less than 0.
13384      */
13385     if (arm_feature(env, ARM_FEATURE_V8) &&
13386         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
13387           (ccr & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13388         DP_TBFLAG_M32(flags, STACKCHECK, 1);
13389     }
13390 
13391     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13392 }
13393 
13394 static CPUARMTBFlags rebuild_hflags_aprofile(CPUARMState *env)
13395 {
13396     CPUARMTBFlags flags = {};
13397 
13398     DP_TBFLAG_ANY(flags, DEBUG_TARGET_EL, arm_debug_target_el(env));
13399     return flags;
13400 }
13401 
13402 static CPUARMTBFlags rebuild_hflags_a32(CPUARMState *env, int fp_el,
13403                                         ARMMMUIdx mmu_idx)
13404 {
13405     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13406     int el = arm_current_el(env);
13407 
13408     if (arm_sctlr(env, el) & SCTLR_A) {
13409         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13410     }
13411 
13412     if (arm_el_is_aa64(env, 1)) {
13413         DP_TBFLAG_A32(flags, VFPEN, 1);
13414     }
13415 
13416     if (el < 2 && env->cp15.hstr_el2 &&
13417         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13418         DP_TBFLAG_A32(flags, HSTR_ACTIVE, 1);
13419     }
13420 
13421     if (env->uncached_cpsr & CPSR_IL) {
13422         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13423     }
13424 
13425     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13426 }
13427 
13428 static CPUARMTBFlags rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
13429                                         ARMMMUIdx mmu_idx)
13430 {
13431     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13432     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13433     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
13434     uint64_t sctlr;
13435     int tbii, tbid;
13436 
13437     DP_TBFLAG_ANY(flags, AARCH64_STATE, 1);
13438 
13439     /* Get control bits for tagged addresses.  */
13440     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
13441     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
13442 
13443     DP_TBFLAG_A64(flags, TBII, tbii);
13444     DP_TBFLAG_A64(flags, TBID, tbid);
13445 
13446     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
13447         int sve_el = sve_exception_el(env, el);
13448         uint32_t zcr_len;
13449 
13450         /*
13451          * If SVE is disabled, but FP is enabled,
13452          * then the effective len is 0.
13453          */
13454         if (sve_el != 0 && fp_el == 0) {
13455             zcr_len = 0;
13456         } else {
13457             zcr_len = sve_zcr_len_for_el(env, el);
13458         }
13459         DP_TBFLAG_A64(flags, SVEEXC_EL, sve_el);
13460         DP_TBFLAG_A64(flags, ZCR_LEN, zcr_len);
13461     }
13462 
13463     sctlr = regime_sctlr(env, stage1);
13464 
13465     if (sctlr & SCTLR_A) {
13466         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13467     }
13468 
13469     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
13470         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13471     }
13472 
13473     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
13474         /*
13475          * In order to save space in flags, we record only whether
13476          * pauth is "inactive", meaning all insns are implemented as
13477          * a nop, or "active" when some action must be performed.
13478          * The decision of which action to take is left to a helper.
13479          */
13480         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13481             DP_TBFLAG_A64(flags, PAUTH_ACTIVE, 1);
13482         }
13483     }
13484 
13485     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13486         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13487         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13488             DP_TBFLAG_A64(flags, BT, 1);
13489         }
13490     }
13491 
13492     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
13493     if (!(env->pstate & PSTATE_UAO)) {
13494         switch (mmu_idx) {
13495         case ARMMMUIdx_E10_1:
13496         case ARMMMUIdx_E10_1_PAN:
13497         case ARMMMUIdx_SE10_1:
13498         case ARMMMUIdx_SE10_1_PAN:
13499             /* TODO: ARMv8.3-NV */
13500             DP_TBFLAG_A64(flags, UNPRIV, 1);
13501             break;
13502         case ARMMMUIdx_E20_2:
13503         case ARMMMUIdx_E20_2_PAN:
13504         case ARMMMUIdx_SE20_2:
13505         case ARMMMUIdx_SE20_2_PAN:
13506             /*
13507              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
13508              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
13509              */
13510             if (env->cp15.hcr_el2 & HCR_TGE) {
13511                 DP_TBFLAG_A64(flags, UNPRIV, 1);
13512             }
13513             break;
13514         default:
13515             break;
13516         }
13517     }
13518 
13519     if (env->pstate & PSTATE_IL) {
13520         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13521     }
13522 
13523     if (cpu_isar_feature(aa64_mte, env_archcpu(env))) {
13524         /*
13525          * Set MTE_ACTIVE if any access may be Checked, and leave clear
13526          * if all accesses must be Unchecked:
13527          * 1) If no TBI, then there are no tags in the address to check,
13528          * 2) If Tag Check Override, then all accesses are Unchecked,
13529          * 3) If Tag Check Fail == 0, then Checked access have no effect,
13530          * 4) If no Allocation Tag Access, then all accesses are Unchecked.
13531          */
13532         if (allocation_tag_access_enabled(env, el, sctlr)) {
13533             DP_TBFLAG_A64(flags, ATA, 1);
13534             if (tbid
13535                 && !(env->pstate & PSTATE_TCO)
13536                 && (sctlr & (el == 0 ? SCTLR_TCF0 : SCTLR_TCF))) {
13537                 DP_TBFLAG_A64(flags, MTE_ACTIVE, 1);
13538             }
13539         }
13540         /* And again for unprivileged accesses, if required.  */
13541         if (EX_TBFLAG_A64(flags, UNPRIV)
13542             && tbid
13543             && !(env->pstate & PSTATE_TCO)
13544             && (sctlr & SCTLR_TCF0)
13545             && allocation_tag_access_enabled(env, 0, sctlr)) {
13546             DP_TBFLAG_A64(flags, MTE0_ACTIVE, 1);
13547         }
13548         /* Cache TCMA as well as TBI. */
13549         DP_TBFLAG_A64(flags, TCMA, aa64_va_parameter_tcma(tcr, mmu_idx));
13550     }
13551 
13552     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13553 }
13554 
13555 static CPUARMTBFlags rebuild_hflags_internal(CPUARMState *env)
13556 {
13557     int el = arm_current_el(env);
13558     int fp_el = fp_exception_el(env, el);
13559     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13560 
13561     if (is_a64(env)) {
13562         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13563     } else if (arm_feature(env, ARM_FEATURE_M)) {
13564         return rebuild_hflags_m32(env, fp_el, mmu_idx);
13565     } else {
13566         return rebuild_hflags_a32(env, fp_el, mmu_idx);
13567     }
13568 }
13569 
13570 void arm_rebuild_hflags(CPUARMState *env)
13571 {
13572     env->hflags = rebuild_hflags_internal(env);
13573 }
13574 
13575 /*
13576  * If we have triggered a EL state change we can't rely on the
13577  * translator having passed it to us, we need to recompute.
13578  */
13579 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
13580 {
13581     int el = arm_current_el(env);
13582     int fp_el = fp_exception_el(env, el);
13583     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13584 
13585     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13586 }
13587 
13588 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
13589 {
13590     int fp_el = fp_exception_el(env, el);
13591     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13592 
13593     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13594 }
13595 
13596 /*
13597  * If we have triggered a EL state change we can't rely on the
13598  * translator having passed it to us, we need to recompute.
13599  */
13600 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
13601 {
13602     int el = arm_current_el(env);
13603     int fp_el = fp_exception_el(env, el);
13604     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13605     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13606 }
13607 
13608 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
13609 {
13610     int fp_el = fp_exception_el(env, el);
13611     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13612 
13613     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13614 }
13615 
13616 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
13617 {
13618     int fp_el = fp_exception_el(env, el);
13619     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13620 
13621     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13622 }
13623 
13624 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
13625 {
13626 #ifdef CONFIG_DEBUG_TCG
13627     CPUARMTBFlags c = env->hflags;
13628     CPUARMTBFlags r = rebuild_hflags_internal(env);
13629 
13630     if (unlikely(c.flags != r.flags || c.flags2 != r.flags2)) {
13631         fprintf(stderr, "TCG hflags mismatch "
13632                         "(current:(0x%08x,0x" TARGET_FMT_lx ")"
13633                         " rebuilt:(0x%08x,0x" TARGET_FMT_lx ")\n",
13634                 c.flags, c.flags2, r.flags, r.flags2);
13635         abort();
13636     }
13637 #endif
13638 }
13639 
13640 static bool mve_no_pred(CPUARMState *env)
13641 {
13642     /*
13643      * Return true if there is definitely no predication of MVE
13644      * instructions by VPR or LTPSIZE. (Returning false even if there
13645      * isn't any predication is OK; generated code will just be
13646      * a little worse.)
13647      * If the CPU does not implement MVE then this TB flag is always 0.
13648      *
13649      * NOTE: if you change this logic, the "recalculate s->mve_no_pred"
13650      * logic in gen_update_fp_context() needs to be updated to match.
13651      *
13652      * We do not include the effect of the ECI bits here -- they are
13653      * tracked in other TB flags. This simplifies the logic for
13654      * "when did we emit code that changes the MVE_NO_PRED TB flag
13655      * and thus need to end the TB?".
13656      */
13657     if (cpu_isar_feature(aa32_mve, env_archcpu(env))) {
13658         return false;
13659     }
13660     if (env->v7m.vpr) {
13661         return false;
13662     }
13663     if (env->v7m.ltpsize < 4) {
13664         return false;
13665     }
13666     return true;
13667 }
13668 
13669 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13670                           target_ulong *cs_base, uint32_t *pflags)
13671 {
13672     CPUARMTBFlags flags;
13673 
13674     assert_hflags_rebuild_correctly(env);
13675     flags = env->hflags;
13676 
13677     if (EX_TBFLAG_ANY(flags, AARCH64_STATE)) {
13678         *pc = env->pc;
13679         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13680             DP_TBFLAG_A64(flags, BTYPE, env->btype);
13681         }
13682     } else {
13683         *pc = env->regs[15];
13684 
13685         if (arm_feature(env, ARM_FEATURE_M)) {
13686             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13687                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
13688                 != env->v7m.secure) {
13689                 DP_TBFLAG_M32(flags, FPCCR_S_WRONG, 1);
13690             }
13691 
13692             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13693                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13694                  (env->v7m.secure &&
13695                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13696                 /*
13697                  * ASPEN is set, but FPCA/SFPA indicate that there is no
13698                  * active FP context; we must create a new FP context before
13699                  * executing any FP insn.
13700                  */
13701                 DP_TBFLAG_M32(flags, NEW_FP_CTXT_NEEDED, 1);
13702             }
13703 
13704             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13705             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13706                 DP_TBFLAG_M32(flags, LSPACT, 1);
13707             }
13708 
13709             if (mve_no_pred(env)) {
13710                 DP_TBFLAG_M32(flags, MVE_NO_PRED, 1);
13711             }
13712         } else {
13713             /*
13714              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
13715              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
13716              */
13717             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13718                 DP_TBFLAG_A32(flags, XSCALE_CPAR, env->cp15.c15_cpar);
13719             } else {
13720                 DP_TBFLAG_A32(flags, VECLEN, env->vfp.vec_len);
13721                 DP_TBFLAG_A32(flags, VECSTRIDE, env->vfp.vec_stride);
13722             }
13723             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
13724                 DP_TBFLAG_A32(flags, VFPEN, 1);
13725             }
13726         }
13727 
13728         DP_TBFLAG_AM32(flags, THUMB, env->thumb);
13729         DP_TBFLAG_AM32(flags, CONDEXEC, env->condexec_bits);
13730     }
13731 
13732     /*
13733      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13734      * states defined in the ARM ARM for software singlestep:
13735      *  SS_ACTIVE   PSTATE.SS   State
13736      *     0            x       Inactive (the TB flag for SS is always 0)
13737      *     1            0       Active-pending
13738      *     1            1       Active-not-pending
13739      * SS_ACTIVE is set in hflags; PSTATE__SS is computed every TB.
13740      */
13741     if (EX_TBFLAG_ANY(flags, SS_ACTIVE) && (env->pstate & PSTATE_SS)) {
13742         DP_TBFLAG_ANY(flags, PSTATE__SS, 1);
13743     }
13744 
13745     *pflags = flags.flags;
13746     *cs_base = flags.flags2;
13747 }
13748 
13749 #ifdef TARGET_AARCH64
13750 /*
13751  * The manual says that when SVE is enabled and VQ is widened the
13752  * implementation is allowed to zero the previously inaccessible
13753  * portion of the registers.  The corollary to that is that when
13754  * SVE is enabled and VQ is narrowed we are also allowed to zero
13755  * the now inaccessible portion of the registers.
13756  *
13757  * The intent of this is that no predicate bit beyond VQ is ever set.
13758  * Which means that some operations on predicate registers themselves
13759  * may operate on full uint64_t or even unrolled across the maximum
13760  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13761  * may well be cheaper than conditionals to restrict the operation
13762  * to the relevant portion of a uint16_t[16].
13763  */
13764 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13765 {
13766     int i, j;
13767     uint64_t pmask;
13768 
13769     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13770     assert(vq <= env_archcpu(env)->sve_max_vq);
13771 
13772     /* Zap the high bits of the zregs.  */
13773     for (i = 0; i < 32; i++) {
13774         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13775     }
13776 
13777     /* Zap the high bits of the pregs and ffr.  */
13778     pmask = 0;
13779     if (vq & 3) {
13780         pmask = ~(-1ULL << (16 * (vq & 3)));
13781     }
13782     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13783         for (i = 0; i < 17; ++i) {
13784             env->vfp.pregs[i].p[j] &= pmask;
13785         }
13786         pmask = 0;
13787     }
13788 }
13789 
13790 /*
13791  * Notice a change in SVE vector size when changing EL.
13792  */
13793 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13794                            int new_el, bool el0_a64)
13795 {
13796     ARMCPU *cpu = env_archcpu(env);
13797     int old_len, new_len;
13798     bool old_a64, new_a64;
13799 
13800     /* Nothing to do if no SVE.  */
13801     if (!cpu_isar_feature(aa64_sve, cpu)) {
13802         return;
13803     }
13804 
13805     /* Nothing to do if FP is disabled in either EL.  */
13806     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13807         return;
13808     }
13809 
13810     /*
13811      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13812      * at ELx, or not available because the EL is in AArch32 state, then
13813      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13814      * has an effective value of 0".
13815      *
13816      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13817      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13818      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13819      * we already have the correct register contents when encountering the
13820      * vq0->vq0 transition between EL0->EL1.
13821      */
13822     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13823     old_len = (old_a64 && !sve_exception_el(env, old_el)
13824                ? sve_zcr_len_for_el(env, old_el) : 0);
13825     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13826     new_len = (new_a64 && !sve_exception_el(env, new_el)
13827                ? sve_zcr_len_for_el(env, new_el) : 0);
13828 
13829     /* When changing vector length, clear inaccessible state.  */
13830     if (new_len < old_len) {
13831         aarch64_sve_narrow_vq(env, new_len + 1);
13832     }
13833 }
13834 #endif
13835