xref: /qemu/target/arm/helper.c (revision 09147930)
1 /*
2  * ARM generic helpers.
3  *
4  * This code is licensed under the GNU GPL v2 or later.
5  *
6  * SPDX-License-Identifier: GPL-2.0-or-later
7  */
8 
9 #include "qemu/osdep.h"
10 #include "qemu/units.h"
11 #include "target/arm/idau.h"
12 #include "trace.h"
13 #include "cpu.h"
14 #include "internals.h"
15 #include "exec/gdbstub.h"
16 #include "exec/helper-proto.h"
17 #include "qemu/host-utils.h"
18 #include "qemu/main-loop.h"
19 #include "qemu/bitops.h"
20 #include "qemu/crc32c.h"
21 #include "qemu/qemu-print.h"
22 #include "exec/exec-all.h"
23 #include <zlib.h> /* For crc32 */
24 #include "hw/irq.h"
25 #include "hw/semihosting/semihost.h"
26 #include "sysemu/cpus.h"
27 #include "sysemu/kvm.h"
28 #include "sysemu/tcg.h"
29 #include "qemu/range.h"
30 #include "qapi/qapi-commands-machine-target.h"
31 #include "qapi/error.h"
32 #include "qemu/guest-random.h"
33 #ifdef CONFIG_TCG
34 #include "arm_ldst.h"
35 #include "exec/cpu_ldst.h"
36 #endif
37 
38 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
39 
40 #ifndef CONFIG_USER_ONLY
41 
42 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
43                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
44                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
45                                target_ulong *page_size_ptr,
46                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs);
47 #endif
48 
49 static void switch_mode(CPUARMState *env, int mode);
50 
51 static int vfp_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
52 {
53     ARMCPU *cpu = env_archcpu(env);
54     int nregs = cpu_isar_feature(aa32_simd_r32, cpu) ? 32 : 16;
55 
56     /* VFP data registers are always little-endian.  */
57     if (reg < nregs) {
58         stq_le_p(buf, *aa32_vfp_dreg(env, reg));
59         return 8;
60     }
61     if (arm_feature(env, ARM_FEATURE_NEON)) {
62         /* Aliases for Q regs.  */
63         nregs += 16;
64         if (reg < nregs) {
65             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
66             stq_le_p(buf, q[0]);
67             stq_le_p(buf + 8, q[1]);
68             return 16;
69         }
70     }
71     switch (reg - nregs) {
72     case 0: stl_p(buf, env->vfp.xregs[ARM_VFP_FPSID]); return 4;
73     case 1: stl_p(buf, vfp_get_fpscr(env)); return 4;
74     case 2: stl_p(buf, env->vfp.xregs[ARM_VFP_FPEXC]); return 4;
75     }
76     return 0;
77 }
78 
79 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
80 {
81     ARMCPU *cpu = env_archcpu(env);
82     int nregs = cpu_isar_feature(aa32_simd_r32, cpu) ? 32 : 16;
83 
84     if (reg < nregs) {
85         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
86         return 8;
87     }
88     if (arm_feature(env, ARM_FEATURE_NEON)) {
89         nregs += 16;
90         if (reg < nregs) {
91             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
92             q[0] = ldq_le_p(buf);
93             q[1] = ldq_le_p(buf + 8);
94             return 16;
95         }
96     }
97     switch (reg - nregs) {
98     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
99     case 1: vfp_set_fpscr(env, ldl_p(buf)); return 4;
100     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
101     }
102     return 0;
103 }
104 
105 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, uint8_t *buf, int reg)
106 {
107     switch (reg) {
108     case 0 ... 31:
109         /* 128 bit FP register */
110         {
111             uint64_t *q = aa64_vfp_qreg(env, reg);
112             stq_le_p(buf, q[0]);
113             stq_le_p(buf + 8, q[1]);
114             return 16;
115         }
116     case 32:
117         /* FPSR */
118         stl_p(buf, vfp_get_fpsr(env));
119         return 4;
120     case 33:
121         /* FPCR */
122         stl_p(buf, vfp_get_fpcr(env));
123         return 4;
124     default:
125         return 0;
126     }
127 }
128 
129 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
130 {
131     switch (reg) {
132     case 0 ... 31:
133         /* 128 bit FP register */
134         {
135             uint64_t *q = aa64_vfp_qreg(env, reg);
136             q[0] = ldq_le_p(buf);
137             q[1] = ldq_le_p(buf + 8);
138             return 16;
139         }
140     case 32:
141         /* FPSR */
142         vfp_set_fpsr(env, ldl_p(buf));
143         return 4;
144     case 33:
145         /* FPCR */
146         vfp_set_fpcr(env, ldl_p(buf));
147         return 4;
148     default:
149         return 0;
150     }
151 }
152 
153 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
154 {
155     assert(ri->fieldoffset);
156     if (cpreg_field_is_64bit(ri)) {
157         return CPREG_FIELD64(env, ri);
158     } else {
159         return CPREG_FIELD32(env, ri);
160     }
161 }
162 
163 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
164                       uint64_t value)
165 {
166     assert(ri->fieldoffset);
167     if (cpreg_field_is_64bit(ri)) {
168         CPREG_FIELD64(env, ri) = value;
169     } else {
170         CPREG_FIELD32(env, ri) = value;
171     }
172 }
173 
174 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
175 {
176     return (char *)env + ri->fieldoffset;
177 }
178 
179 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
180 {
181     /* Raw read of a coprocessor register (as needed for migration, etc). */
182     if (ri->type & ARM_CP_CONST) {
183         return ri->resetvalue;
184     } else if (ri->raw_readfn) {
185         return ri->raw_readfn(env, ri);
186     } else if (ri->readfn) {
187         return ri->readfn(env, ri);
188     } else {
189         return raw_read(env, ri);
190     }
191 }
192 
193 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
194                              uint64_t v)
195 {
196     /* Raw write of a coprocessor register (as needed for migration, etc).
197      * Note that constant registers are treated as write-ignored; the
198      * caller should check for success by whether a readback gives the
199      * value written.
200      */
201     if (ri->type & ARM_CP_CONST) {
202         return;
203     } else if (ri->raw_writefn) {
204         ri->raw_writefn(env, ri, v);
205     } else if (ri->writefn) {
206         ri->writefn(env, ri, v);
207     } else {
208         raw_write(env, ri, v);
209     }
210 }
211 
212 static int arm_gdb_get_sysreg(CPUARMState *env, uint8_t *buf, int reg)
213 {
214     ARMCPU *cpu = env_archcpu(env);
215     const ARMCPRegInfo *ri;
216     uint32_t key;
217 
218     key = cpu->dyn_xml.cpregs_keys[reg];
219     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
220     if (ri) {
221         if (cpreg_field_is_64bit(ri)) {
222             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
223         } else {
224             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
225         }
226     }
227     return 0;
228 }
229 
230 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
231 {
232     return 0;
233 }
234 
235 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
236 {
237    /* Return true if the regdef would cause an assertion if you called
238     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
239     * program bug for it not to have the NO_RAW flag).
240     * NB that returning false here doesn't necessarily mean that calling
241     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
242     * read/write access functions which are safe for raw use" from "has
243     * read/write access functions which have side effects but has forgotten
244     * to provide raw access functions".
245     * The tests here line up with the conditions in read/write_raw_cp_reg()
246     * and assertions in raw_read()/raw_write().
247     */
248     if ((ri->type & ARM_CP_CONST) ||
249         ri->fieldoffset ||
250         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
251         return false;
252     }
253     return true;
254 }
255 
256 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
257 {
258     /* Write the coprocessor state from cpu->env to the (index,value) list. */
259     int i;
260     bool ok = true;
261 
262     for (i = 0; i < cpu->cpreg_array_len; i++) {
263         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
264         const ARMCPRegInfo *ri;
265         uint64_t newval;
266 
267         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
268         if (!ri) {
269             ok = false;
270             continue;
271         }
272         if (ri->type & ARM_CP_NO_RAW) {
273             continue;
274         }
275 
276         newval = read_raw_cp_reg(&cpu->env, ri);
277         if (kvm_sync) {
278             /*
279              * Only sync if the previous list->cpustate sync succeeded.
280              * Rather than tracking the success/failure state for every
281              * item in the list, we just recheck "does the raw write we must
282              * have made in write_list_to_cpustate() read back OK" here.
283              */
284             uint64_t oldval = cpu->cpreg_values[i];
285 
286             if (oldval == newval) {
287                 continue;
288             }
289 
290             write_raw_cp_reg(&cpu->env, ri, oldval);
291             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
292                 continue;
293             }
294 
295             write_raw_cp_reg(&cpu->env, ri, newval);
296         }
297         cpu->cpreg_values[i] = newval;
298     }
299     return ok;
300 }
301 
302 bool write_list_to_cpustate(ARMCPU *cpu)
303 {
304     int i;
305     bool ok = true;
306 
307     for (i = 0; i < cpu->cpreg_array_len; i++) {
308         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
309         uint64_t v = cpu->cpreg_values[i];
310         const ARMCPRegInfo *ri;
311 
312         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
313         if (!ri) {
314             ok = false;
315             continue;
316         }
317         if (ri->type & ARM_CP_NO_RAW) {
318             continue;
319         }
320         /* Write value and confirm it reads back as written
321          * (to catch read-only registers and partially read-only
322          * registers where the incoming migration value doesn't match)
323          */
324         write_raw_cp_reg(&cpu->env, ri, v);
325         if (read_raw_cp_reg(&cpu->env, ri) != v) {
326             ok = false;
327         }
328     }
329     return ok;
330 }
331 
332 static void add_cpreg_to_list(gpointer key, gpointer opaque)
333 {
334     ARMCPU *cpu = opaque;
335     uint64_t regidx;
336     const ARMCPRegInfo *ri;
337 
338     regidx = *(uint32_t *)key;
339     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
340 
341     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
342         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
343         /* The value array need not be initialized at this point */
344         cpu->cpreg_array_len++;
345     }
346 }
347 
348 static void count_cpreg(gpointer key, gpointer opaque)
349 {
350     ARMCPU *cpu = opaque;
351     uint64_t regidx;
352     const ARMCPRegInfo *ri;
353 
354     regidx = *(uint32_t *)key;
355     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
356 
357     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
358         cpu->cpreg_array_len++;
359     }
360 }
361 
362 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
363 {
364     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
365     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
366 
367     if (aidx > bidx) {
368         return 1;
369     }
370     if (aidx < bidx) {
371         return -1;
372     }
373     return 0;
374 }
375 
376 void init_cpreg_list(ARMCPU *cpu)
377 {
378     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
379      * Note that we require cpreg_tuples[] to be sorted by key ID.
380      */
381     GList *keys;
382     int arraylen;
383 
384     keys = g_hash_table_get_keys(cpu->cp_regs);
385     keys = g_list_sort(keys, cpreg_key_compare);
386 
387     cpu->cpreg_array_len = 0;
388 
389     g_list_foreach(keys, count_cpreg, cpu);
390 
391     arraylen = cpu->cpreg_array_len;
392     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
393     cpu->cpreg_values = g_new(uint64_t, arraylen);
394     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
395     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
396     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
397     cpu->cpreg_array_len = 0;
398 
399     g_list_foreach(keys, add_cpreg_to_list, cpu);
400 
401     assert(cpu->cpreg_array_len == arraylen);
402 
403     g_list_free(keys);
404 }
405 
406 /*
407  * Some registers are not accessible if EL3.NS=0 and EL3 is using AArch32 but
408  * they are accessible when EL3 is using AArch64 regardless of EL3.NS.
409  *
410  * access_el3_aa32ns: Used to check AArch32 register views.
411  * access_el3_aa32ns_aa64any: Used to check both AArch32/64 register views.
412  */
413 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
414                                         const ARMCPRegInfo *ri,
415                                         bool isread)
416 {
417     bool secure = arm_is_secure_below_el3(env);
418 
419     assert(!arm_el_is_aa64(env, 3));
420     if (secure) {
421         return CP_ACCESS_TRAP_UNCATEGORIZED;
422     }
423     return CP_ACCESS_OK;
424 }
425 
426 static CPAccessResult access_el3_aa32ns_aa64any(CPUARMState *env,
427                                                 const ARMCPRegInfo *ri,
428                                                 bool isread)
429 {
430     if (!arm_el_is_aa64(env, 3)) {
431         return access_el3_aa32ns(env, ri, isread);
432     }
433     return CP_ACCESS_OK;
434 }
435 
436 /* Some secure-only AArch32 registers trap to EL3 if used from
437  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
438  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
439  * We assume that the .access field is set to PL1_RW.
440  */
441 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
442                                             const ARMCPRegInfo *ri,
443                                             bool isread)
444 {
445     if (arm_current_el(env) == 3) {
446         return CP_ACCESS_OK;
447     }
448     if (arm_is_secure_below_el3(env)) {
449         return CP_ACCESS_TRAP_EL3;
450     }
451     /* This will be EL1 NS and EL2 NS, which just UNDEF */
452     return CP_ACCESS_TRAP_UNCATEGORIZED;
453 }
454 
455 /* Check for traps to "powerdown debug" registers, which are controlled
456  * by MDCR.TDOSA
457  */
458 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
459                                    bool isread)
460 {
461     int el = arm_current_el(env);
462     bool mdcr_el2_tdosa = (env->cp15.mdcr_el2 & MDCR_TDOSA) ||
463         (env->cp15.mdcr_el2 & MDCR_TDE) ||
464         (arm_hcr_el2_eff(env) & HCR_TGE);
465 
466     if (el < 2 && mdcr_el2_tdosa && !arm_is_secure_below_el3(env)) {
467         return CP_ACCESS_TRAP_EL2;
468     }
469     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
470         return CP_ACCESS_TRAP_EL3;
471     }
472     return CP_ACCESS_OK;
473 }
474 
475 /* Check for traps to "debug ROM" registers, which are controlled
476  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
477  */
478 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
479                                   bool isread)
480 {
481     int el = arm_current_el(env);
482     bool mdcr_el2_tdra = (env->cp15.mdcr_el2 & MDCR_TDRA) ||
483         (env->cp15.mdcr_el2 & MDCR_TDE) ||
484         (arm_hcr_el2_eff(env) & HCR_TGE);
485 
486     if (el < 2 && mdcr_el2_tdra && !arm_is_secure_below_el3(env)) {
487         return CP_ACCESS_TRAP_EL2;
488     }
489     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
490         return CP_ACCESS_TRAP_EL3;
491     }
492     return CP_ACCESS_OK;
493 }
494 
495 /* Check for traps to general debug registers, which are controlled
496  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
497  */
498 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
499                                   bool isread)
500 {
501     int el = arm_current_el(env);
502     bool mdcr_el2_tda = (env->cp15.mdcr_el2 & MDCR_TDA) ||
503         (env->cp15.mdcr_el2 & MDCR_TDE) ||
504         (arm_hcr_el2_eff(env) & HCR_TGE);
505 
506     if (el < 2 && mdcr_el2_tda && !arm_is_secure_below_el3(env)) {
507         return CP_ACCESS_TRAP_EL2;
508     }
509     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
510         return CP_ACCESS_TRAP_EL3;
511     }
512     return CP_ACCESS_OK;
513 }
514 
515 /* Check for traps to performance monitor registers, which are controlled
516  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
517  */
518 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
519                                  bool isread)
520 {
521     int el = arm_current_el(env);
522 
523     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
524         && !arm_is_secure_below_el3(env)) {
525         return CP_ACCESS_TRAP_EL2;
526     }
527     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
528         return CP_ACCESS_TRAP_EL3;
529     }
530     return CP_ACCESS_OK;
531 }
532 
533 /* Check for traps from EL1 due to HCR_EL2.TVM and HCR_EL2.TRVM.  */
534 static CPAccessResult access_tvm_trvm(CPUARMState *env, const ARMCPRegInfo *ri,
535                                       bool isread)
536 {
537     if (arm_current_el(env) == 1) {
538         uint64_t trap = isread ? HCR_TRVM : HCR_TVM;
539         if (arm_hcr_el2_eff(env) & trap) {
540             return CP_ACCESS_TRAP_EL2;
541         }
542     }
543     return CP_ACCESS_OK;
544 }
545 
546 /* Check for traps from EL1 due to HCR_EL2.TSW.  */
547 static CPAccessResult access_tsw(CPUARMState *env, const ARMCPRegInfo *ri,
548                                  bool isread)
549 {
550     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TSW)) {
551         return CP_ACCESS_TRAP_EL2;
552     }
553     return CP_ACCESS_OK;
554 }
555 
556 /* Check for traps from EL1 due to HCR_EL2.TACR.  */
557 static CPAccessResult access_tacr(CPUARMState *env, const ARMCPRegInfo *ri,
558                                   bool isread)
559 {
560     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TACR)) {
561         return CP_ACCESS_TRAP_EL2;
562     }
563     return CP_ACCESS_OK;
564 }
565 
566 /* Check for traps from EL1 due to HCR_EL2.TTLB. */
567 static CPAccessResult access_ttlb(CPUARMState *env, const ARMCPRegInfo *ri,
568                                   bool isread)
569 {
570     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TTLB)) {
571         return CP_ACCESS_TRAP_EL2;
572     }
573     return CP_ACCESS_OK;
574 }
575 
576 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
577 {
578     ARMCPU *cpu = env_archcpu(env);
579 
580     raw_write(env, ri, value);
581     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
582 }
583 
584 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
585 {
586     ARMCPU *cpu = env_archcpu(env);
587 
588     if (raw_read(env, ri) != value) {
589         /* Unlike real hardware the qemu TLB uses virtual addresses,
590          * not modified virtual addresses, so this causes a TLB flush.
591          */
592         tlb_flush(CPU(cpu));
593         raw_write(env, ri, value);
594     }
595 }
596 
597 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
598                              uint64_t value)
599 {
600     ARMCPU *cpu = env_archcpu(env);
601 
602     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
603         && !extended_addresses_enabled(env)) {
604         /* For VMSA (when not using the LPAE long descriptor page table
605          * format) this register includes the ASID, so do a TLB flush.
606          * For PMSA it is purely a process ID and no action is needed.
607          */
608         tlb_flush(CPU(cpu));
609     }
610     raw_write(env, ri, value);
611 }
612 
613 /* IS variants of TLB operations must affect all cores */
614 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
615                              uint64_t value)
616 {
617     CPUState *cs = env_cpu(env);
618 
619     tlb_flush_all_cpus_synced(cs);
620 }
621 
622 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
623                              uint64_t value)
624 {
625     CPUState *cs = env_cpu(env);
626 
627     tlb_flush_all_cpus_synced(cs);
628 }
629 
630 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
631                              uint64_t value)
632 {
633     CPUState *cs = env_cpu(env);
634 
635     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
636 }
637 
638 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
639                              uint64_t value)
640 {
641     CPUState *cs = env_cpu(env);
642 
643     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
644 }
645 
646 /*
647  * Non-IS variants of TLB operations are upgraded to
648  * IS versions if we are at NS EL1 and HCR_EL2.FB is set to
649  * force broadcast of these operations.
650  */
651 static bool tlb_force_broadcast(CPUARMState *env)
652 {
653     return (env->cp15.hcr_el2 & HCR_FB) &&
654         arm_current_el(env) == 1 && arm_is_secure_below_el3(env);
655 }
656 
657 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
658                           uint64_t value)
659 {
660     /* Invalidate all (TLBIALL) */
661     CPUState *cs = env_cpu(env);
662 
663     if (tlb_force_broadcast(env)) {
664         tlb_flush_all_cpus_synced(cs);
665     } else {
666         tlb_flush(cs);
667     }
668 }
669 
670 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
671                           uint64_t value)
672 {
673     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
674     CPUState *cs = env_cpu(env);
675 
676     value &= TARGET_PAGE_MASK;
677     if (tlb_force_broadcast(env)) {
678         tlb_flush_page_all_cpus_synced(cs, value);
679     } else {
680         tlb_flush_page(cs, value);
681     }
682 }
683 
684 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
685                            uint64_t value)
686 {
687     /* Invalidate by ASID (TLBIASID) */
688     CPUState *cs = env_cpu(env);
689 
690     if (tlb_force_broadcast(env)) {
691         tlb_flush_all_cpus_synced(cs);
692     } else {
693         tlb_flush(cs);
694     }
695 }
696 
697 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
698                            uint64_t value)
699 {
700     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
701     CPUState *cs = env_cpu(env);
702 
703     value &= TARGET_PAGE_MASK;
704     if (tlb_force_broadcast(env)) {
705         tlb_flush_page_all_cpus_synced(cs, value);
706     } else {
707         tlb_flush_page(cs, value);
708     }
709 }
710 
711 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
712                                uint64_t value)
713 {
714     CPUState *cs = env_cpu(env);
715 
716     tlb_flush_by_mmuidx(cs,
717                         ARMMMUIdxBit_E10_1 |
718                         ARMMMUIdxBit_E10_1_PAN |
719                         ARMMMUIdxBit_E10_0 |
720                         ARMMMUIdxBit_Stage2);
721 }
722 
723 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
724                                   uint64_t value)
725 {
726     CPUState *cs = env_cpu(env);
727 
728     tlb_flush_by_mmuidx_all_cpus_synced(cs,
729                                         ARMMMUIdxBit_E10_1 |
730                                         ARMMMUIdxBit_E10_1_PAN |
731                                         ARMMMUIdxBit_E10_0 |
732                                         ARMMMUIdxBit_Stage2);
733 }
734 
735 static void tlbiipas2_write(CPUARMState *env, const ARMCPRegInfo *ri,
736                             uint64_t value)
737 {
738     /* Invalidate by IPA. This has to invalidate any structures that
739      * contain only stage 2 translation information, but does not need
740      * to apply to structures that contain combined stage 1 and stage 2
741      * translation information.
742      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
743      */
744     CPUState *cs = env_cpu(env);
745     uint64_t pageaddr;
746 
747     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
748         return;
749     }
750 
751     pageaddr = sextract64(value << 12, 0, 40);
752 
753     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_Stage2);
754 }
755 
756 static void tlbiipas2_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
757                                uint64_t value)
758 {
759     CPUState *cs = env_cpu(env);
760     uint64_t pageaddr;
761 
762     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
763         return;
764     }
765 
766     pageaddr = sextract64(value << 12, 0, 40);
767 
768     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
769                                              ARMMMUIdxBit_Stage2);
770 }
771 
772 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
773                               uint64_t value)
774 {
775     CPUState *cs = env_cpu(env);
776 
777     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_E2);
778 }
779 
780 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
781                                  uint64_t value)
782 {
783     CPUState *cs = env_cpu(env);
784 
785     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_E2);
786 }
787 
788 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
789                               uint64_t value)
790 {
791     CPUState *cs = env_cpu(env);
792     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
793 
794     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_E2);
795 }
796 
797 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
798                                  uint64_t value)
799 {
800     CPUState *cs = env_cpu(env);
801     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
802 
803     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
804                                              ARMMMUIdxBit_E2);
805 }
806 
807 static const ARMCPRegInfo cp_reginfo[] = {
808     /* Define the secure and non-secure FCSE identifier CP registers
809      * separately because there is no secure bank in V8 (no _EL3).  This allows
810      * the secure register to be properly reset and migrated. There is also no
811      * v8 EL1 version of the register so the non-secure instance stands alone.
812      */
813     { .name = "FCSEIDR",
814       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
815       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
816       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
817       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
818     { .name = "FCSEIDR_S",
819       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
820       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
821       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
822       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
823     /* Define the secure and non-secure context identifier CP registers
824      * separately because there is no secure bank in V8 (no _EL3).  This allows
825      * the secure register to be properly reset and migrated.  In the
826      * non-secure case, the 32-bit register will have reset and migration
827      * disabled during registration as it is handled by the 64-bit instance.
828      */
829     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
830       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
831       .access = PL1_RW, .accessfn = access_tvm_trvm,
832       .secure = ARM_CP_SECSTATE_NS,
833       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
834       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
835     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
836       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
837       .access = PL1_RW, .accessfn = access_tvm_trvm,
838       .secure = ARM_CP_SECSTATE_S,
839       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
840       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
841     REGINFO_SENTINEL
842 };
843 
844 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
845     /* NB: Some of these registers exist in v8 but with more precise
846      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
847      */
848     /* MMU Domain access control / MPU write buffer control */
849     { .name = "DACR",
850       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
851       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
852       .writefn = dacr_write, .raw_writefn = raw_write,
853       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
854                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
855     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
856      * For v6 and v5, these mappings are overly broad.
857      */
858     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
859       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
860     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
861       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
862     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
863       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
864     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
865       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
866     /* Cache maintenance ops; some of this space may be overridden later. */
867     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
868       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
869       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
870     REGINFO_SENTINEL
871 };
872 
873 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
874     /* Not all pre-v6 cores implemented this WFI, so this is slightly
875      * over-broad.
876      */
877     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
878       .access = PL1_W, .type = ARM_CP_WFI },
879     REGINFO_SENTINEL
880 };
881 
882 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
883     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
884      * is UNPREDICTABLE; we choose to NOP as most implementations do).
885      */
886     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
887       .access = PL1_W, .type = ARM_CP_WFI },
888     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
889      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
890      * OMAPCP will override this space.
891      */
892     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
893       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
894       .resetvalue = 0 },
895     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
896       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
897       .resetvalue = 0 },
898     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
899     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
900       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
901       .resetvalue = 0 },
902     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
903      * implementing it as RAZ means the "debug architecture version" bits
904      * will read as a reserved value, which should cause Linux to not try
905      * to use the debug hardware.
906      */
907     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
908       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
909     /* MMU TLB control. Note that the wildcarding means we cover not just
910      * the unified TLB ops but also the dside/iside/inner-shareable variants.
911      */
912     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
913       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
914       .type = ARM_CP_NO_RAW },
915     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
916       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
917       .type = ARM_CP_NO_RAW },
918     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
919       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
920       .type = ARM_CP_NO_RAW },
921     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
922       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
923       .type = ARM_CP_NO_RAW },
924     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
925       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
926     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
927       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
928     REGINFO_SENTINEL
929 };
930 
931 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
932                         uint64_t value)
933 {
934     uint32_t mask = 0;
935 
936     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
937     if (!arm_feature(env, ARM_FEATURE_V8)) {
938         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
939          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
940          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
941          */
942         if (cpu_isar_feature(aa32_vfp_simd, env_archcpu(env))) {
943             /* VFP coprocessor: cp10 & cp11 [23:20] */
944             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
945 
946             if (!arm_feature(env, ARM_FEATURE_NEON)) {
947                 /* ASEDIS [31] bit is RAO/WI */
948                 value |= (1 << 31);
949             }
950 
951             /* VFPv3 and upwards with NEON implement 32 double precision
952              * registers (D0-D31).
953              */
954             if (!cpu_isar_feature(aa32_simd_r32, env_archcpu(env))) {
955                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
956                 value |= (1 << 30);
957             }
958         }
959         value &= mask;
960     }
961 
962     /*
963      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
964      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
965      */
966     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
967         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
968         value &= ~(0xf << 20);
969         value |= env->cp15.cpacr_el1 & (0xf << 20);
970     }
971 
972     env->cp15.cpacr_el1 = value;
973 }
974 
975 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
976 {
977     /*
978      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
979      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
980      */
981     uint64_t value = env->cp15.cpacr_el1;
982 
983     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
984         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
985         value &= ~(0xf << 20);
986     }
987     return value;
988 }
989 
990 
991 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
992 {
993     /* Call cpacr_write() so that we reset with the correct RAO bits set
994      * for our CPU features.
995      */
996     cpacr_write(env, ri, 0);
997 }
998 
999 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1000                                    bool isread)
1001 {
1002     if (arm_feature(env, ARM_FEATURE_V8)) {
1003         /* Check if CPACR accesses are to be trapped to EL2 */
1004         if (arm_current_el(env) == 1 &&
1005             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
1006             return CP_ACCESS_TRAP_EL2;
1007         /* Check if CPACR accesses are to be trapped to EL3 */
1008         } else if (arm_current_el(env) < 3 &&
1009                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
1010             return CP_ACCESS_TRAP_EL3;
1011         }
1012     }
1013 
1014     return CP_ACCESS_OK;
1015 }
1016 
1017 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1018                                   bool isread)
1019 {
1020     /* Check if CPTR accesses are set to trap to EL3 */
1021     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
1022         return CP_ACCESS_TRAP_EL3;
1023     }
1024 
1025     return CP_ACCESS_OK;
1026 }
1027 
1028 static const ARMCPRegInfo v6_cp_reginfo[] = {
1029     /* prefetch by MVA in v6, NOP in v7 */
1030     { .name = "MVA_prefetch",
1031       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
1032       .access = PL1_W, .type = ARM_CP_NOP },
1033     /* We need to break the TB after ISB to execute self-modifying code
1034      * correctly and also to take any pending interrupts immediately.
1035      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
1036      */
1037     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
1038       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
1039     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
1040       .access = PL0_W, .type = ARM_CP_NOP },
1041     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
1042       .access = PL0_W, .type = ARM_CP_NOP },
1043     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
1044       .access = PL1_RW, .accessfn = access_tvm_trvm,
1045       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
1046                              offsetof(CPUARMState, cp15.ifar_ns) },
1047       .resetvalue = 0, },
1048     /* Watchpoint Fault Address Register : should actually only be present
1049      * for 1136, 1176, 11MPCore.
1050      */
1051     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
1052       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
1053     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
1054       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
1055       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
1056       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
1057     REGINFO_SENTINEL
1058 };
1059 
1060 /* Definitions for the PMU registers */
1061 #define PMCRN_MASK  0xf800
1062 #define PMCRN_SHIFT 11
1063 #define PMCRLC  0x40
1064 #define PMCRDP  0x20
1065 #define PMCRX   0x10
1066 #define PMCRD   0x8
1067 #define PMCRC   0x4
1068 #define PMCRP   0x2
1069 #define PMCRE   0x1
1070 /*
1071  * Mask of PMCR bits writeable by guest (not including WO bits like C, P,
1072  * which can be written as 1 to trigger behaviour but which stay RAZ).
1073  */
1074 #define PMCR_WRITEABLE_MASK (PMCRLC | PMCRDP | PMCRX | PMCRD | PMCRE)
1075 
1076 #define PMXEVTYPER_P          0x80000000
1077 #define PMXEVTYPER_U          0x40000000
1078 #define PMXEVTYPER_NSK        0x20000000
1079 #define PMXEVTYPER_NSU        0x10000000
1080 #define PMXEVTYPER_NSH        0x08000000
1081 #define PMXEVTYPER_M          0x04000000
1082 #define PMXEVTYPER_MT         0x02000000
1083 #define PMXEVTYPER_EVTCOUNT   0x0000ffff
1084 #define PMXEVTYPER_MASK       (PMXEVTYPER_P | PMXEVTYPER_U | PMXEVTYPER_NSK | \
1085                                PMXEVTYPER_NSU | PMXEVTYPER_NSH | \
1086                                PMXEVTYPER_M | PMXEVTYPER_MT | \
1087                                PMXEVTYPER_EVTCOUNT)
1088 
1089 #define PMCCFILTR             0xf8000000
1090 #define PMCCFILTR_M           PMXEVTYPER_M
1091 #define PMCCFILTR_EL0         (PMCCFILTR | PMCCFILTR_M)
1092 
1093 static inline uint32_t pmu_num_counters(CPUARMState *env)
1094 {
1095   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
1096 }
1097 
1098 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1099 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1100 {
1101   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1102 }
1103 
1104 typedef struct pm_event {
1105     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1106     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1107     bool (*supported)(CPUARMState *);
1108     /*
1109      * Retrieve the current count of the underlying event. The programmed
1110      * counters hold a difference from the return value from this function
1111      */
1112     uint64_t (*get_count)(CPUARMState *);
1113     /*
1114      * Return how many nanoseconds it will take (at a minimum) for count events
1115      * to occur. A negative value indicates the counter will never overflow, or
1116      * that the counter has otherwise arranged for the overflow bit to be set
1117      * and the PMU interrupt to be raised on overflow.
1118      */
1119     int64_t (*ns_per_count)(uint64_t);
1120 } pm_event;
1121 
1122 static bool event_always_supported(CPUARMState *env)
1123 {
1124     return true;
1125 }
1126 
1127 static uint64_t swinc_get_count(CPUARMState *env)
1128 {
1129     /*
1130      * SW_INCR events are written directly to the pmevcntr's by writes to
1131      * PMSWINC, so there is no underlying count maintained by the PMU itself
1132      */
1133     return 0;
1134 }
1135 
1136 static int64_t swinc_ns_per(uint64_t ignored)
1137 {
1138     return -1;
1139 }
1140 
1141 /*
1142  * Return the underlying cycle count for the PMU cycle counters. If we're in
1143  * usermode, simply return 0.
1144  */
1145 static uint64_t cycles_get_count(CPUARMState *env)
1146 {
1147 #ifndef CONFIG_USER_ONLY
1148     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1149                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1150 #else
1151     return cpu_get_host_ticks();
1152 #endif
1153 }
1154 
1155 #ifndef CONFIG_USER_ONLY
1156 static int64_t cycles_ns_per(uint64_t cycles)
1157 {
1158     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1159 }
1160 
1161 static bool instructions_supported(CPUARMState *env)
1162 {
1163     return use_icount == 1 /* Precise instruction counting */;
1164 }
1165 
1166 static uint64_t instructions_get_count(CPUARMState *env)
1167 {
1168     return (uint64_t)cpu_get_icount_raw();
1169 }
1170 
1171 static int64_t instructions_ns_per(uint64_t icount)
1172 {
1173     return cpu_icount_to_ns((int64_t)icount);
1174 }
1175 #endif
1176 
1177 static bool pmu_8_1_events_supported(CPUARMState *env)
1178 {
1179     /* For events which are supported in any v8.1 PMU */
1180     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
1181 }
1182 
1183 static bool pmu_8_4_events_supported(CPUARMState *env)
1184 {
1185     /* For events which are supported in any v8.1 PMU */
1186     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
1187 }
1188 
1189 static uint64_t zero_event_get_count(CPUARMState *env)
1190 {
1191     /* For events which on QEMU never fire, so their count is always zero */
1192     return 0;
1193 }
1194 
1195 static int64_t zero_event_ns_per(uint64_t cycles)
1196 {
1197     /* An event which never fires can never overflow */
1198     return -1;
1199 }
1200 
1201 static const pm_event pm_events[] = {
1202     { .number = 0x000, /* SW_INCR */
1203       .supported = event_always_supported,
1204       .get_count = swinc_get_count,
1205       .ns_per_count = swinc_ns_per,
1206     },
1207 #ifndef CONFIG_USER_ONLY
1208     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1209       .supported = instructions_supported,
1210       .get_count = instructions_get_count,
1211       .ns_per_count = instructions_ns_per,
1212     },
1213     { .number = 0x011, /* CPU_CYCLES, Cycle */
1214       .supported = event_always_supported,
1215       .get_count = cycles_get_count,
1216       .ns_per_count = cycles_ns_per,
1217     },
1218 #endif
1219     { .number = 0x023, /* STALL_FRONTEND */
1220       .supported = pmu_8_1_events_supported,
1221       .get_count = zero_event_get_count,
1222       .ns_per_count = zero_event_ns_per,
1223     },
1224     { .number = 0x024, /* STALL_BACKEND */
1225       .supported = pmu_8_1_events_supported,
1226       .get_count = zero_event_get_count,
1227       .ns_per_count = zero_event_ns_per,
1228     },
1229     { .number = 0x03c, /* STALL */
1230       .supported = pmu_8_4_events_supported,
1231       .get_count = zero_event_get_count,
1232       .ns_per_count = zero_event_ns_per,
1233     },
1234 };
1235 
1236 /*
1237  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1238  * events (i.e. the statistical profiling extension), this implementation
1239  * should first be updated to something sparse instead of the current
1240  * supported_event_map[] array.
1241  */
1242 #define MAX_EVENT_ID 0x3c
1243 #define UNSUPPORTED_EVENT UINT16_MAX
1244 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1245 
1246 /*
1247  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1248  * of ARM event numbers to indices in our pm_events array.
1249  *
1250  * Note: Events in the 0x40XX range are not currently supported.
1251  */
1252 void pmu_init(ARMCPU *cpu)
1253 {
1254     unsigned int i;
1255 
1256     /*
1257      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1258      * events to them
1259      */
1260     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1261         supported_event_map[i] = UNSUPPORTED_EVENT;
1262     }
1263     cpu->pmceid0 = 0;
1264     cpu->pmceid1 = 0;
1265 
1266     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1267         const pm_event *cnt = &pm_events[i];
1268         assert(cnt->number <= MAX_EVENT_ID);
1269         /* We do not currently support events in the 0x40xx range */
1270         assert(cnt->number <= 0x3f);
1271 
1272         if (cnt->supported(&cpu->env)) {
1273             supported_event_map[cnt->number] = i;
1274             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1275             if (cnt->number & 0x20) {
1276                 cpu->pmceid1 |= event_mask;
1277             } else {
1278                 cpu->pmceid0 |= event_mask;
1279             }
1280         }
1281     }
1282 }
1283 
1284 /*
1285  * Check at runtime whether a PMU event is supported for the current machine
1286  */
1287 static bool event_supported(uint16_t number)
1288 {
1289     if (number > MAX_EVENT_ID) {
1290         return false;
1291     }
1292     return supported_event_map[number] != UNSUPPORTED_EVENT;
1293 }
1294 
1295 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1296                                    bool isread)
1297 {
1298     /* Performance monitor registers user accessibility is controlled
1299      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1300      * trapping to EL2 or EL3 for other accesses.
1301      */
1302     int el = arm_current_el(env);
1303 
1304     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1305         return CP_ACCESS_TRAP;
1306     }
1307     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
1308         && !arm_is_secure_below_el3(env)) {
1309         return CP_ACCESS_TRAP_EL2;
1310     }
1311     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1312         return CP_ACCESS_TRAP_EL3;
1313     }
1314 
1315     return CP_ACCESS_OK;
1316 }
1317 
1318 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1319                                            const ARMCPRegInfo *ri,
1320                                            bool isread)
1321 {
1322     /* ER: event counter read trap control */
1323     if (arm_feature(env, ARM_FEATURE_V8)
1324         && arm_current_el(env) == 0
1325         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1326         && isread) {
1327         return CP_ACCESS_OK;
1328     }
1329 
1330     return pmreg_access(env, ri, isread);
1331 }
1332 
1333 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1334                                          const ARMCPRegInfo *ri,
1335                                          bool isread)
1336 {
1337     /* SW: software increment write trap control */
1338     if (arm_feature(env, ARM_FEATURE_V8)
1339         && arm_current_el(env) == 0
1340         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1341         && !isread) {
1342         return CP_ACCESS_OK;
1343     }
1344 
1345     return pmreg_access(env, ri, isread);
1346 }
1347 
1348 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1349                                         const ARMCPRegInfo *ri,
1350                                         bool isread)
1351 {
1352     /* ER: event counter read trap control */
1353     if (arm_feature(env, ARM_FEATURE_V8)
1354         && arm_current_el(env) == 0
1355         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1356         return CP_ACCESS_OK;
1357     }
1358 
1359     return pmreg_access(env, ri, isread);
1360 }
1361 
1362 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1363                                          const ARMCPRegInfo *ri,
1364                                          bool isread)
1365 {
1366     /* CR: cycle counter read trap control */
1367     if (arm_feature(env, ARM_FEATURE_V8)
1368         && arm_current_el(env) == 0
1369         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1370         && isread) {
1371         return CP_ACCESS_OK;
1372     }
1373 
1374     return pmreg_access(env, ri, isread);
1375 }
1376 
1377 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1378  * the current EL, security state, and register configuration.
1379  */
1380 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1381 {
1382     uint64_t filter;
1383     bool e, p, u, nsk, nsu, nsh, m;
1384     bool enabled, prohibited, filtered;
1385     bool secure = arm_is_secure(env);
1386     int el = arm_current_el(env);
1387     uint8_t hpmn = env->cp15.mdcr_el2 & MDCR_HPMN;
1388 
1389     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1390         return false;
1391     }
1392 
1393     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1394             (counter < hpmn || counter == 31)) {
1395         e = env->cp15.c9_pmcr & PMCRE;
1396     } else {
1397         e = env->cp15.mdcr_el2 & MDCR_HPME;
1398     }
1399     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1400 
1401     if (!secure) {
1402         if (el == 2 && (counter < hpmn || counter == 31)) {
1403             prohibited = env->cp15.mdcr_el2 & MDCR_HPMD;
1404         } else {
1405             prohibited = false;
1406         }
1407     } else {
1408         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1409            (env->cp15.mdcr_el3 & MDCR_SPME);
1410     }
1411 
1412     if (prohibited && counter == 31) {
1413         prohibited = env->cp15.c9_pmcr & PMCRDP;
1414     }
1415 
1416     if (counter == 31) {
1417         filter = env->cp15.pmccfiltr_el0;
1418     } else {
1419         filter = env->cp15.c14_pmevtyper[counter];
1420     }
1421 
1422     p   = filter & PMXEVTYPER_P;
1423     u   = filter & PMXEVTYPER_U;
1424     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1425     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1426     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1427     m   = arm_el_is_aa64(env, 1) &&
1428               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1429 
1430     if (el == 0) {
1431         filtered = secure ? u : u != nsu;
1432     } else if (el == 1) {
1433         filtered = secure ? p : p != nsk;
1434     } else if (el == 2) {
1435         filtered = !nsh;
1436     } else { /* EL3 */
1437         filtered = m != p;
1438     }
1439 
1440     if (counter != 31) {
1441         /*
1442          * If not checking PMCCNTR, ensure the counter is setup to an event we
1443          * support
1444          */
1445         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1446         if (!event_supported(event)) {
1447             return false;
1448         }
1449     }
1450 
1451     return enabled && !prohibited && !filtered;
1452 }
1453 
1454 static void pmu_update_irq(CPUARMState *env)
1455 {
1456     ARMCPU *cpu = env_archcpu(env);
1457     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1458             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1459 }
1460 
1461 /*
1462  * Ensure c15_ccnt is the guest-visible count so that operations such as
1463  * enabling/disabling the counter or filtering, modifying the count itself,
1464  * etc. can be done logically. This is essentially a no-op if the counter is
1465  * not enabled at the time of the call.
1466  */
1467 static void pmccntr_op_start(CPUARMState *env)
1468 {
1469     uint64_t cycles = cycles_get_count(env);
1470 
1471     if (pmu_counter_enabled(env, 31)) {
1472         uint64_t eff_cycles = cycles;
1473         if (env->cp15.c9_pmcr & PMCRD) {
1474             /* Increment once every 64 processor clock cycles */
1475             eff_cycles /= 64;
1476         }
1477 
1478         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1479 
1480         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1481                                  1ull << 63 : 1ull << 31;
1482         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1483             env->cp15.c9_pmovsr |= (1 << 31);
1484             pmu_update_irq(env);
1485         }
1486 
1487         env->cp15.c15_ccnt = new_pmccntr;
1488     }
1489     env->cp15.c15_ccnt_delta = cycles;
1490 }
1491 
1492 /*
1493  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1494  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1495  * pmccntr_op_start.
1496  */
1497 static void pmccntr_op_finish(CPUARMState *env)
1498 {
1499     if (pmu_counter_enabled(env, 31)) {
1500 #ifndef CONFIG_USER_ONLY
1501         /* Calculate when the counter will next overflow */
1502         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1503         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1504             remaining_cycles = (uint32_t)remaining_cycles;
1505         }
1506         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1507 
1508         if (overflow_in > 0) {
1509             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1510                 overflow_in;
1511             ARMCPU *cpu = env_archcpu(env);
1512             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1513         }
1514 #endif
1515 
1516         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1517         if (env->cp15.c9_pmcr & PMCRD) {
1518             /* Increment once every 64 processor clock cycles */
1519             prev_cycles /= 64;
1520         }
1521         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1522     }
1523 }
1524 
1525 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1526 {
1527 
1528     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1529     uint64_t count = 0;
1530     if (event_supported(event)) {
1531         uint16_t event_idx = supported_event_map[event];
1532         count = pm_events[event_idx].get_count(env);
1533     }
1534 
1535     if (pmu_counter_enabled(env, counter)) {
1536         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1537 
1538         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1539             env->cp15.c9_pmovsr |= (1 << counter);
1540             pmu_update_irq(env);
1541         }
1542         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1543     }
1544     env->cp15.c14_pmevcntr_delta[counter] = count;
1545 }
1546 
1547 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1548 {
1549     if (pmu_counter_enabled(env, counter)) {
1550 #ifndef CONFIG_USER_ONLY
1551         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1552         uint16_t event_idx = supported_event_map[event];
1553         uint64_t delta = UINT32_MAX -
1554             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1555         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1556 
1557         if (overflow_in > 0) {
1558             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1559                 overflow_in;
1560             ARMCPU *cpu = env_archcpu(env);
1561             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1562         }
1563 #endif
1564 
1565         env->cp15.c14_pmevcntr_delta[counter] -=
1566             env->cp15.c14_pmevcntr[counter];
1567     }
1568 }
1569 
1570 void pmu_op_start(CPUARMState *env)
1571 {
1572     unsigned int i;
1573     pmccntr_op_start(env);
1574     for (i = 0; i < pmu_num_counters(env); i++) {
1575         pmevcntr_op_start(env, i);
1576     }
1577 }
1578 
1579 void pmu_op_finish(CPUARMState *env)
1580 {
1581     unsigned int i;
1582     pmccntr_op_finish(env);
1583     for (i = 0; i < pmu_num_counters(env); i++) {
1584         pmevcntr_op_finish(env, i);
1585     }
1586 }
1587 
1588 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1589 {
1590     pmu_op_start(&cpu->env);
1591 }
1592 
1593 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1594 {
1595     pmu_op_finish(&cpu->env);
1596 }
1597 
1598 void arm_pmu_timer_cb(void *opaque)
1599 {
1600     ARMCPU *cpu = opaque;
1601 
1602     /*
1603      * Update all the counter values based on the current underlying counts,
1604      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1605      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1606      * counter may expire.
1607      */
1608     pmu_op_start(&cpu->env);
1609     pmu_op_finish(&cpu->env);
1610 }
1611 
1612 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1613                        uint64_t value)
1614 {
1615     pmu_op_start(env);
1616 
1617     if (value & PMCRC) {
1618         /* The counter has been reset */
1619         env->cp15.c15_ccnt = 0;
1620     }
1621 
1622     if (value & PMCRP) {
1623         unsigned int i;
1624         for (i = 0; i < pmu_num_counters(env); i++) {
1625             env->cp15.c14_pmevcntr[i] = 0;
1626         }
1627     }
1628 
1629     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1630     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1631 
1632     pmu_op_finish(env);
1633 }
1634 
1635 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1636                           uint64_t value)
1637 {
1638     unsigned int i;
1639     for (i = 0; i < pmu_num_counters(env); i++) {
1640         /* Increment a counter's count iff: */
1641         if ((value & (1 << i)) && /* counter's bit is set */
1642                 /* counter is enabled and not filtered */
1643                 pmu_counter_enabled(env, i) &&
1644                 /* counter is SW_INCR */
1645                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1646             pmevcntr_op_start(env, i);
1647 
1648             /*
1649              * Detect if this write causes an overflow since we can't predict
1650              * PMSWINC overflows like we can for other events
1651              */
1652             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1653 
1654             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1655                 env->cp15.c9_pmovsr |= (1 << i);
1656                 pmu_update_irq(env);
1657             }
1658 
1659             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1660 
1661             pmevcntr_op_finish(env, i);
1662         }
1663     }
1664 }
1665 
1666 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1667 {
1668     uint64_t ret;
1669     pmccntr_op_start(env);
1670     ret = env->cp15.c15_ccnt;
1671     pmccntr_op_finish(env);
1672     return ret;
1673 }
1674 
1675 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1676                          uint64_t value)
1677 {
1678     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1679      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1680      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1681      * accessed.
1682      */
1683     env->cp15.c9_pmselr = value & 0x1f;
1684 }
1685 
1686 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1687                         uint64_t value)
1688 {
1689     pmccntr_op_start(env);
1690     env->cp15.c15_ccnt = value;
1691     pmccntr_op_finish(env);
1692 }
1693 
1694 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1695                             uint64_t value)
1696 {
1697     uint64_t cur_val = pmccntr_read(env, NULL);
1698 
1699     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1700 }
1701 
1702 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1703                             uint64_t value)
1704 {
1705     pmccntr_op_start(env);
1706     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1707     pmccntr_op_finish(env);
1708 }
1709 
1710 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1711                             uint64_t value)
1712 {
1713     pmccntr_op_start(env);
1714     /* M is not accessible from AArch32 */
1715     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1716         (value & PMCCFILTR);
1717     pmccntr_op_finish(env);
1718 }
1719 
1720 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1721 {
1722     /* M is not visible in AArch32 */
1723     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1724 }
1725 
1726 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1727                             uint64_t value)
1728 {
1729     value &= pmu_counter_mask(env);
1730     env->cp15.c9_pmcnten |= value;
1731 }
1732 
1733 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1734                              uint64_t value)
1735 {
1736     value &= pmu_counter_mask(env);
1737     env->cp15.c9_pmcnten &= ~value;
1738 }
1739 
1740 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1741                          uint64_t value)
1742 {
1743     value &= pmu_counter_mask(env);
1744     env->cp15.c9_pmovsr &= ~value;
1745     pmu_update_irq(env);
1746 }
1747 
1748 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1749                          uint64_t value)
1750 {
1751     value &= pmu_counter_mask(env);
1752     env->cp15.c9_pmovsr |= value;
1753     pmu_update_irq(env);
1754 }
1755 
1756 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1757                              uint64_t value, const uint8_t counter)
1758 {
1759     if (counter == 31) {
1760         pmccfiltr_write(env, ri, value);
1761     } else if (counter < pmu_num_counters(env)) {
1762         pmevcntr_op_start(env, counter);
1763 
1764         /*
1765          * If this counter's event type is changing, store the current
1766          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1767          * pmevcntr_op_finish has the correct baseline when it converts back to
1768          * a delta.
1769          */
1770         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1771             PMXEVTYPER_EVTCOUNT;
1772         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1773         if (old_event != new_event) {
1774             uint64_t count = 0;
1775             if (event_supported(new_event)) {
1776                 uint16_t event_idx = supported_event_map[new_event];
1777                 count = pm_events[event_idx].get_count(env);
1778             }
1779             env->cp15.c14_pmevcntr_delta[counter] = count;
1780         }
1781 
1782         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1783         pmevcntr_op_finish(env, counter);
1784     }
1785     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1786      * PMSELR value is equal to or greater than the number of implemented
1787      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1788      */
1789 }
1790 
1791 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1792                                const uint8_t counter)
1793 {
1794     if (counter == 31) {
1795         return env->cp15.pmccfiltr_el0;
1796     } else if (counter < pmu_num_counters(env)) {
1797         return env->cp15.c14_pmevtyper[counter];
1798     } else {
1799       /*
1800        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1801        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1802        */
1803         return 0;
1804     }
1805 }
1806 
1807 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1808                               uint64_t value)
1809 {
1810     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1811     pmevtyper_write(env, ri, value, counter);
1812 }
1813 
1814 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1815                                uint64_t value)
1816 {
1817     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1818     env->cp15.c14_pmevtyper[counter] = value;
1819 
1820     /*
1821      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1822      * pmu_op_finish calls when loading saved state for a migration. Because
1823      * we're potentially updating the type of event here, the value written to
1824      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1825      * different counter type. Therefore, we need to set this value to the
1826      * current count for the counter type we're writing so that pmu_op_finish
1827      * has the correct count for its calculation.
1828      */
1829     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1830     if (event_supported(event)) {
1831         uint16_t event_idx = supported_event_map[event];
1832         env->cp15.c14_pmevcntr_delta[counter] =
1833             pm_events[event_idx].get_count(env);
1834     }
1835 }
1836 
1837 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1838 {
1839     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1840     return pmevtyper_read(env, ri, counter);
1841 }
1842 
1843 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1844                              uint64_t value)
1845 {
1846     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1847 }
1848 
1849 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1850 {
1851     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1852 }
1853 
1854 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1855                              uint64_t value, uint8_t counter)
1856 {
1857     if (counter < pmu_num_counters(env)) {
1858         pmevcntr_op_start(env, counter);
1859         env->cp15.c14_pmevcntr[counter] = value;
1860         pmevcntr_op_finish(env, counter);
1861     }
1862     /*
1863      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1864      * are CONSTRAINED UNPREDICTABLE.
1865      */
1866 }
1867 
1868 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1869                               uint8_t counter)
1870 {
1871     if (counter < pmu_num_counters(env)) {
1872         uint64_t ret;
1873         pmevcntr_op_start(env, counter);
1874         ret = env->cp15.c14_pmevcntr[counter];
1875         pmevcntr_op_finish(env, counter);
1876         return ret;
1877     } else {
1878       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1879        * are CONSTRAINED UNPREDICTABLE. */
1880         return 0;
1881     }
1882 }
1883 
1884 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1885                              uint64_t value)
1886 {
1887     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1888     pmevcntr_write(env, ri, value, counter);
1889 }
1890 
1891 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1892 {
1893     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1894     return pmevcntr_read(env, ri, counter);
1895 }
1896 
1897 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1898                              uint64_t value)
1899 {
1900     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1901     assert(counter < pmu_num_counters(env));
1902     env->cp15.c14_pmevcntr[counter] = value;
1903     pmevcntr_write(env, ri, value, counter);
1904 }
1905 
1906 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1907 {
1908     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1909     assert(counter < pmu_num_counters(env));
1910     return env->cp15.c14_pmevcntr[counter];
1911 }
1912 
1913 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1914                              uint64_t value)
1915 {
1916     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1917 }
1918 
1919 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1920 {
1921     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1922 }
1923 
1924 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1925                             uint64_t value)
1926 {
1927     if (arm_feature(env, ARM_FEATURE_V8)) {
1928         env->cp15.c9_pmuserenr = value & 0xf;
1929     } else {
1930         env->cp15.c9_pmuserenr = value & 1;
1931     }
1932 }
1933 
1934 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1935                              uint64_t value)
1936 {
1937     /* We have no event counters so only the C bit can be changed */
1938     value &= pmu_counter_mask(env);
1939     env->cp15.c9_pminten |= value;
1940     pmu_update_irq(env);
1941 }
1942 
1943 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1944                              uint64_t value)
1945 {
1946     value &= pmu_counter_mask(env);
1947     env->cp15.c9_pminten &= ~value;
1948     pmu_update_irq(env);
1949 }
1950 
1951 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1952                        uint64_t value)
1953 {
1954     /* Note that even though the AArch64 view of this register has bits
1955      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1956      * architectural requirements for bits which are RES0 only in some
1957      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1958      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1959      */
1960     raw_write(env, ri, value & ~0x1FULL);
1961 }
1962 
1963 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1964 {
1965     /* Begin with base v8.0 state.  */
1966     uint32_t valid_mask = 0x3fff;
1967     ARMCPU *cpu = env_archcpu(env);
1968 
1969     if (arm_el_is_aa64(env, 3)) {
1970         value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1971         valid_mask &= ~SCR_NET;
1972     } else {
1973         valid_mask &= ~(SCR_RW | SCR_ST);
1974     }
1975 
1976     if (!arm_feature(env, ARM_FEATURE_EL2)) {
1977         valid_mask &= ~SCR_HCE;
1978 
1979         /* On ARMv7, SMD (or SCD as it is called in v7) is only
1980          * supported if EL2 exists. The bit is UNK/SBZP when
1981          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
1982          * when EL2 is unavailable.
1983          * On ARMv8, this bit is always available.
1984          */
1985         if (arm_feature(env, ARM_FEATURE_V7) &&
1986             !arm_feature(env, ARM_FEATURE_V8)) {
1987             valid_mask &= ~SCR_SMD;
1988         }
1989     }
1990     if (cpu_isar_feature(aa64_lor, cpu)) {
1991         valid_mask |= SCR_TLOR;
1992     }
1993     if (cpu_isar_feature(aa64_pauth, cpu)) {
1994         valid_mask |= SCR_API | SCR_APK;
1995     }
1996 
1997     /* Clear all-context RES0 bits.  */
1998     value &= valid_mask;
1999     raw_write(env, ri, value);
2000 }
2001 
2002 static CPAccessResult access_aa64_tid2(CPUARMState *env,
2003                                        const ARMCPRegInfo *ri,
2004                                        bool isread)
2005 {
2006     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
2007         return CP_ACCESS_TRAP_EL2;
2008     }
2009 
2010     return CP_ACCESS_OK;
2011 }
2012 
2013 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2014 {
2015     ARMCPU *cpu = env_archcpu(env);
2016 
2017     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
2018      * bank
2019      */
2020     uint32_t index = A32_BANKED_REG_GET(env, csselr,
2021                                         ri->secure & ARM_CP_SECSTATE_S);
2022 
2023     return cpu->ccsidr[index];
2024 }
2025 
2026 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2027                          uint64_t value)
2028 {
2029     raw_write(env, ri, value & 0xf);
2030 }
2031 
2032 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2033 {
2034     CPUState *cs = env_cpu(env);
2035     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
2036     uint64_t ret = 0;
2037     bool allow_virt = (arm_current_el(env) == 1 &&
2038                        (!arm_is_secure_below_el3(env) ||
2039                         (env->cp15.scr_el3 & SCR_EEL2)));
2040 
2041     if (allow_virt && (hcr_el2 & HCR_IMO)) {
2042         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
2043             ret |= CPSR_I;
2044         }
2045     } else {
2046         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
2047             ret |= CPSR_I;
2048         }
2049     }
2050 
2051     if (allow_virt && (hcr_el2 & HCR_FMO)) {
2052         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
2053             ret |= CPSR_F;
2054         }
2055     } else {
2056         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
2057             ret |= CPSR_F;
2058         }
2059     }
2060 
2061     /* External aborts are not possible in QEMU so A bit is always clear */
2062     return ret;
2063 }
2064 
2065 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2066                                        bool isread)
2067 {
2068     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
2069         return CP_ACCESS_TRAP_EL2;
2070     }
2071 
2072     return CP_ACCESS_OK;
2073 }
2074 
2075 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2076                                        bool isread)
2077 {
2078     if (arm_feature(env, ARM_FEATURE_V8)) {
2079         return access_aa64_tid1(env, ri, isread);
2080     }
2081 
2082     return CP_ACCESS_OK;
2083 }
2084 
2085 static const ARMCPRegInfo v7_cp_reginfo[] = {
2086     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
2087     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
2088       .access = PL1_W, .type = ARM_CP_NOP },
2089     /* Performance monitors are implementation defined in v7,
2090      * but with an ARM recommended set of registers, which we
2091      * follow.
2092      *
2093      * Performance registers fall into three categories:
2094      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
2095      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
2096      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
2097      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
2098      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
2099      */
2100     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
2101       .access = PL0_RW, .type = ARM_CP_ALIAS,
2102       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2103       .writefn = pmcntenset_write,
2104       .accessfn = pmreg_access,
2105       .raw_writefn = raw_write },
2106     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
2107       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
2108       .access = PL0_RW, .accessfn = pmreg_access,
2109       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
2110       .writefn = pmcntenset_write, .raw_writefn = raw_write },
2111     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
2112       .access = PL0_RW,
2113       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2114       .accessfn = pmreg_access,
2115       .writefn = pmcntenclr_write,
2116       .type = ARM_CP_ALIAS },
2117     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
2118       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
2119       .access = PL0_RW, .accessfn = pmreg_access,
2120       .type = ARM_CP_ALIAS,
2121       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
2122       .writefn = pmcntenclr_write },
2123     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
2124       .access = PL0_RW, .type = ARM_CP_IO,
2125       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2126       .accessfn = pmreg_access,
2127       .writefn = pmovsr_write,
2128       .raw_writefn = raw_write },
2129     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2130       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2131       .access = PL0_RW, .accessfn = pmreg_access,
2132       .type = ARM_CP_ALIAS | ARM_CP_IO,
2133       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2134       .writefn = pmovsr_write,
2135       .raw_writefn = raw_write },
2136     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2137       .access = PL0_W, .accessfn = pmreg_access_swinc,
2138       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2139       .writefn = pmswinc_write },
2140     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2141       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2142       .access = PL0_W, .accessfn = pmreg_access_swinc,
2143       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2144       .writefn = pmswinc_write },
2145     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2146       .access = PL0_RW, .type = ARM_CP_ALIAS,
2147       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2148       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2149       .raw_writefn = raw_write},
2150     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2151       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2152       .access = PL0_RW, .accessfn = pmreg_access_selr,
2153       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2154       .writefn = pmselr_write, .raw_writefn = raw_write, },
2155     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2156       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2157       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2158       .accessfn = pmreg_access_ccntr },
2159     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2160       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2161       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2162       .type = ARM_CP_IO,
2163       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2164       .readfn = pmccntr_read, .writefn = pmccntr_write,
2165       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2166     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2167       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2168       .access = PL0_RW, .accessfn = pmreg_access,
2169       .type = ARM_CP_ALIAS | ARM_CP_IO,
2170       .resetvalue = 0, },
2171     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2172       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2173       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2174       .access = PL0_RW, .accessfn = pmreg_access,
2175       .type = ARM_CP_IO,
2176       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2177       .resetvalue = 0, },
2178     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2179       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2180       .accessfn = pmreg_access,
2181       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2182     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2183       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2184       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2185       .accessfn = pmreg_access,
2186       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2187     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2188       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2189       .accessfn = pmreg_access_xevcntr,
2190       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2191     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2192       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2193       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2194       .accessfn = pmreg_access_xevcntr,
2195       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2196     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2197       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2198       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2199       .resetvalue = 0,
2200       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2201     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2202       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2203       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2204       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2205       .resetvalue = 0,
2206       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2207     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2208       .access = PL1_RW, .accessfn = access_tpm,
2209       .type = ARM_CP_ALIAS | ARM_CP_IO,
2210       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2211       .resetvalue = 0,
2212       .writefn = pmintenset_write, .raw_writefn = raw_write },
2213     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2214       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2215       .access = PL1_RW, .accessfn = access_tpm,
2216       .type = ARM_CP_IO,
2217       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2218       .writefn = pmintenset_write, .raw_writefn = raw_write,
2219       .resetvalue = 0x0 },
2220     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2221       .access = PL1_RW, .accessfn = access_tpm,
2222       .type = ARM_CP_ALIAS | ARM_CP_IO,
2223       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2224       .writefn = pmintenclr_write, },
2225     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2226       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2227       .access = PL1_RW, .accessfn = access_tpm,
2228       .type = ARM_CP_ALIAS | ARM_CP_IO,
2229       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2230       .writefn = pmintenclr_write },
2231     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2232       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2233       .access = PL1_R,
2234       .accessfn = access_aa64_tid2,
2235       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2236     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2237       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2238       .access = PL1_RW,
2239       .accessfn = access_aa64_tid2,
2240       .writefn = csselr_write, .resetvalue = 0,
2241       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2242                              offsetof(CPUARMState, cp15.csselr_ns) } },
2243     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2244      * just RAZ for all cores:
2245      */
2246     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2247       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2248       .access = PL1_R, .type = ARM_CP_CONST,
2249       .accessfn = access_aa64_tid1,
2250       .resetvalue = 0 },
2251     /* Auxiliary fault status registers: these also are IMPDEF, and we
2252      * choose to RAZ/WI for all cores.
2253      */
2254     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2255       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2256       .access = PL1_RW, .accessfn = access_tvm_trvm,
2257       .type = ARM_CP_CONST, .resetvalue = 0 },
2258     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2259       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2260       .access = PL1_RW, .accessfn = access_tvm_trvm,
2261       .type = ARM_CP_CONST, .resetvalue = 0 },
2262     /* MAIR can just read-as-written because we don't implement caches
2263      * and so don't need to care about memory attributes.
2264      */
2265     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2266       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2267       .access = PL1_RW, .accessfn = access_tvm_trvm,
2268       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2269       .resetvalue = 0 },
2270     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2271       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2272       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2273       .resetvalue = 0 },
2274     /* For non-long-descriptor page tables these are PRRR and NMRR;
2275      * regardless they still act as reads-as-written for QEMU.
2276      */
2277      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2278       * allows them to assign the correct fieldoffset based on the endianness
2279       * handled in the field definitions.
2280       */
2281     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2282       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2283       .access = PL1_RW, .accessfn = access_tvm_trvm,
2284       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2285                              offsetof(CPUARMState, cp15.mair0_ns) },
2286       .resetfn = arm_cp_reset_ignore },
2287     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2288       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2289       .access = PL1_RW, .accessfn = access_tvm_trvm,
2290       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2291                              offsetof(CPUARMState, cp15.mair1_ns) },
2292       .resetfn = arm_cp_reset_ignore },
2293     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2294       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2295       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2296     /* 32 bit ITLB invalidates */
2297     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2298       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2299       .writefn = tlbiall_write },
2300     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2301       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2302       .writefn = tlbimva_write },
2303     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2304       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2305       .writefn = tlbiasid_write },
2306     /* 32 bit DTLB invalidates */
2307     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2308       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2309       .writefn = tlbiall_write },
2310     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2311       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2312       .writefn = tlbimva_write },
2313     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2314       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2315       .writefn = tlbiasid_write },
2316     /* 32 bit TLB invalidates */
2317     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2318       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2319       .writefn = tlbiall_write },
2320     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2321       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2322       .writefn = tlbimva_write },
2323     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2324       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2325       .writefn = tlbiasid_write },
2326     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2327       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2328       .writefn = tlbimvaa_write },
2329     REGINFO_SENTINEL
2330 };
2331 
2332 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2333     /* 32 bit TLB invalidates, Inner Shareable */
2334     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2335       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2336       .writefn = tlbiall_is_write },
2337     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2338       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2339       .writefn = tlbimva_is_write },
2340     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2341       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2342       .writefn = tlbiasid_is_write },
2343     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2344       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2345       .writefn = tlbimvaa_is_write },
2346     REGINFO_SENTINEL
2347 };
2348 
2349 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2350     /* PMOVSSET is not implemented in v7 before v7ve */
2351     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2352       .access = PL0_RW, .accessfn = pmreg_access,
2353       .type = ARM_CP_ALIAS | ARM_CP_IO,
2354       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2355       .writefn = pmovsset_write,
2356       .raw_writefn = raw_write },
2357     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2358       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2359       .access = PL0_RW, .accessfn = pmreg_access,
2360       .type = ARM_CP_ALIAS | ARM_CP_IO,
2361       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2362       .writefn = pmovsset_write,
2363       .raw_writefn = raw_write },
2364     REGINFO_SENTINEL
2365 };
2366 
2367 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2368                         uint64_t value)
2369 {
2370     value &= 1;
2371     env->teecr = value;
2372 }
2373 
2374 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2375                                     bool isread)
2376 {
2377     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2378         return CP_ACCESS_TRAP;
2379     }
2380     return CP_ACCESS_OK;
2381 }
2382 
2383 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2384     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2385       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2386       .resetvalue = 0,
2387       .writefn = teecr_write },
2388     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2389       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2390       .accessfn = teehbr_access, .resetvalue = 0 },
2391     REGINFO_SENTINEL
2392 };
2393 
2394 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2395     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2396       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2397       .access = PL0_RW,
2398       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2399     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2400       .access = PL0_RW,
2401       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2402                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2403       .resetfn = arm_cp_reset_ignore },
2404     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2405       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2406       .access = PL0_R|PL1_W,
2407       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2408       .resetvalue = 0},
2409     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2410       .access = PL0_R|PL1_W,
2411       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2412                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2413       .resetfn = arm_cp_reset_ignore },
2414     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2415       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2416       .access = PL1_RW,
2417       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2418     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2419       .access = PL1_RW,
2420       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2421                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2422       .resetvalue = 0 },
2423     REGINFO_SENTINEL
2424 };
2425 
2426 #ifndef CONFIG_USER_ONLY
2427 
2428 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2429                                        bool isread)
2430 {
2431     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2432      * Writable only at the highest implemented exception level.
2433      */
2434     int el = arm_current_el(env);
2435     uint64_t hcr;
2436     uint32_t cntkctl;
2437 
2438     switch (el) {
2439     case 0:
2440         hcr = arm_hcr_el2_eff(env);
2441         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2442             cntkctl = env->cp15.cnthctl_el2;
2443         } else {
2444             cntkctl = env->cp15.c14_cntkctl;
2445         }
2446         if (!extract32(cntkctl, 0, 2)) {
2447             return CP_ACCESS_TRAP;
2448         }
2449         break;
2450     case 1:
2451         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2452             arm_is_secure_below_el3(env)) {
2453             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2454             return CP_ACCESS_TRAP_UNCATEGORIZED;
2455         }
2456         break;
2457     case 2:
2458     case 3:
2459         break;
2460     }
2461 
2462     if (!isread && el < arm_highest_el(env)) {
2463         return CP_ACCESS_TRAP_UNCATEGORIZED;
2464     }
2465 
2466     return CP_ACCESS_OK;
2467 }
2468 
2469 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2470                                         bool isread)
2471 {
2472     unsigned int cur_el = arm_current_el(env);
2473     bool secure = arm_is_secure(env);
2474     uint64_t hcr = arm_hcr_el2_eff(env);
2475 
2476     switch (cur_el) {
2477     case 0:
2478         /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2479         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2480             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2481                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2482         }
2483 
2484         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2485         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2486             return CP_ACCESS_TRAP;
2487         }
2488 
2489         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2490         if (hcr & HCR_E2H) {
2491             if (timeridx == GTIMER_PHYS &&
2492                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2493                 return CP_ACCESS_TRAP_EL2;
2494             }
2495         } else {
2496             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2497             if (arm_feature(env, ARM_FEATURE_EL2) &&
2498                 timeridx == GTIMER_PHYS && !secure &&
2499                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2500                 return CP_ACCESS_TRAP_EL2;
2501             }
2502         }
2503         break;
2504 
2505     case 1:
2506         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2507         if (arm_feature(env, ARM_FEATURE_EL2) &&
2508             timeridx == GTIMER_PHYS && !secure &&
2509             (hcr & HCR_E2H
2510              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2511              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2512             return CP_ACCESS_TRAP_EL2;
2513         }
2514         break;
2515     }
2516     return CP_ACCESS_OK;
2517 }
2518 
2519 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2520                                       bool isread)
2521 {
2522     unsigned int cur_el = arm_current_el(env);
2523     bool secure = arm_is_secure(env);
2524     uint64_t hcr = arm_hcr_el2_eff(env);
2525 
2526     switch (cur_el) {
2527     case 0:
2528         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2529             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2530             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2531                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2532         }
2533 
2534         /*
2535          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2536          * EL0 if EL0[PV]TEN is zero.
2537          */
2538         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2539             return CP_ACCESS_TRAP;
2540         }
2541         /* fall through */
2542 
2543     case 1:
2544         if (arm_feature(env, ARM_FEATURE_EL2) &&
2545             timeridx == GTIMER_PHYS && !secure) {
2546             if (hcr & HCR_E2H) {
2547                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2548                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2549                     return CP_ACCESS_TRAP_EL2;
2550                 }
2551             } else {
2552                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2553                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2554                     return CP_ACCESS_TRAP_EL2;
2555                 }
2556             }
2557         }
2558         break;
2559     }
2560     return CP_ACCESS_OK;
2561 }
2562 
2563 static CPAccessResult gt_pct_access(CPUARMState *env,
2564                                     const ARMCPRegInfo *ri,
2565                                     bool isread)
2566 {
2567     return gt_counter_access(env, GTIMER_PHYS, isread);
2568 }
2569 
2570 static CPAccessResult gt_vct_access(CPUARMState *env,
2571                                     const ARMCPRegInfo *ri,
2572                                     bool isread)
2573 {
2574     return gt_counter_access(env, GTIMER_VIRT, isread);
2575 }
2576 
2577 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2578                                        bool isread)
2579 {
2580     return gt_timer_access(env, GTIMER_PHYS, isread);
2581 }
2582 
2583 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2584                                        bool isread)
2585 {
2586     return gt_timer_access(env, GTIMER_VIRT, isread);
2587 }
2588 
2589 static CPAccessResult gt_stimer_access(CPUARMState *env,
2590                                        const ARMCPRegInfo *ri,
2591                                        bool isread)
2592 {
2593     /* The AArch64 register view of the secure physical timer is
2594      * always accessible from EL3, and configurably accessible from
2595      * Secure EL1.
2596      */
2597     switch (arm_current_el(env)) {
2598     case 1:
2599         if (!arm_is_secure(env)) {
2600             return CP_ACCESS_TRAP;
2601         }
2602         if (!(env->cp15.scr_el3 & SCR_ST)) {
2603             return CP_ACCESS_TRAP_EL3;
2604         }
2605         return CP_ACCESS_OK;
2606     case 0:
2607     case 2:
2608         return CP_ACCESS_TRAP;
2609     case 3:
2610         return CP_ACCESS_OK;
2611     default:
2612         g_assert_not_reached();
2613     }
2614 }
2615 
2616 static uint64_t gt_get_countervalue(CPUARMState *env)
2617 {
2618     ARMCPU *cpu = env_archcpu(env);
2619 
2620     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2621 }
2622 
2623 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2624 {
2625     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2626 
2627     if (gt->ctl & 1) {
2628         /* Timer enabled: calculate and set current ISTATUS, irq, and
2629          * reset timer to when ISTATUS next has to change
2630          */
2631         uint64_t offset = timeridx == GTIMER_VIRT ?
2632                                       cpu->env.cp15.cntvoff_el2 : 0;
2633         uint64_t count = gt_get_countervalue(&cpu->env);
2634         /* Note that this must be unsigned 64 bit arithmetic: */
2635         int istatus = count - offset >= gt->cval;
2636         uint64_t nexttick;
2637         int irqstate;
2638 
2639         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2640 
2641         irqstate = (istatus && !(gt->ctl & 2));
2642         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2643 
2644         if (istatus) {
2645             /* Next transition is when count rolls back over to zero */
2646             nexttick = UINT64_MAX;
2647         } else {
2648             /* Next transition is when we hit cval */
2649             nexttick = gt->cval + offset;
2650         }
2651         /* Note that the desired next expiry time might be beyond the
2652          * signed-64-bit range of a QEMUTimer -- in this case we just
2653          * set the timer for as far in the future as possible. When the
2654          * timer expires we will reset the timer for any remaining period.
2655          */
2656         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2657             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2658         } else {
2659             timer_mod(cpu->gt_timer[timeridx], nexttick);
2660         }
2661         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2662     } else {
2663         /* Timer disabled: ISTATUS and timer output always clear */
2664         gt->ctl &= ~4;
2665         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2666         timer_del(cpu->gt_timer[timeridx]);
2667         trace_arm_gt_recalc_disabled(timeridx);
2668     }
2669 }
2670 
2671 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2672                            int timeridx)
2673 {
2674     ARMCPU *cpu = env_archcpu(env);
2675 
2676     timer_del(cpu->gt_timer[timeridx]);
2677 }
2678 
2679 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2680 {
2681     return gt_get_countervalue(env);
2682 }
2683 
2684 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2685 {
2686     uint64_t hcr;
2687 
2688     switch (arm_current_el(env)) {
2689     case 2:
2690         hcr = arm_hcr_el2_eff(env);
2691         if (hcr & HCR_E2H) {
2692             return 0;
2693         }
2694         break;
2695     case 0:
2696         hcr = arm_hcr_el2_eff(env);
2697         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2698             return 0;
2699         }
2700         break;
2701     }
2702 
2703     return env->cp15.cntvoff_el2;
2704 }
2705 
2706 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2707 {
2708     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2709 }
2710 
2711 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2712                           int timeridx,
2713                           uint64_t value)
2714 {
2715     trace_arm_gt_cval_write(timeridx, value);
2716     env->cp15.c14_timer[timeridx].cval = value;
2717     gt_recalc_timer(env_archcpu(env), timeridx);
2718 }
2719 
2720 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2721                              int timeridx)
2722 {
2723     uint64_t offset = 0;
2724 
2725     switch (timeridx) {
2726     case GTIMER_VIRT:
2727     case GTIMER_HYPVIRT:
2728         offset = gt_virt_cnt_offset(env);
2729         break;
2730     }
2731 
2732     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2733                       (gt_get_countervalue(env) - offset));
2734 }
2735 
2736 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2737                           int timeridx,
2738                           uint64_t value)
2739 {
2740     uint64_t offset = 0;
2741 
2742     switch (timeridx) {
2743     case GTIMER_VIRT:
2744     case GTIMER_HYPVIRT:
2745         offset = gt_virt_cnt_offset(env);
2746         break;
2747     }
2748 
2749     trace_arm_gt_tval_write(timeridx, value);
2750     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2751                                          sextract64(value, 0, 32);
2752     gt_recalc_timer(env_archcpu(env), timeridx);
2753 }
2754 
2755 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2756                          int timeridx,
2757                          uint64_t value)
2758 {
2759     ARMCPU *cpu = env_archcpu(env);
2760     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2761 
2762     trace_arm_gt_ctl_write(timeridx, value);
2763     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2764     if ((oldval ^ value) & 1) {
2765         /* Enable toggled */
2766         gt_recalc_timer(cpu, timeridx);
2767     } else if ((oldval ^ value) & 2) {
2768         /* IMASK toggled: don't need to recalculate,
2769          * just set the interrupt line based on ISTATUS
2770          */
2771         int irqstate = (oldval & 4) && !(value & 2);
2772 
2773         trace_arm_gt_imask_toggle(timeridx, irqstate);
2774         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2775     }
2776 }
2777 
2778 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2779 {
2780     gt_timer_reset(env, ri, GTIMER_PHYS);
2781 }
2782 
2783 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2784                                uint64_t value)
2785 {
2786     gt_cval_write(env, ri, GTIMER_PHYS, value);
2787 }
2788 
2789 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2790 {
2791     return gt_tval_read(env, ri, GTIMER_PHYS);
2792 }
2793 
2794 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2795                                uint64_t value)
2796 {
2797     gt_tval_write(env, ri, GTIMER_PHYS, value);
2798 }
2799 
2800 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2801                               uint64_t value)
2802 {
2803     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2804 }
2805 
2806 static int gt_phys_redir_timeridx(CPUARMState *env)
2807 {
2808     switch (arm_mmu_idx(env)) {
2809     case ARMMMUIdx_E20_0:
2810     case ARMMMUIdx_E20_2:
2811     case ARMMMUIdx_E20_2_PAN:
2812         return GTIMER_HYP;
2813     default:
2814         return GTIMER_PHYS;
2815     }
2816 }
2817 
2818 static int gt_virt_redir_timeridx(CPUARMState *env)
2819 {
2820     switch (arm_mmu_idx(env)) {
2821     case ARMMMUIdx_E20_0:
2822     case ARMMMUIdx_E20_2:
2823     case ARMMMUIdx_E20_2_PAN:
2824         return GTIMER_HYPVIRT;
2825     default:
2826         return GTIMER_VIRT;
2827     }
2828 }
2829 
2830 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2831                                         const ARMCPRegInfo *ri)
2832 {
2833     int timeridx = gt_phys_redir_timeridx(env);
2834     return env->cp15.c14_timer[timeridx].cval;
2835 }
2836 
2837 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2838                                      uint64_t value)
2839 {
2840     int timeridx = gt_phys_redir_timeridx(env);
2841     gt_cval_write(env, ri, timeridx, value);
2842 }
2843 
2844 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2845                                         const ARMCPRegInfo *ri)
2846 {
2847     int timeridx = gt_phys_redir_timeridx(env);
2848     return gt_tval_read(env, ri, timeridx);
2849 }
2850 
2851 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2852                                      uint64_t value)
2853 {
2854     int timeridx = gt_phys_redir_timeridx(env);
2855     gt_tval_write(env, ri, timeridx, value);
2856 }
2857 
2858 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2859                                        const ARMCPRegInfo *ri)
2860 {
2861     int timeridx = gt_phys_redir_timeridx(env);
2862     return env->cp15.c14_timer[timeridx].ctl;
2863 }
2864 
2865 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2866                                     uint64_t value)
2867 {
2868     int timeridx = gt_phys_redir_timeridx(env);
2869     gt_ctl_write(env, ri, timeridx, value);
2870 }
2871 
2872 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2873 {
2874     gt_timer_reset(env, ri, GTIMER_VIRT);
2875 }
2876 
2877 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2878                                uint64_t value)
2879 {
2880     gt_cval_write(env, ri, GTIMER_VIRT, value);
2881 }
2882 
2883 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2884 {
2885     return gt_tval_read(env, ri, GTIMER_VIRT);
2886 }
2887 
2888 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2889                                uint64_t value)
2890 {
2891     gt_tval_write(env, ri, GTIMER_VIRT, value);
2892 }
2893 
2894 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2895                               uint64_t value)
2896 {
2897     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2898 }
2899 
2900 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2901                               uint64_t value)
2902 {
2903     ARMCPU *cpu = env_archcpu(env);
2904 
2905     trace_arm_gt_cntvoff_write(value);
2906     raw_write(env, ri, value);
2907     gt_recalc_timer(cpu, GTIMER_VIRT);
2908 }
2909 
2910 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
2911                                         const ARMCPRegInfo *ri)
2912 {
2913     int timeridx = gt_virt_redir_timeridx(env);
2914     return env->cp15.c14_timer[timeridx].cval;
2915 }
2916 
2917 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2918                                      uint64_t value)
2919 {
2920     int timeridx = gt_virt_redir_timeridx(env);
2921     gt_cval_write(env, ri, timeridx, value);
2922 }
2923 
2924 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
2925                                         const ARMCPRegInfo *ri)
2926 {
2927     int timeridx = gt_virt_redir_timeridx(env);
2928     return gt_tval_read(env, ri, timeridx);
2929 }
2930 
2931 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2932                                      uint64_t value)
2933 {
2934     int timeridx = gt_virt_redir_timeridx(env);
2935     gt_tval_write(env, ri, timeridx, value);
2936 }
2937 
2938 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
2939                                        const ARMCPRegInfo *ri)
2940 {
2941     int timeridx = gt_virt_redir_timeridx(env);
2942     return env->cp15.c14_timer[timeridx].ctl;
2943 }
2944 
2945 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2946                                     uint64_t value)
2947 {
2948     int timeridx = gt_virt_redir_timeridx(env);
2949     gt_ctl_write(env, ri, timeridx, value);
2950 }
2951 
2952 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2953 {
2954     gt_timer_reset(env, ri, GTIMER_HYP);
2955 }
2956 
2957 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2958                               uint64_t value)
2959 {
2960     gt_cval_write(env, ri, GTIMER_HYP, value);
2961 }
2962 
2963 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2964 {
2965     return gt_tval_read(env, ri, GTIMER_HYP);
2966 }
2967 
2968 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2969                               uint64_t value)
2970 {
2971     gt_tval_write(env, ri, GTIMER_HYP, value);
2972 }
2973 
2974 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2975                               uint64_t value)
2976 {
2977     gt_ctl_write(env, ri, GTIMER_HYP, value);
2978 }
2979 
2980 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2981 {
2982     gt_timer_reset(env, ri, GTIMER_SEC);
2983 }
2984 
2985 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2986                               uint64_t value)
2987 {
2988     gt_cval_write(env, ri, GTIMER_SEC, value);
2989 }
2990 
2991 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2992 {
2993     return gt_tval_read(env, ri, GTIMER_SEC);
2994 }
2995 
2996 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2997                               uint64_t value)
2998 {
2999     gt_tval_write(env, ri, GTIMER_SEC, value);
3000 }
3001 
3002 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3003                               uint64_t value)
3004 {
3005     gt_ctl_write(env, ri, GTIMER_SEC, value);
3006 }
3007 
3008 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3009 {
3010     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
3011 }
3012 
3013 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3014                              uint64_t value)
3015 {
3016     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
3017 }
3018 
3019 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3020 {
3021     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
3022 }
3023 
3024 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3025                              uint64_t value)
3026 {
3027     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
3028 }
3029 
3030 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3031                             uint64_t value)
3032 {
3033     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
3034 }
3035 
3036 void arm_gt_ptimer_cb(void *opaque)
3037 {
3038     ARMCPU *cpu = opaque;
3039 
3040     gt_recalc_timer(cpu, GTIMER_PHYS);
3041 }
3042 
3043 void arm_gt_vtimer_cb(void *opaque)
3044 {
3045     ARMCPU *cpu = opaque;
3046 
3047     gt_recalc_timer(cpu, GTIMER_VIRT);
3048 }
3049 
3050 void arm_gt_htimer_cb(void *opaque)
3051 {
3052     ARMCPU *cpu = opaque;
3053 
3054     gt_recalc_timer(cpu, GTIMER_HYP);
3055 }
3056 
3057 void arm_gt_stimer_cb(void *opaque)
3058 {
3059     ARMCPU *cpu = opaque;
3060 
3061     gt_recalc_timer(cpu, GTIMER_SEC);
3062 }
3063 
3064 void arm_gt_hvtimer_cb(void *opaque)
3065 {
3066     ARMCPU *cpu = opaque;
3067 
3068     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
3069 }
3070 
3071 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
3072 {
3073     ARMCPU *cpu = env_archcpu(env);
3074 
3075     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
3076 }
3077 
3078 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3079     /* Note that CNTFRQ is purely reads-as-written for the benefit
3080      * of software; writing it doesn't actually change the timer frequency.
3081      * Our reset value matches the fixed frequency we implement the timer at.
3082      */
3083     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
3084       .type = ARM_CP_ALIAS,
3085       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3086       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
3087     },
3088     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3089       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3090       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3091       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3092       .resetfn = arm_gt_cntfrq_reset,
3093     },
3094     /* overall control: mostly access permissions */
3095     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
3096       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
3097       .access = PL1_RW,
3098       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
3099       .resetvalue = 0,
3100     },
3101     /* per-timer control */
3102     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3103       .secure = ARM_CP_SECSTATE_NS,
3104       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3105       .accessfn = gt_ptimer_access,
3106       .fieldoffset = offsetoflow32(CPUARMState,
3107                                    cp15.c14_timer[GTIMER_PHYS].ctl),
3108       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3109       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3110     },
3111     { .name = "CNTP_CTL_S",
3112       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3113       .secure = ARM_CP_SECSTATE_S,
3114       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3115       .accessfn = gt_ptimer_access,
3116       .fieldoffset = offsetoflow32(CPUARMState,
3117                                    cp15.c14_timer[GTIMER_SEC].ctl),
3118       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3119     },
3120     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
3121       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
3122       .type = ARM_CP_IO, .access = PL0_RW,
3123       .accessfn = gt_ptimer_access,
3124       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
3125       .resetvalue = 0,
3126       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3127       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3128     },
3129     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
3130       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3131       .accessfn = gt_vtimer_access,
3132       .fieldoffset = offsetoflow32(CPUARMState,
3133                                    cp15.c14_timer[GTIMER_VIRT].ctl),
3134       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3135       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3136     },
3137     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
3138       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
3139       .type = ARM_CP_IO, .access = PL0_RW,
3140       .accessfn = gt_vtimer_access,
3141       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
3142       .resetvalue = 0,
3143       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3144       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3145     },
3146     /* TimerValue views: a 32 bit downcounting view of the underlying state */
3147     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3148       .secure = ARM_CP_SECSTATE_NS,
3149       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3150       .accessfn = gt_ptimer_access,
3151       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3152     },
3153     { .name = "CNTP_TVAL_S",
3154       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3155       .secure = ARM_CP_SECSTATE_S,
3156       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3157       .accessfn = gt_ptimer_access,
3158       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
3159     },
3160     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3161       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
3162       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3163       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
3164       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3165     },
3166     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
3167       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3168       .accessfn = gt_vtimer_access,
3169       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3170     },
3171     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3172       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
3173       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3174       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
3175       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3176     },
3177     /* The counter itself */
3178     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
3179       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3180       .accessfn = gt_pct_access,
3181       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
3182     },
3183     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
3184       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
3185       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3186       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
3187     },
3188     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3189       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3190       .accessfn = gt_vct_access,
3191       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3192     },
3193     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3194       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3195       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3196       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3197     },
3198     /* Comparison value, indicating when the timer goes off */
3199     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3200       .secure = ARM_CP_SECSTATE_NS,
3201       .access = PL0_RW,
3202       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3203       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3204       .accessfn = gt_ptimer_access,
3205       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3206       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3207     },
3208     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3209       .secure = ARM_CP_SECSTATE_S,
3210       .access = PL0_RW,
3211       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3212       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3213       .accessfn = gt_ptimer_access,
3214       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3215     },
3216     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3217       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3218       .access = PL0_RW,
3219       .type = ARM_CP_IO,
3220       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3221       .resetvalue = 0, .accessfn = gt_ptimer_access,
3222       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3223       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3224     },
3225     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3226       .access = PL0_RW,
3227       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3228       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3229       .accessfn = gt_vtimer_access,
3230       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3231       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3232     },
3233     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3234       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3235       .access = PL0_RW,
3236       .type = ARM_CP_IO,
3237       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3238       .resetvalue = 0, .accessfn = gt_vtimer_access,
3239       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3240       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3241     },
3242     /* Secure timer -- this is actually restricted to only EL3
3243      * and configurably Secure-EL1 via the accessfn.
3244      */
3245     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3246       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3247       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3248       .accessfn = gt_stimer_access,
3249       .readfn = gt_sec_tval_read,
3250       .writefn = gt_sec_tval_write,
3251       .resetfn = gt_sec_timer_reset,
3252     },
3253     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3254       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3255       .type = ARM_CP_IO, .access = PL1_RW,
3256       .accessfn = gt_stimer_access,
3257       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3258       .resetvalue = 0,
3259       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3260     },
3261     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3262       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3263       .type = ARM_CP_IO, .access = PL1_RW,
3264       .accessfn = gt_stimer_access,
3265       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3266       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3267     },
3268     REGINFO_SENTINEL
3269 };
3270 
3271 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3272                                  bool isread)
3273 {
3274     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3275         return CP_ACCESS_TRAP;
3276     }
3277     return CP_ACCESS_OK;
3278 }
3279 
3280 #else
3281 
3282 /* In user-mode most of the generic timer registers are inaccessible
3283  * however modern kernels (4.12+) allow access to cntvct_el0
3284  */
3285 
3286 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3287 {
3288     ARMCPU *cpu = env_archcpu(env);
3289 
3290     /* Currently we have no support for QEMUTimer in linux-user so we
3291      * can't call gt_get_countervalue(env), instead we directly
3292      * call the lower level functions.
3293      */
3294     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3295 }
3296 
3297 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3298     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3299       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3300       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3301       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3302       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3303     },
3304     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3305       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3306       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3307       .readfn = gt_virt_cnt_read,
3308     },
3309     REGINFO_SENTINEL
3310 };
3311 
3312 #endif
3313 
3314 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3315 {
3316     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3317         raw_write(env, ri, value);
3318     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3319         raw_write(env, ri, value & 0xfffff6ff);
3320     } else {
3321         raw_write(env, ri, value & 0xfffff1ff);
3322     }
3323 }
3324 
3325 #ifndef CONFIG_USER_ONLY
3326 /* get_phys_addr() isn't present for user-mode-only targets */
3327 
3328 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3329                                  bool isread)
3330 {
3331     if (ri->opc2 & 4) {
3332         /* The ATS12NSO* operations must trap to EL3 if executed in
3333          * Secure EL1 (which can only happen if EL3 is AArch64).
3334          * They are simply UNDEF if executed from NS EL1.
3335          * They function normally from EL2 or EL3.
3336          */
3337         if (arm_current_el(env) == 1) {
3338             if (arm_is_secure_below_el3(env)) {
3339                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3340             }
3341             return CP_ACCESS_TRAP_UNCATEGORIZED;
3342         }
3343     }
3344     return CP_ACCESS_OK;
3345 }
3346 
3347 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3348                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3349 {
3350     hwaddr phys_addr;
3351     target_ulong page_size;
3352     int prot;
3353     bool ret;
3354     uint64_t par64;
3355     bool format64 = false;
3356     MemTxAttrs attrs = {};
3357     ARMMMUFaultInfo fi = {};
3358     ARMCacheAttrs cacheattrs = {};
3359 
3360     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3361                         &prot, &page_size, &fi, &cacheattrs);
3362 
3363     if (ret) {
3364         /*
3365          * Some kinds of translation fault must cause exceptions rather
3366          * than being reported in the PAR.
3367          */
3368         int current_el = arm_current_el(env);
3369         int target_el;
3370         uint32_t syn, fsr, fsc;
3371         bool take_exc = false;
3372 
3373         if (fi.s1ptw && current_el == 1 && !arm_is_secure(env)
3374             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3375             /*
3376              * Synchronous stage 2 fault on an access made as part of the
3377              * translation table walk for AT S1E0* or AT S1E1* insn
3378              * executed from NS EL1. If this is a synchronous external abort
3379              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3380              * to EL3. Otherwise the fault is taken as an exception to EL2,
3381              * and HPFAR_EL2 holds the faulting IPA.
3382              */
3383             if (fi.type == ARMFault_SyncExternalOnWalk &&
3384                 (env->cp15.scr_el3 & SCR_EA)) {
3385                 target_el = 3;
3386             } else {
3387                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3388                 target_el = 2;
3389             }
3390             take_exc = true;
3391         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3392             /*
3393              * Synchronous external aborts during a translation table walk
3394              * are taken as Data Abort exceptions.
3395              */
3396             if (fi.stage2) {
3397                 if (current_el == 3) {
3398                     target_el = 3;
3399                 } else {
3400                     target_el = 2;
3401                 }
3402             } else {
3403                 target_el = exception_target_el(env);
3404             }
3405             take_exc = true;
3406         }
3407 
3408         if (take_exc) {
3409             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3410             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3411                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3412                 fsr = arm_fi_to_lfsc(&fi);
3413                 fsc = extract32(fsr, 0, 6);
3414             } else {
3415                 fsr = arm_fi_to_sfsc(&fi);
3416                 fsc = 0x3f;
3417             }
3418             /*
3419              * Report exception with ESR indicating a fault due to a
3420              * translation table walk for a cache maintenance instruction.
3421              */
3422             syn = syn_data_abort_no_iss(current_el == target_el,
3423                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3424             env->exception.vaddress = value;
3425             env->exception.fsr = fsr;
3426             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3427         }
3428     }
3429 
3430     if (is_a64(env)) {
3431         format64 = true;
3432     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3433         /*
3434          * ATS1Cxx:
3435          * * TTBCR.EAE determines whether the result is returned using the
3436          *   32-bit or the 64-bit PAR format
3437          * * Instructions executed in Hyp mode always use the 64bit format
3438          *
3439          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3440          * * The Non-secure TTBCR.EAE bit is set to 1
3441          * * The implementation includes EL2, and the value of HCR.VM is 1
3442          *
3443          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3444          *
3445          * ATS1Hx always uses the 64bit format.
3446          */
3447         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3448 
3449         if (arm_feature(env, ARM_FEATURE_EL2)) {
3450             if (mmu_idx == ARMMMUIdx_E10_0 ||
3451                 mmu_idx == ARMMMUIdx_E10_1 ||
3452                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3453                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3454             } else {
3455                 format64 |= arm_current_el(env) == 2;
3456             }
3457         }
3458     }
3459 
3460     if (format64) {
3461         /* Create a 64-bit PAR */
3462         par64 = (1 << 11); /* LPAE bit always set */
3463         if (!ret) {
3464             par64 |= phys_addr & ~0xfffULL;
3465             if (!attrs.secure) {
3466                 par64 |= (1 << 9); /* NS */
3467             }
3468             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3469             par64 |= cacheattrs.shareability << 7; /* SH */
3470         } else {
3471             uint32_t fsr = arm_fi_to_lfsc(&fi);
3472 
3473             par64 |= 1; /* F */
3474             par64 |= (fsr & 0x3f) << 1; /* FS */
3475             if (fi.stage2) {
3476                 par64 |= (1 << 9); /* S */
3477             }
3478             if (fi.s1ptw) {
3479                 par64 |= (1 << 8); /* PTW */
3480             }
3481         }
3482     } else {
3483         /* fsr is a DFSR/IFSR value for the short descriptor
3484          * translation table format (with WnR always clear).
3485          * Convert it to a 32-bit PAR.
3486          */
3487         if (!ret) {
3488             /* We do not set any attribute bits in the PAR */
3489             if (page_size == (1 << 24)
3490                 && arm_feature(env, ARM_FEATURE_V7)) {
3491                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3492             } else {
3493                 par64 = phys_addr & 0xfffff000;
3494             }
3495             if (!attrs.secure) {
3496                 par64 |= (1 << 9); /* NS */
3497             }
3498         } else {
3499             uint32_t fsr = arm_fi_to_sfsc(&fi);
3500 
3501             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3502                     ((fsr & 0xf) << 1) | 1;
3503         }
3504     }
3505     return par64;
3506 }
3507 
3508 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3509 {
3510     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3511     uint64_t par64;
3512     ARMMMUIdx mmu_idx;
3513     int el = arm_current_el(env);
3514     bool secure = arm_is_secure_below_el3(env);
3515 
3516     switch (ri->opc2 & 6) {
3517     case 0:
3518         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3519         switch (el) {
3520         case 3:
3521             mmu_idx = ARMMMUIdx_SE3;
3522             break;
3523         case 2:
3524             g_assert(!secure);  /* TODO: ARMv8.4-SecEL2 */
3525             /* fall through */
3526         case 1:
3527             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3528                 mmu_idx = (secure ? ARMMMUIdx_SE10_1_PAN
3529                            : ARMMMUIdx_Stage1_E1_PAN);
3530             } else {
3531                 mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_Stage1_E1;
3532             }
3533             break;
3534         default:
3535             g_assert_not_reached();
3536         }
3537         break;
3538     case 2:
3539         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3540         switch (el) {
3541         case 3:
3542             mmu_idx = ARMMMUIdx_SE10_0;
3543             break;
3544         case 2:
3545             mmu_idx = ARMMMUIdx_Stage1_E0;
3546             break;
3547         case 1:
3548             mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_Stage1_E0;
3549             break;
3550         default:
3551             g_assert_not_reached();
3552         }
3553         break;
3554     case 4:
3555         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3556         mmu_idx = ARMMMUIdx_E10_1;
3557         break;
3558     case 6:
3559         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3560         mmu_idx = ARMMMUIdx_E10_0;
3561         break;
3562     default:
3563         g_assert_not_reached();
3564     }
3565 
3566     par64 = do_ats_write(env, value, access_type, mmu_idx);
3567 
3568     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3569 }
3570 
3571 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3572                         uint64_t value)
3573 {
3574     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3575     uint64_t par64;
3576 
3577     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3578 
3579     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3580 }
3581 
3582 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3583                                      bool isread)
3584 {
3585     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
3586         return CP_ACCESS_TRAP;
3587     }
3588     return CP_ACCESS_OK;
3589 }
3590 
3591 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3592                         uint64_t value)
3593 {
3594     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3595     ARMMMUIdx mmu_idx;
3596     int secure = arm_is_secure_below_el3(env);
3597 
3598     switch (ri->opc2 & 6) {
3599     case 0:
3600         switch (ri->opc1) {
3601         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3602             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3603                 mmu_idx = (secure ? ARMMMUIdx_SE10_1_PAN
3604                            : ARMMMUIdx_Stage1_E1_PAN);
3605             } else {
3606                 mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_Stage1_E1;
3607             }
3608             break;
3609         case 4: /* AT S1E2R, AT S1E2W */
3610             mmu_idx = ARMMMUIdx_E2;
3611             break;
3612         case 6: /* AT S1E3R, AT S1E3W */
3613             mmu_idx = ARMMMUIdx_SE3;
3614             break;
3615         default:
3616             g_assert_not_reached();
3617         }
3618         break;
3619     case 2: /* AT S1E0R, AT S1E0W */
3620         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_Stage1_E0;
3621         break;
3622     case 4: /* AT S12E1R, AT S12E1W */
3623         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3624         break;
3625     case 6: /* AT S12E0R, AT S12E0W */
3626         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3627         break;
3628     default:
3629         g_assert_not_reached();
3630     }
3631 
3632     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3633 }
3634 #endif
3635 
3636 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3637     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3638       .access = PL1_RW, .resetvalue = 0,
3639       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3640                              offsetoflow32(CPUARMState, cp15.par_ns) },
3641       .writefn = par_write },
3642 #ifndef CONFIG_USER_ONLY
3643     /* This underdecoding is safe because the reginfo is NO_RAW. */
3644     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3645       .access = PL1_W, .accessfn = ats_access,
3646       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3647 #endif
3648     REGINFO_SENTINEL
3649 };
3650 
3651 /* Return basic MPU access permission bits.  */
3652 static uint32_t simple_mpu_ap_bits(uint32_t val)
3653 {
3654     uint32_t ret;
3655     uint32_t mask;
3656     int i;
3657     ret = 0;
3658     mask = 3;
3659     for (i = 0; i < 16; i += 2) {
3660         ret |= (val >> i) & mask;
3661         mask <<= 2;
3662     }
3663     return ret;
3664 }
3665 
3666 /* Pad basic MPU access permission bits to extended format.  */
3667 static uint32_t extended_mpu_ap_bits(uint32_t val)
3668 {
3669     uint32_t ret;
3670     uint32_t mask;
3671     int i;
3672     ret = 0;
3673     mask = 3;
3674     for (i = 0; i < 16; i += 2) {
3675         ret |= (val & mask) << i;
3676         mask <<= 2;
3677     }
3678     return ret;
3679 }
3680 
3681 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3682                                  uint64_t value)
3683 {
3684     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3685 }
3686 
3687 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3688 {
3689     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3690 }
3691 
3692 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3693                                  uint64_t value)
3694 {
3695     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3696 }
3697 
3698 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3699 {
3700     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3701 }
3702 
3703 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3704 {
3705     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3706 
3707     if (!u32p) {
3708         return 0;
3709     }
3710 
3711     u32p += env->pmsav7.rnr[M_REG_NS];
3712     return *u32p;
3713 }
3714 
3715 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3716                          uint64_t value)
3717 {
3718     ARMCPU *cpu = env_archcpu(env);
3719     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3720 
3721     if (!u32p) {
3722         return;
3723     }
3724 
3725     u32p += env->pmsav7.rnr[M_REG_NS];
3726     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3727     *u32p = value;
3728 }
3729 
3730 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3731                               uint64_t value)
3732 {
3733     ARMCPU *cpu = env_archcpu(env);
3734     uint32_t nrgs = cpu->pmsav7_dregion;
3735 
3736     if (value >= nrgs) {
3737         qemu_log_mask(LOG_GUEST_ERROR,
3738                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3739                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3740         return;
3741     }
3742 
3743     raw_write(env, ri, value);
3744 }
3745 
3746 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3747     /* Reset for all these registers is handled in arm_cpu_reset(),
3748      * because the PMSAv7 is also used by M-profile CPUs, which do
3749      * not register cpregs but still need the state to be reset.
3750      */
3751     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3752       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3753       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3754       .readfn = pmsav7_read, .writefn = pmsav7_write,
3755       .resetfn = arm_cp_reset_ignore },
3756     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3757       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3758       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3759       .readfn = pmsav7_read, .writefn = pmsav7_write,
3760       .resetfn = arm_cp_reset_ignore },
3761     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3762       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3763       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3764       .readfn = pmsav7_read, .writefn = pmsav7_write,
3765       .resetfn = arm_cp_reset_ignore },
3766     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3767       .access = PL1_RW,
3768       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3769       .writefn = pmsav7_rgnr_write,
3770       .resetfn = arm_cp_reset_ignore },
3771     REGINFO_SENTINEL
3772 };
3773 
3774 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3775     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3776       .access = PL1_RW, .type = ARM_CP_ALIAS,
3777       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3778       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3779     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3780       .access = PL1_RW, .type = ARM_CP_ALIAS,
3781       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3782       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3783     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3784       .access = PL1_RW,
3785       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3786       .resetvalue = 0, },
3787     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3788       .access = PL1_RW,
3789       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3790       .resetvalue = 0, },
3791     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3792       .access = PL1_RW,
3793       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3794     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3795       .access = PL1_RW,
3796       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3797     /* Protection region base and size registers */
3798     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3799       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3800       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3801     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3802       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3803       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3804     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3805       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3806       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3807     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3808       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3809       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3810     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3811       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3812       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3813     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3814       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3815       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3816     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3817       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3818       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3819     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3820       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3821       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3822     REGINFO_SENTINEL
3823 };
3824 
3825 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3826                                  uint64_t value)
3827 {
3828     TCR *tcr = raw_ptr(env, ri);
3829     int maskshift = extract32(value, 0, 3);
3830 
3831     if (!arm_feature(env, ARM_FEATURE_V8)) {
3832         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3833             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3834              * using Long-desciptor translation table format */
3835             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3836         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3837             /* In an implementation that includes the Security Extensions
3838              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3839              * Short-descriptor translation table format.
3840              */
3841             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3842         } else {
3843             value &= TTBCR_N;
3844         }
3845     }
3846 
3847     /* Update the masks corresponding to the TCR bank being written
3848      * Note that we always calculate mask and base_mask, but
3849      * they are only used for short-descriptor tables (ie if EAE is 0);
3850      * for long-descriptor tables the TCR fields are used differently
3851      * and the mask and base_mask values are meaningless.
3852      */
3853     tcr->raw_tcr = value;
3854     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3855     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3856 }
3857 
3858 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3859                              uint64_t value)
3860 {
3861     ARMCPU *cpu = env_archcpu(env);
3862     TCR *tcr = raw_ptr(env, ri);
3863 
3864     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3865         /* With LPAE the TTBCR could result in a change of ASID
3866          * via the TTBCR.A1 bit, so do a TLB flush.
3867          */
3868         tlb_flush(CPU(cpu));
3869     }
3870     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3871     value = deposit64(tcr->raw_tcr, 0, 32, value);
3872     vmsa_ttbcr_raw_write(env, ri, value);
3873 }
3874 
3875 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3876 {
3877     TCR *tcr = raw_ptr(env, ri);
3878 
3879     /* Reset both the TCR as well as the masks corresponding to the bank of
3880      * the TCR being reset.
3881      */
3882     tcr->raw_tcr = 0;
3883     tcr->mask = 0;
3884     tcr->base_mask = 0xffffc000u;
3885 }
3886 
3887 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3888                                uint64_t value)
3889 {
3890     ARMCPU *cpu = env_archcpu(env);
3891     TCR *tcr = raw_ptr(env, ri);
3892 
3893     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3894     tlb_flush(CPU(cpu));
3895     tcr->raw_tcr = value;
3896 }
3897 
3898 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3899                             uint64_t value)
3900 {
3901     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3902     if (cpreg_field_is_64bit(ri) &&
3903         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3904         ARMCPU *cpu = env_archcpu(env);
3905         tlb_flush(CPU(cpu));
3906     }
3907     raw_write(env, ri, value);
3908 }
3909 
3910 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3911                                     uint64_t value)
3912 {
3913     /*
3914      * If we are running with E2&0 regime, then an ASID is active.
3915      * Flush if that might be changing.  Note we're not checking
3916      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
3917      * holds the active ASID, only checking the field that might.
3918      */
3919     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
3920         (arm_hcr_el2_eff(env) & HCR_E2H)) {
3921         tlb_flush_by_mmuidx(env_cpu(env),
3922                             ARMMMUIdxBit_E20_2 |
3923                             ARMMMUIdxBit_E20_2_PAN |
3924                             ARMMMUIdxBit_E20_0);
3925     }
3926     raw_write(env, ri, value);
3927 }
3928 
3929 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3930                         uint64_t value)
3931 {
3932     ARMCPU *cpu = env_archcpu(env);
3933     CPUState *cs = CPU(cpu);
3934 
3935     /*
3936      * A change in VMID to the stage2 page table (Stage2) invalidates
3937      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
3938      */
3939     if (raw_read(env, ri) != value) {
3940         tlb_flush_by_mmuidx(cs,
3941                             ARMMMUIdxBit_E10_1 |
3942                             ARMMMUIdxBit_E10_1_PAN |
3943                             ARMMMUIdxBit_E10_0 |
3944                             ARMMMUIdxBit_Stage2);
3945         raw_write(env, ri, value);
3946     }
3947 }
3948 
3949 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
3950     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3951       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
3952       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
3953                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
3954     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3955       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3956       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
3957                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
3958     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
3959       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
3960       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
3961                              offsetof(CPUARMState, cp15.dfar_ns) } },
3962     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
3963       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
3964       .access = PL1_RW, .accessfn = access_tvm_trvm,
3965       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
3966       .resetvalue = 0, },
3967     REGINFO_SENTINEL
3968 };
3969 
3970 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
3971     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
3972       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
3973       .access = PL1_RW, .accessfn = access_tvm_trvm,
3974       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
3975     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
3976       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
3977       .access = PL1_RW, .accessfn = access_tvm_trvm,
3978       .writefn = vmsa_ttbr_write, .resetvalue = 0,
3979       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
3980                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
3981     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
3982       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
3983       .access = PL1_RW, .accessfn = access_tvm_trvm,
3984       .writefn = vmsa_ttbr_write, .resetvalue = 0,
3985       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
3986                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
3987     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
3988       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3989       .access = PL1_RW, .accessfn = access_tvm_trvm,
3990       .writefn = vmsa_tcr_el12_write,
3991       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
3992       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
3993     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
3994       .access = PL1_RW, .accessfn = access_tvm_trvm,
3995       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
3996       .raw_writefn = vmsa_ttbcr_raw_write,
3997       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
3998                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
3999     REGINFO_SENTINEL
4000 };
4001 
4002 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
4003  * qemu tlbs nor adjusting cached masks.
4004  */
4005 static const ARMCPRegInfo ttbcr2_reginfo = {
4006     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
4007     .access = PL1_RW, .accessfn = access_tvm_trvm,
4008     .type = ARM_CP_ALIAS,
4009     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
4010                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
4011 };
4012 
4013 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
4014                                 uint64_t value)
4015 {
4016     env->cp15.c15_ticonfig = value & 0xe7;
4017     /* The OS_TYPE bit in this register changes the reported CPUID! */
4018     env->cp15.c0_cpuid = (value & (1 << 5)) ?
4019         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
4020 }
4021 
4022 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
4023                                 uint64_t value)
4024 {
4025     env->cp15.c15_threadid = value & 0xffff;
4026 }
4027 
4028 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
4029                            uint64_t value)
4030 {
4031     /* Wait-for-interrupt (deprecated) */
4032     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
4033 }
4034 
4035 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
4036                                   uint64_t value)
4037 {
4038     /* On OMAP there are registers indicating the max/min index of dcache lines
4039      * containing a dirty line; cache flush operations have to reset these.
4040      */
4041     env->cp15.c15_i_max = 0x000;
4042     env->cp15.c15_i_min = 0xff0;
4043 }
4044 
4045 static const ARMCPRegInfo omap_cp_reginfo[] = {
4046     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
4047       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
4048       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
4049       .resetvalue = 0, },
4050     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
4051       .access = PL1_RW, .type = ARM_CP_NOP },
4052     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
4053       .access = PL1_RW,
4054       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
4055       .writefn = omap_ticonfig_write },
4056     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
4057       .access = PL1_RW,
4058       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
4059     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
4060       .access = PL1_RW, .resetvalue = 0xff0,
4061       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
4062     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
4063       .access = PL1_RW,
4064       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
4065       .writefn = omap_threadid_write },
4066     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
4067       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4068       .type = ARM_CP_NO_RAW,
4069       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
4070     /* TODO: Peripheral port remap register:
4071      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
4072      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
4073      * when MMU is off.
4074      */
4075     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
4076       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
4077       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
4078       .writefn = omap_cachemaint_write },
4079     { .name = "C9", .cp = 15, .crn = 9,
4080       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
4081       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
4082     REGINFO_SENTINEL
4083 };
4084 
4085 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4086                               uint64_t value)
4087 {
4088     env->cp15.c15_cpar = value & 0x3fff;
4089 }
4090 
4091 static const ARMCPRegInfo xscale_cp_reginfo[] = {
4092     { .name = "XSCALE_CPAR",
4093       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4094       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
4095       .writefn = xscale_cpar_write, },
4096     { .name = "XSCALE_AUXCR",
4097       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
4098       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
4099       .resetvalue = 0, },
4100     /* XScale specific cache-lockdown: since we have no cache we NOP these
4101      * and hope the guest does not really rely on cache behaviour.
4102      */
4103     { .name = "XSCALE_LOCK_ICACHE_LINE",
4104       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
4105       .access = PL1_W, .type = ARM_CP_NOP },
4106     { .name = "XSCALE_UNLOCK_ICACHE",
4107       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
4108       .access = PL1_W, .type = ARM_CP_NOP },
4109     { .name = "XSCALE_DCACHE_LOCK",
4110       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
4111       .access = PL1_RW, .type = ARM_CP_NOP },
4112     { .name = "XSCALE_UNLOCK_DCACHE",
4113       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
4114       .access = PL1_W, .type = ARM_CP_NOP },
4115     REGINFO_SENTINEL
4116 };
4117 
4118 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
4119     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
4120      * implementation of this implementation-defined space.
4121      * Ideally this should eventually disappear in favour of actually
4122      * implementing the correct behaviour for all cores.
4123      */
4124     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
4125       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4126       .access = PL1_RW,
4127       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
4128       .resetvalue = 0 },
4129     REGINFO_SENTINEL
4130 };
4131 
4132 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
4133     /* Cache status: RAZ because we have no cache so it's always clean */
4134     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
4135       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4136       .resetvalue = 0 },
4137     REGINFO_SENTINEL
4138 };
4139 
4140 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
4141     /* We never have a a block transfer operation in progress */
4142     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
4143       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4144       .resetvalue = 0 },
4145     /* The cache ops themselves: these all NOP for QEMU */
4146     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
4147       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4148     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
4149       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4150     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
4151       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4152     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4153       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4154     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4155       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4156     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4157       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4158     REGINFO_SENTINEL
4159 };
4160 
4161 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4162     /* The cache test-and-clean instructions always return (1 << 30)
4163      * to indicate that there are no dirty cache lines.
4164      */
4165     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4166       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4167       .resetvalue = (1 << 30) },
4168     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4169       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4170       .resetvalue = (1 << 30) },
4171     REGINFO_SENTINEL
4172 };
4173 
4174 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4175     /* Ignore ReadBuffer accesses */
4176     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4177       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4178       .access = PL1_RW, .resetvalue = 0,
4179       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4180     REGINFO_SENTINEL
4181 };
4182 
4183 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4184 {
4185     ARMCPU *cpu = env_archcpu(env);
4186     unsigned int cur_el = arm_current_el(env);
4187     bool secure = arm_is_secure(env);
4188 
4189     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
4190         return env->cp15.vpidr_el2;
4191     }
4192     return raw_read(env, ri);
4193 }
4194 
4195 static uint64_t mpidr_read_val(CPUARMState *env)
4196 {
4197     ARMCPU *cpu = env_archcpu(env);
4198     uint64_t mpidr = cpu->mp_affinity;
4199 
4200     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4201         mpidr |= (1U << 31);
4202         /* Cores which are uniprocessor (non-coherent)
4203          * but still implement the MP extensions set
4204          * bit 30. (For instance, Cortex-R5).
4205          */
4206         if (cpu->mp_is_up) {
4207             mpidr |= (1u << 30);
4208         }
4209     }
4210     return mpidr;
4211 }
4212 
4213 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4214 {
4215     unsigned int cur_el = arm_current_el(env);
4216     bool secure = arm_is_secure(env);
4217 
4218     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
4219         return env->cp15.vmpidr_el2;
4220     }
4221     return mpidr_read_val(env);
4222 }
4223 
4224 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4225     /* NOP AMAIR0/1 */
4226     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4227       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4228       .access = PL1_RW, .accessfn = access_tvm_trvm,
4229       .type = ARM_CP_CONST, .resetvalue = 0 },
4230     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4231     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4232       .access = PL1_RW, .accessfn = access_tvm_trvm,
4233       .type = ARM_CP_CONST, .resetvalue = 0 },
4234     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4235       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4236       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4237                              offsetof(CPUARMState, cp15.par_ns)} },
4238     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4239       .access = PL1_RW, .accessfn = access_tvm_trvm,
4240       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4241       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4242                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4243       .writefn = vmsa_ttbr_write, },
4244     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4245       .access = PL1_RW, .accessfn = access_tvm_trvm,
4246       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4247       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4248                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4249       .writefn = vmsa_ttbr_write, },
4250     REGINFO_SENTINEL
4251 };
4252 
4253 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4254 {
4255     return vfp_get_fpcr(env);
4256 }
4257 
4258 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4259                             uint64_t value)
4260 {
4261     vfp_set_fpcr(env, value);
4262 }
4263 
4264 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4265 {
4266     return vfp_get_fpsr(env);
4267 }
4268 
4269 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4270                             uint64_t value)
4271 {
4272     vfp_set_fpsr(env, value);
4273 }
4274 
4275 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4276                                        bool isread)
4277 {
4278     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4279         return CP_ACCESS_TRAP;
4280     }
4281     return CP_ACCESS_OK;
4282 }
4283 
4284 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4285                             uint64_t value)
4286 {
4287     env->daif = value & PSTATE_DAIF;
4288 }
4289 
4290 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4291 {
4292     return env->pstate & PSTATE_PAN;
4293 }
4294 
4295 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4296                            uint64_t value)
4297 {
4298     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4299 }
4300 
4301 static const ARMCPRegInfo pan_reginfo = {
4302     .name = "PAN", .state = ARM_CP_STATE_AA64,
4303     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4304     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4305     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4306 };
4307 
4308 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4309 {
4310     return env->pstate & PSTATE_UAO;
4311 }
4312 
4313 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4314                            uint64_t value)
4315 {
4316     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4317 }
4318 
4319 static const ARMCPRegInfo uao_reginfo = {
4320     .name = "UAO", .state = ARM_CP_STATE_AA64,
4321     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4322     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4323     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4324 };
4325 
4326 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4327                                               const ARMCPRegInfo *ri,
4328                                               bool isread)
4329 {
4330     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4331     switch (arm_current_el(env)) {
4332     case 0:
4333         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4334         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4335             return CP_ACCESS_TRAP;
4336         }
4337         /* fall through */
4338     case 1:
4339         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4340         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4341             return CP_ACCESS_TRAP_EL2;
4342         }
4343         break;
4344     }
4345     return CP_ACCESS_OK;
4346 }
4347 
4348 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4349                                               const ARMCPRegInfo *ri,
4350                                               bool isread)
4351 {
4352     /* Cache invalidate/clean to Point of Unification... */
4353     switch (arm_current_el(env)) {
4354     case 0:
4355         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4356         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4357             return CP_ACCESS_TRAP;
4358         }
4359         /* fall through */
4360     case 1:
4361         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4362         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4363             return CP_ACCESS_TRAP_EL2;
4364         }
4365         break;
4366     }
4367     return CP_ACCESS_OK;
4368 }
4369 
4370 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4371  * Page D4-1736 (DDI0487A.b)
4372  */
4373 
4374 static int vae1_tlbmask(CPUARMState *env)
4375 {
4376     /* Since we exclude secure first, we may read HCR_EL2 directly. */
4377     if (arm_is_secure_below_el3(env)) {
4378         return ARMMMUIdxBit_SE10_1 |
4379                ARMMMUIdxBit_SE10_1_PAN |
4380                ARMMMUIdxBit_SE10_0;
4381     } else if ((env->cp15.hcr_el2 & (HCR_E2H | HCR_TGE))
4382                == (HCR_E2H | HCR_TGE)) {
4383         return ARMMMUIdxBit_E20_2 |
4384                ARMMMUIdxBit_E20_2_PAN |
4385                ARMMMUIdxBit_E20_0;
4386     } else {
4387         return ARMMMUIdxBit_E10_1 |
4388                ARMMMUIdxBit_E10_1_PAN |
4389                ARMMMUIdxBit_E10_0;
4390     }
4391 }
4392 
4393 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4394                                       uint64_t value)
4395 {
4396     CPUState *cs = env_cpu(env);
4397     int mask = vae1_tlbmask(env);
4398 
4399     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4400 }
4401 
4402 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4403                                     uint64_t value)
4404 {
4405     CPUState *cs = env_cpu(env);
4406     int mask = vae1_tlbmask(env);
4407 
4408     if (tlb_force_broadcast(env)) {
4409         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4410     } else {
4411         tlb_flush_by_mmuidx(cs, mask);
4412     }
4413 }
4414 
4415 static int alle1_tlbmask(CPUARMState *env)
4416 {
4417     /*
4418      * Note that the 'ALL' scope must invalidate both stage 1 and
4419      * stage 2 translations, whereas most other scopes only invalidate
4420      * stage 1 translations.
4421      */
4422     if (arm_is_secure_below_el3(env)) {
4423         return ARMMMUIdxBit_SE10_1 |
4424                ARMMMUIdxBit_SE10_1_PAN |
4425                ARMMMUIdxBit_SE10_0;
4426     } else if (arm_feature(env, ARM_FEATURE_EL2)) {
4427         return ARMMMUIdxBit_E10_1 |
4428                ARMMMUIdxBit_E10_1_PAN |
4429                ARMMMUIdxBit_E10_0 |
4430                ARMMMUIdxBit_Stage2;
4431     } else {
4432         return ARMMMUIdxBit_E10_1 |
4433                ARMMMUIdxBit_E10_1_PAN |
4434                ARMMMUIdxBit_E10_0;
4435     }
4436 }
4437 
4438 static int e2_tlbmask(CPUARMState *env)
4439 {
4440     /* TODO: ARMv8.4-SecEL2 */
4441     return ARMMMUIdxBit_E20_0 |
4442            ARMMMUIdxBit_E20_2 |
4443            ARMMMUIdxBit_E20_2_PAN |
4444            ARMMMUIdxBit_E2;
4445 }
4446 
4447 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4448                                   uint64_t value)
4449 {
4450     CPUState *cs = env_cpu(env);
4451     int mask = alle1_tlbmask(env);
4452 
4453     tlb_flush_by_mmuidx(cs, mask);
4454 }
4455 
4456 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4457                                   uint64_t value)
4458 {
4459     CPUState *cs = env_cpu(env);
4460     int mask = e2_tlbmask(env);
4461 
4462     tlb_flush_by_mmuidx(cs, mask);
4463 }
4464 
4465 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4466                                   uint64_t value)
4467 {
4468     ARMCPU *cpu = env_archcpu(env);
4469     CPUState *cs = CPU(cpu);
4470 
4471     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4472 }
4473 
4474 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4475                                     uint64_t value)
4476 {
4477     CPUState *cs = env_cpu(env);
4478     int mask = alle1_tlbmask(env);
4479 
4480     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4481 }
4482 
4483 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4484                                     uint64_t value)
4485 {
4486     CPUState *cs = env_cpu(env);
4487     int mask = e2_tlbmask(env);
4488 
4489     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4490 }
4491 
4492 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4493                                     uint64_t value)
4494 {
4495     CPUState *cs = env_cpu(env);
4496 
4497     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4498 }
4499 
4500 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4501                                  uint64_t value)
4502 {
4503     /* Invalidate by VA, EL2
4504      * Currently handles both VAE2 and VALE2, since we don't support
4505      * flush-last-level-only.
4506      */
4507     CPUState *cs = env_cpu(env);
4508     int mask = e2_tlbmask(env);
4509     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4510 
4511     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4512 }
4513 
4514 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4515                                  uint64_t value)
4516 {
4517     /* Invalidate by VA, EL3
4518      * Currently handles both VAE3 and VALE3, since we don't support
4519      * flush-last-level-only.
4520      */
4521     ARMCPU *cpu = env_archcpu(env);
4522     CPUState *cs = CPU(cpu);
4523     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4524 
4525     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4526 }
4527 
4528 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4529                                    uint64_t value)
4530 {
4531     CPUState *cs = env_cpu(env);
4532     int mask = vae1_tlbmask(env);
4533     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4534 
4535     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr, mask);
4536 }
4537 
4538 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4539                                  uint64_t value)
4540 {
4541     /* Invalidate by VA, EL1&0 (AArch64 version).
4542      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4543      * since we don't support flush-for-specific-ASID-only or
4544      * flush-last-level-only.
4545      */
4546     CPUState *cs = env_cpu(env);
4547     int mask = vae1_tlbmask(env);
4548     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4549 
4550     if (tlb_force_broadcast(env)) {
4551         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr, mask);
4552     } else {
4553         tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4554     }
4555 }
4556 
4557 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4558                                    uint64_t value)
4559 {
4560     CPUState *cs = env_cpu(env);
4561     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4562 
4563     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4564                                              ARMMMUIdxBit_E2);
4565 }
4566 
4567 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4568                                    uint64_t value)
4569 {
4570     CPUState *cs = env_cpu(env);
4571     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4572 
4573     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4574                                              ARMMMUIdxBit_SE3);
4575 }
4576 
4577 static void tlbi_aa64_ipas2e1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4578                                     uint64_t value)
4579 {
4580     /* Invalidate by IPA. This has to invalidate any structures that
4581      * contain only stage 2 translation information, but does not need
4582      * to apply to structures that contain combined stage 1 and stage 2
4583      * translation information.
4584      * This must NOP if EL2 isn't implemented or SCR_EL3.NS is zero.
4585      */
4586     ARMCPU *cpu = env_archcpu(env);
4587     CPUState *cs = CPU(cpu);
4588     uint64_t pageaddr;
4589 
4590     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4591         return;
4592     }
4593 
4594     pageaddr = sextract64(value << 12, 0, 48);
4595 
4596     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_Stage2);
4597 }
4598 
4599 static void tlbi_aa64_ipas2e1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4600                                       uint64_t value)
4601 {
4602     CPUState *cs = env_cpu(env);
4603     uint64_t pageaddr;
4604 
4605     if (!arm_feature(env, ARM_FEATURE_EL2) || !(env->cp15.scr_el3 & SCR_NS)) {
4606         return;
4607     }
4608 
4609     pageaddr = sextract64(value << 12, 0, 48);
4610 
4611     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4612                                              ARMMMUIdxBit_Stage2);
4613 }
4614 
4615 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4616                                       bool isread)
4617 {
4618     int cur_el = arm_current_el(env);
4619 
4620     if (cur_el < 2) {
4621         uint64_t hcr = arm_hcr_el2_eff(env);
4622 
4623         if (cur_el == 0) {
4624             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4625                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4626                     return CP_ACCESS_TRAP_EL2;
4627                 }
4628             } else {
4629                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4630                     return CP_ACCESS_TRAP;
4631                 }
4632                 if (hcr & HCR_TDZ) {
4633                     return CP_ACCESS_TRAP_EL2;
4634                 }
4635             }
4636         } else if (hcr & HCR_TDZ) {
4637             return CP_ACCESS_TRAP_EL2;
4638         }
4639     }
4640     return CP_ACCESS_OK;
4641 }
4642 
4643 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4644 {
4645     ARMCPU *cpu = env_archcpu(env);
4646     int dzp_bit = 1 << 4;
4647 
4648     /* DZP indicates whether DC ZVA access is allowed */
4649     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4650         dzp_bit = 0;
4651     }
4652     return cpu->dcz_blocksize | dzp_bit;
4653 }
4654 
4655 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4656                                     bool isread)
4657 {
4658     if (!(env->pstate & PSTATE_SP)) {
4659         /* Access to SP_EL0 is undefined if it's being used as
4660          * the stack pointer.
4661          */
4662         return CP_ACCESS_TRAP_UNCATEGORIZED;
4663     }
4664     return CP_ACCESS_OK;
4665 }
4666 
4667 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4668 {
4669     return env->pstate & PSTATE_SP;
4670 }
4671 
4672 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4673 {
4674     update_spsel(env, val);
4675 }
4676 
4677 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4678                         uint64_t value)
4679 {
4680     ARMCPU *cpu = env_archcpu(env);
4681 
4682     if (raw_read(env, ri) == value) {
4683         /* Skip the TLB flush if nothing actually changed; Linux likes
4684          * to do a lot of pointless SCTLR writes.
4685          */
4686         return;
4687     }
4688 
4689     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4690         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4691         value &= ~SCTLR_M;
4692     }
4693 
4694     raw_write(env, ri, value);
4695     /* ??? Lots of these bits are not implemented.  */
4696     /* This may enable/disable the MMU, so do a TLB flush.  */
4697     tlb_flush(CPU(cpu));
4698 
4699     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4700         /*
4701          * Normally we would always end the TB on an SCTLR write; see the
4702          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4703          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4704          * of hflags from the translator, so do it here.
4705          */
4706         arm_rebuild_hflags(env);
4707     }
4708 }
4709 
4710 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4711                                      bool isread)
4712 {
4713     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4714         return CP_ACCESS_TRAP_FP_EL2;
4715     }
4716     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4717         return CP_ACCESS_TRAP_FP_EL3;
4718     }
4719     return CP_ACCESS_OK;
4720 }
4721 
4722 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4723                        uint64_t value)
4724 {
4725     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4726 }
4727 
4728 static const ARMCPRegInfo v8_cp_reginfo[] = {
4729     /* Minimal set of EL0-visible registers. This will need to be expanded
4730      * significantly for system emulation of AArch64 CPUs.
4731      */
4732     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4733       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4734       .access = PL0_RW, .type = ARM_CP_NZCV },
4735     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4736       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4737       .type = ARM_CP_NO_RAW,
4738       .access = PL0_RW, .accessfn = aa64_daif_access,
4739       .fieldoffset = offsetof(CPUARMState, daif),
4740       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4741     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4742       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4743       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4744       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4745     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4746       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4747       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4748       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4749     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4750       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4751       .access = PL0_R, .type = ARM_CP_NO_RAW,
4752       .readfn = aa64_dczid_read },
4753     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4754       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4755       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4756 #ifndef CONFIG_USER_ONLY
4757       /* Avoid overhead of an access check that always passes in user-mode */
4758       .accessfn = aa64_zva_access,
4759 #endif
4760     },
4761     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4762       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4763       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4764     /* Cache ops: all NOPs since we don't emulate caches */
4765     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4766       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4767       .access = PL1_W, .type = ARM_CP_NOP,
4768       .accessfn = aa64_cacheop_pou_access },
4769     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4770       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4771       .access = PL1_W, .type = ARM_CP_NOP,
4772       .accessfn = aa64_cacheop_pou_access },
4773     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4774       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4775       .access = PL0_W, .type = ARM_CP_NOP,
4776       .accessfn = aa64_cacheop_pou_access },
4777     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4778       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4779       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4780       .type = ARM_CP_NOP },
4781     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4782       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4783       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4784     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4785       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4786       .access = PL0_W, .type = ARM_CP_NOP,
4787       .accessfn = aa64_cacheop_poc_access },
4788     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4789       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4790       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4791     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4792       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4793       .access = PL0_W, .type = ARM_CP_NOP,
4794       .accessfn = aa64_cacheop_pou_access },
4795     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4796       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4797       .access = PL0_W, .type = ARM_CP_NOP,
4798       .accessfn = aa64_cacheop_poc_access },
4799     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4800       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4801       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4802     /* TLBI operations */
4803     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4804       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4805       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4806       .writefn = tlbi_aa64_vmalle1is_write },
4807     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4808       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4809       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4810       .writefn = tlbi_aa64_vae1is_write },
4811     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4812       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4813       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4814       .writefn = tlbi_aa64_vmalle1is_write },
4815     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4816       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4817       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4818       .writefn = tlbi_aa64_vae1is_write },
4819     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4820       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4821       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4822       .writefn = tlbi_aa64_vae1is_write },
4823     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4824       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4825       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4826       .writefn = tlbi_aa64_vae1is_write },
4827     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4828       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4829       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4830       .writefn = tlbi_aa64_vmalle1_write },
4831     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4832       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4833       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4834       .writefn = tlbi_aa64_vae1_write },
4835     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4836       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4837       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4838       .writefn = tlbi_aa64_vmalle1_write },
4839     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4840       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4841       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4842       .writefn = tlbi_aa64_vae1_write },
4843     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4844       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4845       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4846       .writefn = tlbi_aa64_vae1_write },
4847     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4848       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4849       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4850       .writefn = tlbi_aa64_vae1_write },
4851     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4852       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4853       .access = PL2_W, .type = ARM_CP_NO_RAW,
4854       .writefn = tlbi_aa64_ipas2e1is_write },
4855     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4856       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4857       .access = PL2_W, .type = ARM_CP_NO_RAW,
4858       .writefn = tlbi_aa64_ipas2e1is_write },
4859     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4860       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4861       .access = PL2_W, .type = ARM_CP_NO_RAW,
4862       .writefn = tlbi_aa64_alle1is_write },
4863     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4864       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4865       .access = PL2_W, .type = ARM_CP_NO_RAW,
4866       .writefn = tlbi_aa64_alle1is_write },
4867     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4868       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4869       .access = PL2_W, .type = ARM_CP_NO_RAW,
4870       .writefn = tlbi_aa64_ipas2e1_write },
4871     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4872       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4873       .access = PL2_W, .type = ARM_CP_NO_RAW,
4874       .writefn = tlbi_aa64_ipas2e1_write },
4875     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4876       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4877       .access = PL2_W, .type = ARM_CP_NO_RAW,
4878       .writefn = tlbi_aa64_alle1_write },
4879     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4880       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4881       .access = PL2_W, .type = ARM_CP_NO_RAW,
4882       .writefn = tlbi_aa64_alle1is_write },
4883 #ifndef CONFIG_USER_ONLY
4884     /* 64 bit address translation operations */
4885     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4886       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4887       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4888       .writefn = ats_write64 },
4889     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4890       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4891       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4892       .writefn = ats_write64 },
4893     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4894       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4895       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4896       .writefn = ats_write64 },
4897     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4898       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4899       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4900       .writefn = ats_write64 },
4901     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4902       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4903       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4904       .writefn = ats_write64 },
4905     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4906       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4907       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4908       .writefn = ats_write64 },
4909     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4910       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4911       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4912       .writefn = ats_write64 },
4913     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4914       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4915       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4916       .writefn = ats_write64 },
4917     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4918     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4919       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4920       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4921       .writefn = ats_write64 },
4922     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4923       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4924       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4925       .writefn = ats_write64 },
4926     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4927       .type = ARM_CP_ALIAS,
4928       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4929       .access = PL1_RW, .resetvalue = 0,
4930       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4931       .writefn = par_write },
4932 #endif
4933     /* TLB invalidate last level of translation table walk */
4934     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4935       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4936       .writefn = tlbimva_is_write },
4937     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4938       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4939       .writefn = tlbimvaa_is_write },
4940     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4941       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4942       .writefn = tlbimva_write },
4943     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4944       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4945       .writefn = tlbimvaa_write },
4946     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4947       .type = ARM_CP_NO_RAW, .access = PL2_W,
4948       .writefn = tlbimva_hyp_write },
4949     { .name = "TLBIMVALHIS",
4950       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4951       .type = ARM_CP_NO_RAW, .access = PL2_W,
4952       .writefn = tlbimva_hyp_is_write },
4953     { .name = "TLBIIPAS2",
4954       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4955       .type = ARM_CP_NO_RAW, .access = PL2_W,
4956       .writefn = tlbiipas2_write },
4957     { .name = "TLBIIPAS2IS",
4958       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4959       .type = ARM_CP_NO_RAW, .access = PL2_W,
4960       .writefn = tlbiipas2_is_write },
4961     { .name = "TLBIIPAS2L",
4962       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4963       .type = ARM_CP_NO_RAW, .access = PL2_W,
4964       .writefn = tlbiipas2_write },
4965     { .name = "TLBIIPAS2LIS",
4966       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4967       .type = ARM_CP_NO_RAW, .access = PL2_W,
4968       .writefn = tlbiipas2_is_write },
4969     /* 32 bit cache operations */
4970     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4971       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
4972     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
4973       .type = ARM_CP_NOP, .access = PL1_W },
4974     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4975       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
4976     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
4977       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
4978     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
4979       .type = ARM_CP_NOP, .access = PL1_W },
4980     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
4981       .type = ARM_CP_NOP, .access = PL1_W },
4982     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4983       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
4984     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4985       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
4986     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
4987       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
4988     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4989       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
4990     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
4991       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
4992     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
4993       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
4994     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4995       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
4996     /* MMU Domain access control / MPU write buffer control */
4997     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
4998       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4999       .writefn = dacr_write, .raw_writefn = raw_write,
5000       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5001                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5002     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5003       .type = ARM_CP_ALIAS,
5004       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5005       .access = PL1_RW,
5006       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5007     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5008       .type = ARM_CP_ALIAS,
5009       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5010       .access = PL1_RW,
5011       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5012     /* We rely on the access checks not allowing the guest to write to the
5013      * state field when SPSel indicates that it's being used as the stack
5014      * pointer.
5015      */
5016     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5017       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5018       .access = PL1_RW, .accessfn = sp_el0_access,
5019       .type = ARM_CP_ALIAS,
5020       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5021     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5022       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5023       .access = PL2_RW, .type = ARM_CP_ALIAS,
5024       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5025     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5026       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5027       .type = ARM_CP_NO_RAW,
5028       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5029     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5030       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5031       .type = ARM_CP_ALIAS,
5032       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
5033       .access = PL2_RW, .accessfn = fpexc32_access },
5034     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5035       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5036       .access = PL2_RW, .resetvalue = 0,
5037       .writefn = dacr_write, .raw_writefn = raw_write,
5038       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5039     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5040       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5041       .access = PL2_RW, .resetvalue = 0,
5042       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5043     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5044       .type = ARM_CP_ALIAS,
5045       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5046       .access = PL2_RW,
5047       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5048     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5049       .type = ARM_CP_ALIAS,
5050       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5051       .access = PL2_RW,
5052       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5053     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5054       .type = ARM_CP_ALIAS,
5055       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5056       .access = PL2_RW,
5057       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5058     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5059       .type = ARM_CP_ALIAS,
5060       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5061       .access = PL2_RW,
5062       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5063     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5064       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5065       .resetvalue = 0,
5066       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5067     { .name = "SDCR", .type = ARM_CP_ALIAS,
5068       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5069       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5070       .writefn = sdcr_write,
5071       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5072     REGINFO_SENTINEL
5073 };
5074 
5075 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
5076 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
5077     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5078       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5079       .access = PL2_RW,
5080       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
5081     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
5082       .type = ARM_CP_NO_RAW,
5083       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5084       .access = PL2_RW,
5085       .type = ARM_CP_CONST, .resetvalue = 0 },
5086     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5087       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5088       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5089     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5090       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5091       .access = PL2_RW,
5092       .type = ARM_CP_CONST, .resetvalue = 0 },
5093     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5094       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5095       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5096     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5097       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5098       .access = PL2_RW, .type = ARM_CP_CONST,
5099       .resetvalue = 0 },
5100     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5101       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5102       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5103     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5104       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5105       .access = PL2_RW, .type = ARM_CP_CONST,
5106       .resetvalue = 0 },
5107     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5108       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5109       .access = PL2_RW, .type = ARM_CP_CONST,
5110       .resetvalue = 0 },
5111     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5112       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5113       .access = PL2_RW, .type = ARM_CP_CONST,
5114       .resetvalue = 0 },
5115     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5116       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5117       .access = PL2_RW, .type = ARM_CP_CONST,
5118       .resetvalue = 0 },
5119     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5120       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5121       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5122     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
5123       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5124       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5125       .type = ARM_CP_CONST, .resetvalue = 0 },
5126     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5127       .cp = 15, .opc1 = 6, .crm = 2,
5128       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5129       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
5130     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5131       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5132       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5133     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5134       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5135       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5136     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5137       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5138       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5139     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5140       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5141       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5142     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5143       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5144       .resetvalue = 0 },
5145     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5146       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5147       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5148     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5149       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5150       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5151     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5152       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5153       .resetvalue = 0 },
5154     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5155       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5156       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5157     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5158       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5159       .resetvalue = 0 },
5160     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5161       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5162       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5163     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5164       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5165       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5166     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5167       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5168       .access = PL2_RW, .accessfn = access_tda,
5169       .type = ARM_CP_CONST, .resetvalue = 0 },
5170     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
5171       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5172       .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
5173       .type = ARM_CP_CONST, .resetvalue = 0 },
5174     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5175       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5176       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5177     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5178       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5179       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5180     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5181       .type = ARM_CP_CONST,
5182       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5183       .access = PL2_RW, .resetvalue = 0 },
5184     REGINFO_SENTINEL
5185 };
5186 
5187 /* Ditto, but for registers which exist in ARMv8 but not v7 */
5188 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
5189     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5190       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5191       .access = PL2_RW,
5192       .type = ARM_CP_CONST, .resetvalue = 0 },
5193     REGINFO_SENTINEL
5194 };
5195 
5196 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5197 {
5198     ARMCPU *cpu = env_archcpu(env);
5199 
5200     if (arm_feature(env, ARM_FEATURE_V8)) {
5201         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5202     } else {
5203         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5204     }
5205 
5206     if (arm_feature(env, ARM_FEATURE_EL3)) {
5207         valid_mask &= ~HCR_HCD;
5208     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5209         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5210          * However, if we're using the SMC PSCI conduit then QEMU is
5211          * effectively acting like EL3 firmware and so the guest at
5212          * EL2 should retain the ability to prevent EL1 from being
5213          * able to make SMC calls into the ersatz firmware, so in
5214          * that case HCR.TSC should be read/write.
5215          */
5216         valid_mask &= ~HCR_TSC;
5217     }
5218 
5219     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5220         if (cpu_isar_feature(aa64_vh, cpu)) {
5221             valid_mask |= HCR_E2H;
5222         }
5223         if (cpu_isar_feature(aa64_lor, cpu)) {
5224             valid_mask |= HCR_TLOR;
5225         }
5226         if (cpu_isar_feature(aa64_pauth, cpu)) {
5227             valid_mask |= HCR_API | HCR_APK;
5228         }
5229     }
5230 
5231     /* Clear RES0 bits.  */
5232     value &= valid_mask;
5233 
5234     /* These bits change the MMU setup:
5235      * HCR_VM enables stage 2 translation
5236      * HCR_PTW forbids certain page-table setups
5237      * HCR_DC Disables stage1 and enables stage2 translation
5238      */
5239     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
5240         tlb_flush(CPU(cpu));
5241     }
5242     env->cp15.hcr_el2 = value;
5243 
5244     /*
5245      * Updates to VI and VF require us to update the status of
5246      * virtual interrupts, which are the logical OR of these bits
5247      * and the state of the input lines from the GIC. (This requires
5248      * that we have the iothread lock, which is done by marking the
5249      * reginfo structs as ARM_CP_IO.)
5250      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5251      * possible for it to be taken immediately, because VIRQ and
5252      * VFIQ are masked unless running at EL0 or EL1, and HCR
5253      * can only be written at EL2.
5254      */
5255     g_assert(qemu_mutex_iothread_locked());
5256     arm_cpu_update_virq(cpu);
5257     arm_cpu_update_vfiq(cpu);
5258 }
5259 
5260 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5261 {
5262     do_hcr_write(env, value, 0);
5263 }
5264 
5265 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5266                           uint64_t value)
5267 {
5268     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5269     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5270     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5271 }
5272 
5273 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5274                          uint64_t value)
5275 {
5276     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5277     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5278     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5279 }
5280 
5281 /*
5282  * Return the effective value of HCR_EL2.
5283  * Bits that are not included here:
5284  * RW       (read from SCR_EL3.RW as needed)
5285  */
5286 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5287 {
5288     uint64_t ret = env->cp15.hcr_el2;
5289 
5290     if (arm_is_secure_below_el3(env)) {
5291         /*
5292          * "This register has no effect if EL2 is not enabled in the
5293          * current Security state".  This is ARMv8.4-SecEL2 speak for
5294          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5295          *
5296          * Prior to that, the language was "In an implementation that
5297          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5298          * as if this field is 0 for all purposes other than a direct
5299          * read or write access of HCR_EL2".  With lots of enumeration
5300          * on a per-field basis.  In current QEMU, this is condition
5301          * is arm_is_secure_below_el3.
5302          *
5303          * Since the v8.4 language applies to the entire register, and
5304          * appears to be backward compatible, use that.
5305          */
5306         return 0;
5307     }
5308 
5309     /*
5310      * For a cpu that supports both aarch64 and aarch32, we can set bits
5311      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5312      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5313      */
5314     if (!arm_el_is_aa64(env, 2)) {
5315         uint64_t aa32_valid;
5316 
5317         /*
5318          * These bits are up-to-date as of ARMv8.6.
5319          * For HCR, it's easiest to list just the 2 bits that are invalid.
5320          * For HCR2, list those that are valid.
5321          */
5322         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5323         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5324                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5325         ret &= aa32_valid;
5326     }
5327 
5328     if (ret & HCR_TGE) {
5329         /* These bits are up-to-date as of ARMv8.6.  */
5330         if (ret & HCR_E2H) {
5331             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5332                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5333                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5334                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5335                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5336                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5337         } else {
5338             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5339         }
5340         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5341                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5342                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5343                  HCR_TLOR);
5344     }
5345 
5346     return ret;
5347 }
5348 
5349 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5350                            uint64_t value)
5351 {
5352     /*
5353      * For A-profile AArch32 EL3, if NSACR.CP10
5354      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5355      */
5356     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5357         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5358         value &= ~(0x3 << 10);
5359         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5360     }
5361     env->cp15.cptr_el[2] = value;
5362 }
5363 
5364 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5365 {
5366     /*
5367      * For A-profile AArch32 EL3, if NSACR.CP10
5368      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5369      */
5370     uint64_t value = env->cp15.cptr_el[2];
5371 
5372     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5373         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5374         value |= 0x3 << 10;
5375     }
5376     return value;
5377 }
5378 
5379 static const ARMCPRegInfo el2_cp_reginfo[] = {
5380     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5381       .type = ARM_CP_IO,
5382       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5383       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5384       .writefn = hcr_write },
5385     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5386       .type = ARM_CP_ALIAS | ARM_CP_IO,
5387       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5388       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5389       .writefn = hcr_writelow },
5390     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5391       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5392       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5393     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5394       .type = ARM_CP_ALIAS,
5395       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5396       .access = PL2_RW,
5397       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5398     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5399       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5400       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5401     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5402       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5403       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5404     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5405       .type = ARM_CP_ALIAS,
5406       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5407       .access = PL2_RW,
5408       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5409     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5410       .type = ARM_CP_ALIAS,
5411       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5412       .access = PL2_RW,
5413       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5414     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5415       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5416       .access = PL2_RW, .writefn = vbar_write,
5417       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5418       .resetvalue = 0 },
5419     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5420       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5421       .access = PL3_RW, .type = ARM_CP_ALIAS,
5422       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5423     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5424       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5425       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5426       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5427       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5428     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5429       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5430       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5431       .resetvalue = 0 },
5432     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5433       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5434       .access = PL2_RW, .type = ARM_CP_ALIAS,
5435       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5436     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5437       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5438       .access = PL2_RW, .type = ARM_CP_CONST,
5439       .resetvalue = 0 },
5440     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5441     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5442       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5443       .access = PL2_RW, .type = ARM_CP_CONST,
5444       .resetvalue = 0 },
5445     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5446       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5447       .access = PL2_RW, .type = ARM_CP_CONST,
5448       .resetvalue = 0 },
5449     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5450       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5451       .access = PL2_RW, .type = ARM_CP_CONST,
5452       .resetvalue = 0 },
5453     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5454       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5455       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5456       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5457       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5458     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5459       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5460       .type = ARM_CP_ALIAS,
5461       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5462       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5463     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5464       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5465       .access = PL2_RW,
5466       /* no .writefn needed as this can't cause an ASID change;
5467        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5468        */
5469       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5470     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5471       .cp = 15, .opc1 = 6, .crm = 2,
5472       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5473       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5474       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5475       .writefn = vttbr_write },
5476     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5477       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5478       .access = PL2_RW, .writefn = vttbr_write,
5479       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5480     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5481       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5482       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5483       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5484     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5485       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5486       .access = PL2_RW, .resetvalue = 0,
5487       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5488     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5489       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5490       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5491       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5492     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5493       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5494       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5495     { .name = "TLBIALLNSNH",
5496       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5497       .type = ARM_CP_NO_RAW, .access = PL2_W,
5498       .writefn = tlbiall_nsnh_write },
5499     { .name = "TLBIALLNSNHIS",
5500       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5501       .type = ARM_CP_NO_RAW, .access = PL2_W,
5502       .writefn = tlbiall_nsnh_is_write },
5503     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5504       .type = ARM_CP_NO_RAW, .access = PL2_W,
5505       .writefn = tlbiall_hyp_write },
5506     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5507       .type = ARM_CP_NO_RAW, .access = PL2_W,
5508       .writefn = tlbiall_hyp_is_write },
5509     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5510       .type = ARM_CP_NO_RAW, .access = PL2_W,
5511       .writefn = tlbimva_hyp_write },
5512     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5513       .type = ARM_CP_NO_RAW, .access = PL2_W,
5514       .writefn = tlbimva_hyp_is_write },
5515     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5516       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5517       .type = ARM_CP_NO_RAW, .access = PL2_W,
5518       .writefn = tlbi_aa64_alle2_write },
5519     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5520       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5521       .type = ARM_CP_NO_RAW, .access = PL2_W,
5522       .writefn = tlbi_aa64_vae2_write },
5523     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5524       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5525       .access = PL2_W, .type = ARM_CP_NO_RAW,
5526       .writefn = tlbi_aa64_vae2_write },
5527     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5528       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5529       .access = PL2_W, .type = ARM_CP_NO_RAW,
5530       .writefn = tlbi_aa64_alle2is_write },
5531     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5532       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5533       .type = ARM_CP_NO_RAW, .access = PL2_W,
5534       .writefn = tlbi_aa64_vae2is_write },
5535     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5536       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5537       .access = PL2_W, .type = ARM_CP_NO_RAW,
5538       .writefn = tlbi_aa64_vae2is_write },
5539 #ifndef CONFIG_USER_ONLY
5540     /* Unlike the other EL2-related AT operations, these must
5541      * UNDEF from EL3 if EL2 is not implemented, which is why we
5542      * define them here rather than with the rest of the AT ops.
5543      */
5544     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5545       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5546       .access = PL2_W, .accessfn = at_s1e2_access,
5547       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5548     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5549       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5550       .access = PL2_W, .accessfn = at_s1e2_access,
5551       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5552     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5553      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5554      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5555      * to behave as if SCR.NS was 1.
5556      */
5557     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5558       .access = PL2_W,
5559       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5560     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5561       .access = PL2_W,
5562       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5563     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5564       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5565       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5566        * reset values as IMPDEF. We choose to reset to 3 to comply with
5567        * both ARMv7 and ARMv8.
5568        */
5569       .access = PL2_RW, .resetvalue = 3,
5570       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5571     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5572       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5573       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5574       .writefn = gt_cntvoff_write,
5575       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5576     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5577       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5578       .writefn = gt_cntvoff_write,
5579       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5580     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5581       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5582       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5583       .type = ARM_CP_IO, .access = PL2_RW,
5584       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5585     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5586       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5587       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5588       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5589     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5590       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5591       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5592       .resetfn = gt_hyp_timer_reset,
5593       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5594     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5595       .type = ARM_CP_IO,
5596       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5597       .access = PL2_RW,
5598       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5599       .resetvalue = 0,
5600       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5601 #endif
5602     /* The only field of MDCR_EL2 that has a defined architectural reset value
5603      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
5604      * don't implement any PMU event counters, so using zero as a reset
5605      * value for MDCR_EL2 is okay
5606      */
5607     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5608       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5609       .access = PL2_RW, .resetvalue = 0,
5610       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5611     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5612       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5613       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5614       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5615     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5616       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5617       .access = PL2_RW,
5618       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5619     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5620       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5621       .access = PL2_RW,
5622       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5623     REGINFO_SENTINEL
5624 };
5625 
5626 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5627     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5628       .type = ARM_CP_ALIAS | ARM_CP_IO,
5629       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5630       .access = PL2_RW,
5631       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5632       .writefn = hcr_writehigh },
5633     REGINFO_SENTINEL
5634 };
5635 
5636 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5637                                    bool isread)
5638 {
5639     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5640      * At Secure EL1 it traps to EL3.
5641      */
5642     if (arm_current_el(env) == 3) {
5643         return CP_ACCESS_OK;
5644     }
5645     if (arm_is_secure_below_el3(env)) {
5646         return CP_ACCESS_TRAP_EL3;
5647     }
5648     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5649     if (isread) {
5650         return CP_ACCESS_OK;
5651     }
5652     return CP_ACCESS_TRAP_UNCATEGORIZED;
5653 }
5654 
5655 static const ARMCPRegInfo el3_cp_reginfo[] = {
5656     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5657       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5658       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5659       .resetvalue = 0, .writefn = scr_write },
5660     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5661       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5662       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5663       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5664       .writefn = scr_write },
5665     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5666       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5667       .access = PL3_RW, .resetvalue = 0,
5668       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5669     { .name = "SDER",
5670       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5671       .access = PL3_RW, .resetvalue = 0,
5672       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5673     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5674       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5675       .writefn = vbar_write, .resetvalue = 0,
5676       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5677     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5678       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5679       .access = PL3_RW, .resetvalue = 0,
5680       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5681     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5682       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5683       .access = PL3_RW,
5684       /* no .writefn needed as this can't cause an ASID change;
5685        * we must provide a .raw_writefn and .resetfn because we handle
5686        * reset and migration for the AArch32 TTBCR(S), which might be
5687        * using mask and base_mask.
5688        */
5689       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5690       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5691     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5692       .type = ARM_CP_ALIAS,
5693       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5694       .access = PL3_RW,
5695       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5696     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5697       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5698       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5699     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5700       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5701       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5702     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5703       .type = ARM_CP_ALIAS,
5704       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5705       .access = PL3_RW,
5706       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5707     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5708       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5709       .access = PL3_RW, .writefn = vbar_write,
5710       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5711       .resetvalue = 0 },
5712     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5713       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5714       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5715       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5716     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5717       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5718       .access = PL3_RW, .resetvalue = 0,
5719       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5720     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5721       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5722       .access = PL3_RW, .type = ARM_CP_CONST,
5723       .resetvalue = 0 },
5724     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5725       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5726       .access = PL3_RW, .type = ARM_CP_CONST,
5727       .resetvalue = 0 },
5728     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5729       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5730       .access = PL3_RW, .type = ARM_CP_CONST,
5731       .resetvalue = 0 },
5732     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5733       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5734       .access = PL3_W, .type = ARM_CP_NO_RAW,
5735       .writefn = tlbi_aa64_alle3is_write },
5736     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5737       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5738       .access = PL3_W, .type = ARM_CP_NO_RAW,
5739       .writefn = tlbi_aa64_vae3is_write },
5740     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5741       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5742       .access = PL3_W, .type = ARM_CP_NO_RAW,
5743       .writefn = tlbi_aa64_vae3is_write },
5744     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5745       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5746       .access = PL3_W, .type = ARM_CP_NO_RAW,
5747       .writefn = tlbi_aa64_alle3_write },
5748     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5749       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5750       .access = PL3_W, .type = ARM_CP_NO_RAW,
5751       .writefn = tlbi_aa64_vae3_write },
5752     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5753       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5754       .access = PL3_W, .type = ARM_CP_NO_RAW,
5755       .writefn = tlbi_aa64_vae3_write },
5756     REGINFO_SENTINEL
5757 };
5758 
5759 #ifndef CONFIG_USER_ONLY
5760 /* Test if system register redirection is to occur in the current state.  */
5761 static bool redirect_for_e2h(CPUARMState *env)
5762 {
5763     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5764 }
5765 
5766 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5767 {
5768     CPReadFn *readfn;
5769 
5770     if (redirect_for_e2h(env)) {
5771         /* Switch to the saved EL2 version of the register.  */
5772         ri = ri->opaque;
5773         readfn = ri->readfn;
5774     } else {
5775         readfn = ri->orig_readfn;
5776     }
5777     if (readfn == NULL) {
5778         readfn = raw_read;
5779     }
5780     return readfn(env, ri);
5781 }
5782 
5783 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5784                           uint64_t value)
5785 {
5786     CPWriteFn *writefn;
5787 
5788     if (redirect_for_e2h(env)) {
5789         /* Switch to the saved EL2 version of the register.  */
5790         ri = ri->opaque;
5791         writefn = ri->writefn;
5792     } else {
5793         writefn = ri->orig_writefn;
5794     }
5795     if (writefn == NULL) {
5796         writefn = raw_write;
5797     }
5798     writefn(env, ri, value);
5799 }
5800 
5801 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5802 {
5803     struct E2HAlias {
5804         uint32_t src_key, dst_key, new_key;
5805         const char *src_name, *dst_name, *new_name;
5806         bool (*feature)(const ARMISARegisters *id);
5807     };
5808 
5809 #define K(op0, op1, crn, crm, op2) \
5810     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5811 
5812     static const struct E2HAlias aliases[] = {
5813         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5814           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5815         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5816           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5817         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5818           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5819         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5820           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5821         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5822           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5823         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5824           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5825         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5826           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5827         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5828           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5829         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5830           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5831         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5832           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5833         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5834           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5835         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5836           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5837         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5838           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5839         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5840           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5841         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
5842           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
5843         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
5844           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
5845 
5846         /*
5847          * Note that redirection of ZCR is mentioned in the description
5848          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
5849          * not in the summary table.
5850          */
5851         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
5852           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
5853 
5854         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
5855         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
5856     };
5857 #undef K
5858 
5859     size_t i;
5860 
5861     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
5862         const struct E2HAlias *a = &aliases[i];
5863         ARMCPRegInfo *src_reg, *dst_reg;
5864 
5865         if (a->feature && !a->feature(&cpu->isar)) {
5866             continue;
5867         }
5868 
5869         src_reg = g_hash_table_lookup(cpu->cp_regs, &a->src_key);
5870         dst_reg = g_hash_table_lookup(cpu->cp_regs, &a->dst_key);
5871         g_assert(src_reg != NULL);
5872         g_assert(dst_reg != NULL);
5873 
5874         /* Cross-compare names to detect typos in the keys.  */
5875         g_assert(strcmp(src_reg->name, a->src_name) == 0);
5876         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
5877 
5878         /* None of the core system registers use opaque; we will.  */
5879         g_assert(src_reg->opaque == NULL);
5880 
5881         /* Create alias before redirection so we dup the right data. */
5882         if (a->new_key) {
5883             ARMCPRegInfo *new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
5884             uint32_t *new_key = g_memdup(&a->new_key, sizeof(uint32_t));
5885             bool ok;
5886 
5887             new_reg->name = a->new_name;
5888             new_reg->type |= ARM_CP_ALIAS;
5889             /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
5890             new_reg->access &= PL2_RW | PL3_RW;
5891 
5892             ok = g_hash_table_insert(cpu->cp_regs, new_key, new_reg);
5893             g_assert(ok);
5894         }
5895 
5896         src_reg->opaque = dst_reg;
5897         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
5898         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
5899         if (!src_reg->raw_readfn) {
5900             src_reg->raw_readfn = raw_read;
5901         }
5902         if (!src_reg->raw_writefn) {
5903             src_reg->raw_writefn = raw_write;
5904         }
5905         src_reg->readfn = el2_e2h_read;
5906         src_reg->writefn = el2_e2h_write;
5907     }
5908 }
5909 #endif
5910 
5911 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5912                                      bool isread)
5913 {
5914     int cur_el = arm_current_el(env);
5915 
5916     if (cur_el < 2) {
5917         uint64_t hcr = arm_hcr_el2_eff(env);
5918 
5919         if (cur_el == 0) {
5920             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
5921                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
5922                     return CP_ACCESS_TRAP_EL2;
5923                 }
5924             } else {
5925                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5926                     return CP_ACCESS_TRAP;
5927                 }
5928                 if (hcr & HCR_TID2) {
5929                     return CP_ACCESS_TRAP_EL2;
5930                 }
5931             }
5932         } else if (hcr & HCR_TID2) {
5933             return CP_ACCESS_TRAP_EL2;
5934         }
5935     }
5936 
5937     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
5938         return CP_ACCESS_TRAP_EL2;
5939     }
5940 
5941     return CP_ACCESS_OK;
5942 }
5943 
5944 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5945                         uint64_t value)
5946 {
5947     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5948      * read via a bit in OSLSR_EL1.
5949      */
5950     int oslock;
5951 
5952     if (ri->state == ARM_CP_STATE_AA32) {
5953         oslock = (value == 0xC5ACCE55);
5954     } else {
5955         oslock = value & 1;
5956     }
5957 
5958     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5959 }
5960 
5961 static const ARMCPRegInfo debug_cp_reginfo[] = {
5962     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5963      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5964      * unlike DBGDRAR it is never accessible from EL0.
5965      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5966      * accessor.
5967      */
5968     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5969       .access = PL0_R, .accessfn = access_tdra,
5970       .type = ARM_CP_CONST, .resetvalue = 0 },
5971     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5972       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5973       .access = PL1_R, .accessfn = access_tdra,
5974       .type = ARM_CP_CONST, .resetvalue = 0 },
5975     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5976       .access = PL0_R, .accessfn = access_tdra,
5977       .type = ARM_CP_CONST, .resetvalue = 0 },
5978     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5979     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5980       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5981       .access = PL1_RW, .accessfn = access_tda,
5982       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5983       .resetvalue = 0 },
5984     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
5985      * We don't implement the configurable EL0 access.
5986      */
5987     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
5988       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5989       .type = ARM_CP_ALIAS,
5990       .access = PL1_R, .accessfn = access_tda,
5991       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
5992     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
5993       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
5994       .access = PL1_W, .type = ARM_CP_NO_RAW,
5995       .accessfn = access_tdosa,
5996       .writefn = oslar_write },
5997     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
5998       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
5999       .access = PL1_R, .resetvalue = 10,
6000       .accessfn = access_tdosa,
6001       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
6002     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
6003     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
6004       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
6005       .access = PL1_RW, .accessfn = access_tdosa,
6006       .type = ARM_CP_NOP },
6007     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
6008      * implement vector catch debug events yet.
6009      */
6010     { .name = "DBGVCR",
6011       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6012       .access = PL1_RW, .accessfn = access_tda,
6013       .type = ARM_CP_NOP },
6014     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
6015      * to save and restore a 32-bit guest's DBGVCR)
6016      */
6017     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
6018       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
6019       .access = PL2_RW, .accessfn = access_tda,
6020       .type = ARM_CP_NOP },
6021     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6022      * Channel but Linux may try to access this register. The 32-bit
6023      * alias is DBGDCCINT.
6024      */
6025     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6026       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6027       .access = PL1_RW, .accessfn = access_tda,
6028       .type = ARM_CP_NOP },
6029     REGINFO_SENTINEL
6030 };
6031 
6032 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6033     /* 64 bit access versions of the (dummy) debug registers */
6034     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6035       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6036     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6037       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6038     REGINFO_SENTINEL
6039 };
6040 
6041 /* Return the exception level to which exceptions should be taken
6042  * via SVEAccessTrap.  If an exception should be routed through
6043  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6044  * take care of raising that exception.
6045  * C.f. the ARM pseudocode function CheckSVEEnabled.
6046  */
6047 int sve_exception_el(CPUARMState *env, int el)
6048 {
6049 #ifndef CONFIG_USER_ONLY
6050     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6051 
6052     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6053         bool disabled = false;
6054 
6055         /* The CPACR.ZEN controls traps to EL1:
6056          * 0, 2 : trap EL0 and EL1 accesses
6057          * 1    : trap only EL0 accesses
6058          * 3    : trap no accesses
6059          */
6060         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
6061             disabled = true;
6062         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
6063             disabled = el == 0;
6064         }
6065         if (disabled) {
6066             /* route_to_el2 */
6067             return hcr_el2 & HCR_TGE ? 2 : 1;
6068         }
6069 
6070         /* Check CPACR.FPEN.  */
6071         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
6072             disabled = true;
6073         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
6074             disabled = el == 0;
6075         }
6076         if (disabled) {
6077             return 0;
6078         }
6079     }
6080 
6081     /* CPTR_EL2.  Since TZ and TFP are positive,
6082      * they will be zero when EL2 is not present.
6083      */
6084     if (el <= 2 && !arm_is_secure_below_el3(env)) {
6085         if (env->cp15.cptr_el[2] & CPTR_TZ) {
6086             return 2;
6087         }
6088         if (env->cp15.cptr_el[2] & CPTR_TFP) {
6089             return 0;
6090         }
6091     }
6092 
6093     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6094     if (arm_feature(env, ARM_FEATURE_EL3)
6095         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6096         return 3;
6097     }
6098 #endif
6099     return 0;
6100 }
6101 
6102 static uint32_t sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6103 {
6104     uint32_t end_len;
6105 
6106     end_len = start_len &= 0xf;
6107     if (!test_bit(start_len, cpu->sve_vq_map)) {
6108         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6109         assert(end_len < start_len);
6110     }
6111     return end_len;
6112 }
6113 
6114 /*
6115  * Given that SVE is enabled, return the vector length for EL.
6116  */
6117 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6118 {
6119     ARMCPU *cpu = env_archcpu(env);
6120     uint32_t zcr_len = cpu->sve_max_vq - 1;
6121 
6122     if (el <= 1) {
6123         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6124     }
6125     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6126         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6127     }
6128     if (arm_feature(env, ARM_FEATURE_EL3)) {
6129         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6130     }
6131 
6132     return sve_zcr_get_valid_len(cpu, zcr_len);
6133 }
6134 
6135 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6136                       uint64_t value)
6137 {
6138     int cur_el = arm_current_el(env);
6139     int old_len = sve_zcr_len_for_el(env, cur_el);
6140     int new_len;
6141 
6142     /* Bits other than [3:0] are RAZ/WI.  */
6143     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6144     raw_write(env, ri, value & 0xf);
6145 
6146     /*
6147      * Because we arrived here, we know both FP and SVE are enabled;
6148      * otherwise we would have trapped access to the ZCR_ELn register.
6149      */
6150     new_len = sve_zcr_len_for_el(env, cur_el);
6151     if (new_len < old_len) {
6152         aarch64_sve_narrow_vq(env, new_len + 1);
6153     }
6154 }
6155 
6156 static const ARMCPRegInfo zcr_el1_reginfo = {
6157     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6158     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6159     .access = PL1_RW, .type = ARM_CP_SVE,
6160     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6161     .writefn = zcr_write, .raw_writefn = raw_write
6162 };
6163 
6164 static const ARMCPRegInfo zcr_el2_reginfo = {
6165     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6166     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6167     .access = PL2_RW, .type = ARM_CP_SVE,
6168     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6169     .writefn = zcr_write, .raw_writefn = raw_write
6170 };
6171 
6172 static const ARMCPRegInfo zcr_no_el2_reginfo = {
6173     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6174     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6175     .access = PL2_RW, .type = ARM_CP_SVE,
6176     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
6177 };
6178 
6179 static const ARMCPRegInfo zcr_el3_reginfo = {
6180     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6181     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6182     .access = PL3_RW, .type = ARM_CP_SVE,
6183     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6184     .writefn = zcr_write, .raw_writefn = raw_write
6185 };
6186 
6187 void hw_watchpoint_update(ARMCPU *cpu, int n)
6188 {
6189     CPUARMState *env = &cpu->env;
6190     vaddr len = 0;
6191     vaddr wvr = env->cp15.dbgwvr[n];
6192     uint64_t wcr = env->cp15.dbgwcr[n];
6193     int mask;
6194     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6195 
6196     if (env->cpu_watchpoint[n]) {
6197         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6198         env->cpu_watchpoint[n] = NULL;
6199     }
6200 
6201     if (!extract64(wcr, 0, 1)) {
6202         /* E bit clear : watchpoint disabled */
6203         return;
6204     }
6205 
6206     switch (extract64(wcr, 3, 2)) {
6207     case 0:
6208         /* LSC 00 is reserved and must behave as if the wp is disabled */
6209         return;
6210     case 1:
6211         flags |= BP_MEM_READ;
6212         break;
6213     case 2:
6214         flags |= BP_MEM_WRITE;
6215         break;
6216     case 3:
6217         flags |= BP_MEM_ACCESS;
6218         break;
6219     }
6220 
6221     /* Attempts to use both MASK and BAS fields simultaneously are
6222      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6223      * thus generating a watchpoint for every byte in the masked region.
6224      */
6225     mask = extract64(wcr, 24, 4);
6226     if (mask == 1 || mask == 2) {
6227         /* Reserved values of MASK; we must act as if the mask value was
6228          * some non-reserved value, or as if the watchpoint were disabled.
6229          * We choose the latter.
6230          */
6231         return;
6232     } else if (mask) {
6233         /* Watchpoint covers an aligned area up to 2GB in size */
6234         len = 1ULL << mask;
6235         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6236          * whether the watchpoint fires when the unmasked bits match; we opt
6237          * to generate the exceptions.
6238          */
6239         wvr &= ~(len - 1);
6240     } else {
6241         /* Watchpoint covers bytes defined by the byte address select bits */
6242         int bas = extract64(wcr, 5, 8);
6243         int basstart;
6244 
6245         if (bas == 0) {
6246             /* This must act as if the watchpoint is disabled */
6247             return;
6248         }
6249 
6250         if (extract64(wvr, 2, 1)) {
6251             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6252              * ignored, and BAS[3:0] define which bytes to watch.
6253              */
6254             bas &= 0xf;
6255         }
6256         /* The BAS bits are supposed to be programmed to indicate a contiguous
6257          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6258          * we fire for each byte in the word/doubleword addressed by the WVR.
6259          * We choose to ignore any non-zero bits after the first range of 1s.
6260          */
6261         basstart = ctz32(bas);
6262         len = cto32(bas >> basstart);
6263         wvr += basstart;
6264     }
6265 
6266     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6267                           &env->cpu_watchpoint[n]);
6268 }
6269 
6270 void hw_watchpoint_update_all(ARMCPU *cpu)
6271 {
6272     int i;
6273     CPUARMState *env = &cpu->env;
6274 
6275     /* Completely clear out existing QEMU watchpoints and our array, to
6276      * avoid possible stale entries following migration load.
6277      */
6278     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6279     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6280 
6281     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6282         hw_watchpoint_update(cpu, i);
6283     }
6284 }
6285 
6286 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6287                          uint64_t value)
6288 {
6289     ARMCPU *cpu = env_archcpu(env);
6290     int i = ri->crm;
6291 
6292     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
6293      * register reads and behaves as if values written are sign extended.
6294      * Bits [1:0] are RES0.
6295      */
6296     value = sextract64(value, 0, 49) & ~3ULL;
6297 
6298     raw_write(env, ri, value);
6299     hw_watchpoint_update(cpu, i);
6300 }
6301 
6302 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6303                          uint64_t value)
6304 {
6305     ARMCPU *cpu = env_archcpu(env);
6306     int i = ri->crm;
6307 
6308     raw_write(env, ri, value);
6309     hw_watchpoint_update(cpu, i);
6310 }
6311 
6312 void hw_breakpoint_update(ARMCPU *cpu, int n)
6313 {
6314     CPUARMState *env = &cpu->env;
6315     uint64_t bvr = env->cp15.dbgbvr[n];
6316     uint64_t bcr = env->cp15.dbgbcr[n];
6317     vaddr addr;
6318     int bt;
6319     int flags = BP_CPU;
6320 
6321     if (env->cpu_breakpoint[n]) {
6322         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6323         env->cpu_breakpoint[n] = NULL;
6324     }
6325 
6326     if (!extract64(bcr, 0, 1)) {
6327         /* E bit clear : watchpoint disabled */
6328         return;
6329     }
6330 
6331     bt = extract64(bcr, 20, 4);
6332 
6333     switch (bt) {
6334     case 4: /* unlinked address mismatch (reserved if AArch64) */
6335     case 5: /* linked address mismatch (reserved if AArch64) */
6336         qemu_log_mask(LOG_UNIMP,
6337                       "arm: address mismatch breakpoint types not implemented\n");
6338         return;
6339     case 0: /* unlinked address match */
6340     case 1: /* linked address match */
6341     {
6342         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
6343          * we behave as if the register was sign extended. Bits [1:0] are
6344          * RES0. The BAS field is used to allow setting breakpoints on 16
6345          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6346          * a bp will fire if the addresses covered by the bp and the addresses
6347          * covered by the insn overlap but the insn doesn't start at the
6348          * start of the bp address range. We choose to require the insn and
6349          * the bp to have the same address. The constraints on writing to
6350          * BAS enforced in dbgbcr_write mean we have only four cases:
6351          *  0b0000  => no breakpoint
6352          *  0b0011  => breakpoint on addr
6353          *  0b1100  => breakpoint on addr + 2
6354          *  0b1111  => breakpoint on addr
6355          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6356          */
6357         int bas = extract64(bcr, 5, 4);
6358         addr = sextract64(bvr, 0, 49) & ~3ULL;
6359         if (bas == 0) {
6360             return;
6361         }
6362         if (bas == 0xc) {
6363             addr += 2;
6364         }
6365         break;
6366     }
6367     case 2: /* unlinked context ID match */
6368     case 8: /* unlinked VMID match (reserved if no EL2) */
6369     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6370         qemu_log_mask(LOG_UNIMP,
6371                       "arm: unlinked context breakpoint types not implemented\n");
6372         return;
6373     case 9: /* linked VMID match (reserved if no EL2) */
6374     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6375     case 3: /* linked context ID match */
6376     default:
6377         /* We must generate no events for Linked context matches (unless
6378          * they are linked to by some other bp/wp, which is handled in
6379          * updates for the linking bp/wp). We choose to also generate no events
6380          * for reserved values.
6381          */
6382         return;
6383     }
6384 
6385     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6386 }
6387 
6388 void hw_breakpoint_update_all(ARMCPU *cpu)
6389 {
6390     int i;
6391     CPUARMState *env = &cpu->env;
6392 
6393     /* Completely clear out existing QEMU breakpoints and our array, to
6394      * avoid possible stale entries following migration load.
6395      */
6396     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6397     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6398 
6399     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6400         hw_breakpoint_update(cpu, i);
6401     }
6402 }
6403 
6404 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6405                          uint64_t value)
6406 {
6407     ARMCPU *cpu = env_archcpu(env);
6408     int i = ri->crm;
6409 
6410     raw_write(env, ri, value);
6411     hw_breakpoint_update(cpu, i);
6412 }
6413 
6414 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6415                          uint64_t value)
6416 {
6417     ARMCPU *cpu = env_archcpu(env);
6418     int i = ri->crm;
6419 
6420     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6421      * copy of BAS[0].
6422      */
6423     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6424     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6425 
6426     raw_write(env, ri, value);
6427     hw_breakpoint_update(cpu, i);
6428 }
6429 
6430 static void define_debug_regs(ARMCPU *cpu)
6431 {
6432     /* Define v7 and v8 architectural debug registers.
6433      * These are just dummy implementations for now.
6434      */
6435     int i;
6436     int wrps, brps, ctx_cmps;
6437     ARMCPRegInfo dbgdidr = {
6438         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
6439         .access = PL0_R, .accessfn = access_tda,
6440         .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6441     };
6442 
6443     /* Note that all these register fields hold "number of Xs minus 1". */
6444     brps = arm_num_brps(cpu);
6445     wrps = arm_num_wrps(cpu);
6446     ctx_cmps = arm_num_ctx_cmps(cpu);
6447 
6448     assert(ctx_cmps <= brps);
6449 
6450     define_one_arm_cp_reg(cpu, &dbgdidr);
6451     define_arm_cp_regs(cpu, debug_cp_reginfo);
6452 
6453     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6454         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6455     }
6456 
6457     for (i = 0; i < brps; i++) {
6458         ARMCPRegInfo dbgregs[] = {
6459             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6460               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6461               .access = PL1_RW, .accessfn = access_tda,
6462               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6463               .writefn = dbgbvr_write, .raw_writefn = raw_write
6464             },
6465             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6466               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6467               .access = PL1_RW, .accessfn = access_tda,
6468               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6469               .writefn = dbgbcr_write, .raw_writefn = raw_write
6470             },
6471             REGINFO_SENTINEL
6472         };
6473         define_arm_cp_regs(cpu, dbgregs);
6474     }
6475 
6476     for (i = 0; i < wrps; i++) {
6477         ARMCPRegInfo dbgregs[] = {
6478             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6479               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6480               .access = PL1_RW, .accessfn = access_tda,
6481               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6482               .writefn = dbgwvr_write, .raw_writefn = raw_write
6483             },
6484             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6485               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6486               .access = PL1_RW, .accessfn = access_tda,
6487               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6488               .writefn = dbgwcr_write, .raw_writefn = raw_write
6489             },
6490             REGINFO_SENTINEL
6491         };
6492         define_arm_cp_regs(cpu, dbgregs);
6493     }
6494 }
6495 
6496 static void define_pmu_regs(ARMCPU *cpu)
6497 {
6498     /*
6499      * v7 performance monitor control register: same implementor
6500      * field as main ID register, and we implement four counters in
6501      * addition to the cycle count register.
6502      */
6503     unsigned int i, pmcrn = 4;
6504     ARMCPRegInfo pmcr = {
6505         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6506         .access = PL0_RW,
6507         .type = ARM_CP_IO | ARM_CP_ALIAS,
6508         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6509         .accessfn = pmreg_access, .writefn = pmcr_write,
6510         .raw_writefn = raw_write,
6511     };
6512     ARMCPRegInfo pmcr64 = {
6513         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6514         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6515         .access = PL0_RW, .accessfn = pmreg_access,
6516         .type = ARM_CP_IO,
6517         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6518         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6519                       PMCRLC,
6520         .writefn = pmcr_write, .raw_writefn = raw_write,
6521     };
6522     define_one_arm_cp_reg(cpu, &pmcr);
6523     define_one_arm_cp_reg(cpu, &pmcr64);
6524     for (i = 0; i < pmcrn; i++) {
6525         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6526         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6527         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6528         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6529         ARMCPRegInfo pmev_regs[] = {
6530             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6531               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6532               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6533               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6534               .accessfn = pmreg_access },
6535             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6536               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6537               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6538               .type = ARM_CP_IO,
6539               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6540               .raw_readfn = pmevcntr_rawread,
6541               .raw_writefn = pmevcntr_rawwrite },
6542             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6543               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6544               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6545               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6546               .accessfn = pmreg_access },
6547             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6548               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6549               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6550               .type = ARM_CP_IO,
6551               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6552               .raw_writefn = pmevtyper_rawwrite },
6553             REGINFO_SENTINEL
6554         };
6555         define_arm_cp_regs(cpu, pmev_regs);
6556         g_free(pmevcntr_name);
6557         g_free(pmevcntr_el0_name);
6558         g_free(pmevtyper_name);
6559         g_free(pmevtyper_el0_name);
6560     }
6561     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6562         ARMCPRegInfo v81_pmu_regs[] = {
6563             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6564               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6565               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6566               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6567             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6568               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6569               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6570               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6571             REGINFO_SENTINEL
6572         };
6573         define_arm_cp_regs(cpu, v81_pmu_regs);
6574     }
6575     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6576         static const ARMCPRegInfo v84_pmmir = {
6577             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6578             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6579             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6580             .resetvalue = 0
6581         };
6582         define_one_arm_cp_reg(cpu, &v84_pmmir);
6583     }
6584 }
6585 
6586 /* We don't know until after realize whether there's a GICv3
6587  * attached, and that is what registers the gicv3 sysregs.
6588  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6589  * at runtime.
6590  */
6591 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6592 {
6593     ARMCPU *cpu = env_archcpu(env);
6594     uint64_t pfr1 = cpu->id_pfr1;
6595 
6596     if (env->gicv3state) {
6597         pfr1 |= 1 << 28;
6598     }
6599     return pfr1;
6600 }
6601 
6602 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6603 {
6604     ARMCPU *cpu = env_archcpu(env);
6605     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6606 
6607     if (env->gicv3state) {
6608         pfr0 |= 1 << 24;
6609     }
6610     return pfr0;
6611 }
6612 
6613 /* Shared logic between LORID and the rest of the LOR* registers.
6614  * Secure state has already been delt with.
6615  */
6616 static CPAccessResult access_lor_ns(CPUARMState *env)
6617 {
6618     int el = arm_current_el(env);
6619 
6620     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6621         return CP_ACCESS_TRAP_EL2;
6622     }
6623     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6624         return CP_ACCESS_TRAP_EL3;
6625     }
6626     return CP_ACCESS_OK;
6627 }
6628 
6629 static CPAccessResult access_lorid(CPUARMState *env, const ARMCPRegInfo *ri,
6630                                    bool isread)
6631 {
6632     if (arm_is_secure_below_el3(env)) {
6633         /* Access ok in secure mode.  */
6634         return CP_ACCESS_OK;
6635     }
6636     return access_lor_ns(env);
6637 }
6638 
6639 static CPAccessResult access_lor_other(CPUARMState *env,
6640                                        const ARMCPRegInfo *ri, bool isread)
6641 {
6642     if (arm_is_secure_below_el3(env)) {
6643         /* Access denied in secure mode.  */
6644         return CP_ACCESS_TRAP;
6645     }
6646     return access_lor_ns(env);
6647 }
6648 
6649 /*
6650  * A trivial implementation of ARMv8.1-LOR leaves all of these
6651  * registers fixed at 0, which indicates that there are zero
6652  * supported Limited Ordering regions.
6653  */
6654 static const ARMCPRegInfo lor_reginfo[] = {
6655     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6656       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6657       .access = PL1_RW, .accessfn = access_lor_other,
6658       .type = ARM_CP_CONST, .resetvalue = 0 },
6659     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6660       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6661       .access = PL1_RW, .accessfn = access_lor_other,
6662       .type = ARM_CP_CONST, .resetvalue = 0 },
6663     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6664       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6665       .access = PL1_RW, .accessfn = access_lor_other,
6666       .type = ARM_CP_CONST, .resetvalue = 0 },
6667     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6668       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6669       .access = PL1_RW, .accessfn = access_lor_other,
6670       .type = ARM_CP_CONST, .resetvalue = 0 },
6671     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6672       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6673       .access = PL1_R, .accessfn = access_lorid,
6674       .type = ARM_CP_CONST, .resetvalue = 0 },
6675     REGINFO_SENTINEL
6676 };
6677 
6678 #ifdef TARGET_AARCH64
6679 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6680                                    bool isread)
6681 {
6682     int el = arm_current_el(env);
6683 
6684     if (el < 2 &&
6685         arm_feature(env, ARM_FEATURE_EL2) &&
6686         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6687         return CP_ACCESS_TRAP_EL2;
6688     }
6689     if (el < 3 &&
6690         arm_feature(env, ARM_FEATURE_EL3) &&
6691         !(env->cp15.scr_el3 & SCR_APK)) {
6692         return CP_ACCESS_TRAP_EL3;
6693     }
6694     return CP_ACCESS_OK;
6695 }
6696 
6697 static const ARMCPRegInfo pauth_reginfo[] = {
6698     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6699       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6700       .access = PL1_RW, .accessfn = access_pauth,
6701       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6702     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6703       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6704       .access = PL1_RW, .accessfn = access_pauth,
6705       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6706     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6707       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6708       .access = PL1_RW, .accessfn = access_pauth,
6709       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6710     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6711       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6712       .access = PL1_RW, .accessfn = access_pauth,
6713       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6714     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6715       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6716       .access = PL1_RW, .accessfn = access_pauth,
6717       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6718     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6719       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6720       .access = PL1_RW, .accessfn = access_pauth,
6721       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6722     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6723       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6724       .access = PL1_RW, .accessfn = access_pauth,
6725       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6726     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6727       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6728       .access = PL1_RW, .accessfn = access_pauth,
6729       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6730     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6731       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6732       .access = PL1_RW, .accessfn = access_pauth,
6733       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6734     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6735       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6736       .access = PL1_RW, .accessfn = access_pauth,
6737       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6738     REGINFO_SENTINEL
6739 };
6740 
6741 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
6742 {
6743     Error *err = NULL;
6744     uint64_t ret;
6745 
6746     /* Success sets NZCV = 0000.  */
6747     env->NF = env->CF = env->VF = 0, env->ZF = 1;
6748 
6749     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
6750         /*
6751          * ??? Failed, for unknown reasons in the crypto subsystem.
6752          * The best we can do is log the reason and return the
6753          * timed-out indication to the guest.  There is no reason
6754          * we know to expect this failure to be transitory, so the
6755          * guest may well hang retrying the operation.
6756          */
6757         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
6758                       ri->name, error_get_pretty(err));
6759         error_free(err);
6760 
6761         env->ZF = 0; /* NZCF = 0100 */
6762         return 0;
6763     }
6764     return ret;
6765 }
6766 
6767 /* We do not support re-seeding, so the two registers operate the same.  */
6768 static const ARMCPRegInfo rndr_reginfo[] = {
6769     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
6770       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6771       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
6772       .access = PL0_R, .readfn = rndr_readfn },
6773     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
6774       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6775       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
6776       .access = PL0_R, .readfn = rndr_readfn },
6777     REGINFO_SENTINEL
6778 };
6779 
6780 #ifndef CONFIG_USER_ONLY
6781 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
6782                           uint64_t value)
6783 {
6784     ARMCPU *cpu = env_archcpu(env);
6785     /* CTR_EL0 System register -> DminLine, bits [19:16] */
6786     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
6787     uint64_t vaddr_in = (uint64_t) value;
6788     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
6789     void *haddr;
6790     int mem_idx = cpu_mmu_index(env, false);
6791 
6792     /* This won't be crossing page boundaries */
6793     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
6794     if (haddr) {
6795 
6796         ram_addr_t offset;
6797         MemoryRegion *mr;
6798 
6799         /* RCU lock is already being held */
6800         mr = memory_region_from_host(haddr, &offset);
6801 
6802         if (mr) {
6803             memory_region_do_writeback(mr, offset, dline_size);
6804         }
6805     }
6806 }
6807 
6808 static const ARMCPRegInfo dcpop_reg[] = {
6809     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
6810       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
6811       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6812       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6813     REGINFO_SENTINEL
6814 };
6815 
6816 static const ARMCPRegInfo dcpodp_reg[] = {
6817     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
6818       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
6819       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6820       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6821     REGINFO_SENTINEL
6822 };
6823 #endif /*CONFIG_USER_ONLY*/
6824 
6825 #endif
6826 
6827 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
6828                                      bool isread)
6829 {
6830     int el = arm_current_el(env);
6831 
6832     if (el == 0) {
6833         uint64_t sctlr = arm_sctlr(env, el);
6834         if (!(sctlr & SCTLR_EnRCTX)) {
6835             return CP_ACCESS_TRAP;
6836         }
6837     } else if (el == 1) {
6838         uint64_t hcr = arm_hcr_el2_eff(env);
6839         if (hcr & HCR_NV) {
6840             return CP_ACCESS_TRAP_EL2;
6841         }
6842     }
6843     return CP_ACCESS_OK;
6844 }
6845 
6846 static const ARMCPRegInfo predinv_reginfo[] = {
6847     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
6848       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
6849       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6850     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
6851       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
6852       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6853     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
6854       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
6855       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6856     /*
6857      * Note the AArch32 opcodes have a different OPC1.
6858      */
6859     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
6860       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
6861       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6862     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
6863       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
6864       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6865     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
6866       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
6867       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6868     REGINFO_SENTINEL
6869 };
6870 
6871 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
6872 {
6873     /* Read the high 32 bits of the current CCSIDR */
6874     return extract64(ccsidr_read(env, ri), 32, 32);
6875 }
6876 
6877 static const ARMCPRegInfo ccsidr2_reginfo[] = {
6878     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
6879       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
6880       .access = PL1_R,
6881       .accessfn = access_aa64_tid2,
6882       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
6883     REGINFO_SENTINEL
6884 };
6885 
6886 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
6887                                        bool isread)
6888 {
6889     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
6890         return CP_ACCESS_TRAP_EL2;
6891     }
6892 
6893     return CP_ACCESS_OK;
6894 }
6895 
6896 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
6897                                        bool isread)
6898 {
6899     if (arm_feature(env, ARM_FEATURE_V8)) {
6900         return access_aa64_tid3(env, ri, isread);
6901     }
6902 
6903     return CP_ACCESS_OK;
6904 }
6905 
6906 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
6907                                      bool isread)
6908 {
6909     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
6910         return CP_ACCESS_TRAP_EL2;
6911     }
6912 
6913     return CP_ACCESS_OK;
6914 }
6915 
6916 static const ARMCPRegInfo jazelle_regs[] = {
6917     { .name = "JIDR",
6918       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
6919       .access = PL1_R, .accessfn = access_jazelle,
6920       .type = ARM_CP_CONST, .resetvalue = 0 },
6921     { .name = "JOSCR",
6922       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
6923       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
6924     { .name = "JMCR",
6925       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
6926       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
6927     REGINFO_SENTINEL
6928 };
6929 
6930 static const ARMCPRegInfo vhe_reginfo[] = {
6931     { .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
6932       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
6933       .access = PL2_RW,
6934       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2]) },
6935     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
6936       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
6937       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
6938       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
6939 #ifndef CONFIG_USER_ONLY
6940     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
6941       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
6942       .fieldoffset =
6943         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
6944       .type = ARM_CP_IO, .access = PL2_RW,
6945       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
6946     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
6947       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
6948       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
6949       .resetfn = gt_hv_timer_reset,
6950       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
6951     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
6952       .type = ARM_CP_IO,
6953       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
6954       .access = PL2_RW,
6955       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
6956       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
6957     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
6958       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
6959       .type = ARM_CP_IO | ARM_CP_ALIAS,
6960       .access = PL2_RW, .accessfn = e2h_access,
6961       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
6962       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
6963     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
6964       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
6965       .type = ARM_CP_IO | ARM_CP_ALIAS,
6966       .access = PL2_RW, .accessfn = e2h_access,
6967       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
6968       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
6969     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
6970       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
6971       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
6972       .access = PL2_RW, .accessfn = e2h_access,
6973       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
6974     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
6975       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
6976       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
6977       .access = PL2_RW, .accessfn = e2h_access,
6978       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
6979     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
6980       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
6981       .type = ARM_CP_IO | ARM_CP_ALIAS,
6982       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
6983       .access = PL2_RW, .accessfn = e2h_access,
6984       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
6985     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
6986       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
6987       .type = ARM_CP_IO | ARM_CP_ALIAS,
6988       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
6989       .access = PL2_RW, .accessfn = e2h_access,
6990       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
6991 #endif
6992     REGINFO_SENTINEL
6993 };
6994 
6995 #ifndef CONFIG_USER_ONLY
6996 static const ARMCPRegInfo ats1e1_reginfo[] = {
6997     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
6998       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
6999       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7000       .writefn = ats_write64 },
7001     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7002       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7003       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7004       .writefn = ats_write64 },
7005     REGINFO_SENTINEL
7006 };
7007 
7008 static const ARMCPRegInfo ats1cp_reginfo[] = {
7009     { .name = "ATS1CPRP",
7010       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7011       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7012       .writefn = ats_write },
7013     { .name = "ATS1CPWP",
7014       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7015       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7016       .writefn = ats_write },
7017     REGINFO_SENTINEL
7018 };
7019 #endif
7020 
7021 /*
7022  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7023  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7024  * is non-zero, which is never for ARMv7, optionally in ARMv8
7025  * and mandatorily for ARMv8.2 and up.
7026  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7027  * implementation is RAZ/WI we can ignore this detail, as we
7028  * do for ACTLR.
7029  */
7030 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7031     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7032       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7033       .access = PL1_RW, .accessfn = access_tacr,
7034       .type = ARM_CP_CONST, .resetvalue = 0 },
7035     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7036       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7037       .access = PL2_RW, .type = ARM_CP_CONST,
7038       .resetvalue = 0 },
7039     REGINFO_SENTINEL
7040 };
7041 
7042 void register_cp_regs_for_features(ARMCPU *cpu)
7043 {
7044     /* Register all the coprocessor registers based on feature bits */
7045     CPUARMState *env = &cpu->env;
7046     if (arm_feature(env, ARM_FEATURE_M)) {
7047         /* M profile has no coprocessor registers */
7048         return;
7049     }
7050 
7051     define_arm_cp_regs(cpu, cp_reginfo);
7052     if (!arm_feature(env, ARM_FEATURE_V8)) {
7053         /* Must go early as it is full of wildcards that may be
7054          * overridden by later definitions.
7055          */
7056         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7057     }
7058 
7059     if (arm_feature(env, ARM_FEATURE_V6)) {
7060         /* The ID registers all have impdef reset values */
7061         ARMCPRegInfo v6_idregs[] = {
7062             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7063               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7064               .access = PL1_R, .type = ARM_CP_CONST,
7065               .accessfn = access_aa32_tid3,
7066               .resetvalue = cpu->id_pfr0 },
7067             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7068              * the value of the GIC field until after we define these regs.
7069              */
7070             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7071               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7072               .access = PL1_R, .type = ARM_CP_NO_RAW,
7073               .accessfn = access_aa32_tid3,
7074               .readfn = id_pfr1_read,
7075               .writefn = arm_cp_write_ignore },
7076             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7077               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7078               .access = PL1_R, .type = ARM_CP_CONST,
7079               .accessfn = access_aa32_tid3,
7080               .resetvalue = cpu->isar.id_dfr0 },
7081             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7082               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7083               .access = PL1_R, .type = ARM_CP_CONST,
7084               .accessfn = access_aa32_tid3,
7085               .resetvalue = cpu->id_afr0 },
7086             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7087               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7088               .access = PL1_R, .type = ARM_CP_CONST,
7089               .accessfn = access_aa32_tid3,
7090               .resetvalue = cpu->isar.id_mmfr0 },
7091             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7092               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7093               .access = PL1_R, .type = ARM_CP_CONST,
7094               .accessfn = access_aa32_tid3,
7095               .resetvalue = cpu->isar.id_mmfr1 },
7096             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7097               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7098               .access = PL1_R, .type = ARM_CP_CONST,
7099               .accessfn = access_aa32_tid3,
7100               .resetvalue = cpu->isar.id_mmfr2 },
7101             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7102               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7103               .access = PL1_R, .type = ARM_CP_CONST,
7104               .accessfn = access_aa32_tid3,
7105               .resetvalue = cpu->isar.id_mmfr3 },
7106             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7107               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7108               .access = PL1_R, .type = ARM_CP_CONST,
7109               .accessfn = access_aa32_tid3,
7110               .resetvalue = cpu->isar.id_isar0 },
7111             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7112               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7113               .access = PL1_R, .type = ARM_CP_CONST,
7114               .accessfn = access_aa32_tid3,
7115               .resetvalue = cpu->isar.id_isar1 },
7116             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7117               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7118               .access = PL1_R, .type = ARM_CP_CONST,
7119               .accessfn = access_aa32_tid3,
7120               .resetvalue = cpu->isar.id_isar2 },
7121             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7122               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7123               .access = PL1_R, .type = ARM_CP_CONST,
7124               .accessfn = access_aa32_tid3,
7125               .resetvalue = cpu->isar.id_isar3 },
7126             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7127               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7128               .access = PL1_R, .type = ARM_CP_CONST,
7129               .accessfn = access_aa32_tid3,
7130               .resetvalue = cpu->isar.id_isar4 },
7131             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7132               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7133               .access = PL1_R, .type = ARM_CP_CONST,
7134               .accessfn = access_aa32_tid3,
7135               .resetvalue = cpu->isar.id_isar5 },
7136             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7137               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7138               .access = PL1_R, .type = ARM_CP_CONST,
7139               .accessfn = access_aa32_tid3,
7140               .resetvalue = cpu->isar.id_mmfr4 },
7141             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7142               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7143               .access = PL1_R, .type = ARM_CP_CONST,
7144               .accessfn = access_aa32_tid3,
7145               .resetvalue = cpu->isar.id_isar6 },
7146             REGINFO_SENTINEL
7147         };
7148         define_arm_cp_regs(cpu, v6_idregs);
7149         define_arm_cp_regs(cpu, v6_cp_reginfo);
7150     } else {
7151         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7152     }
7153     if (arm_feature(env, ARM_FEATURE_V6K)) {
7154         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7155     }
7156     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7157         !arm_feature(env, ARM_FEATURE_PMSA)) {
7158         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7159     }
7160     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7161         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7162     }
7163     if (arm_feature(env, ARM_FEATURE_V7)) {
7164         ARMCPRegInfo clidr = {
7165             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7166             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7167             .access = PL1_R, .type = ARM_CP_CONST,
7168             .accessfn = access_aa64_tid2,
7169             .resetvalue = cpu->clidr
7170         };
7171         define_one_arm_cp_reg(cpu, &clidr);
7172         define_arm_cp_regs(cpu, v7_cp_reginfo);
7173         define_debug_regs(cpu);
7174         define_pmu_regs(cpu);
7175     } else {
7176         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7177     }
7178     if (arm_feature(env, ARM_FEATURE_V8)) {
7179         /* AArch64 ID registers, which all have impdef reset values.
7180          * Note that within the ID register ranges the unused slots
7181          * must all RAZ, not UNDEF; future architecture versions may
7182          * define new registers here.
7183          */
7184         ARMCPRegInfo v8_idregs[] = {
7185             /* ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST because we don't
7186              * know the right value for the GIC field until after we
7187              * define these regs.
7188              */
7189             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7190               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7191               .access = PL1_R, .type = ARM_CP_NO_RAW,
7192               .accessfn = access_aa64_tid3,
7193               .readfn = id_aa64pfr0_read,
7194               .writefn = arm_cp_write_ignore },
7195             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7196               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7197               .access = PL1_R, .type = ARM_CP_CONST,
7198               .accessfn = access_aa64_tid3,
7199               .resetvalue = cpu->isar.id_aa64pfr1},
7200             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7201               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7202               .access = PL1_R, .type = ARM_CP_CONST,
7203               .accessfn = access_aa64_tid3,
7204               .resetvalue = 0 },
7205             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7206               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7207               .access = PL1_R, .type = ARM_CP_CONST,
7208               .accessfn = access_aa64_tid3,
7209               .resetvalue = 0 },
7210             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7211               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7212               .access = PL1_R, .type = ARM_CP_CONST,
7213               .accessfn = access_aa64_tid3,
7214               /* At present, only SVEver == 0 is defined anyway.  */
7215               .resetvalue = 0 },
7216             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7217               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7218               .access = PL1_R, .type = ARM_CP_CONST,
7219               .accessfn = access_aa64_tid3,
7220               .resetvalue = 0 },
7221             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7222               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7223               .access = PL1_R, .type = ARM_CP_CONST,
7224               .accessfn = access_aa64_tid3,
7225               .resetvalue = 0 },
7226             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7227               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7228               .access = PL1_R, .type = ARM_CP_CONST,
7229               .accessfn = access_aa64_tid3,
7230               .resetvalue = 0 },
7231             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7232               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7233               .access = PL1_R, .type = ARM_CP_CONST,
7234               .accessfn = access_aa64_tid3,
7235               .resetvalue = cpu->isar.id_aa64dfr0 },
7236             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7237               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7238               .access = PL1_R, .type = ARM_CP_CONST,
7239               .accessfn = access_aa64_tid3,
7240               .resetvalue = cpu->isar.id_aa64dfr1 },
7241             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7242               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7243               .access = PL1_R, .type = ARM_CP_CONST,
7244               .accessfn = access_aa64_tid3,
7245               .resetvalue = 0 },
7246             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7247               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7248               .access = PL1_R, .type = ARM_CP_CONST,
7249               .accessfn = access_aa64_tid3,
7250               .resetvalue = 0 },
7251             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7252               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7253               .access = PL1_R, .type = ARM_CP_CONST,
7254               .accessfn = access_aa64_tid3,
7255               .resetvalue = cpu->id_aa64afr0 },
7256             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7257               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7258               .access = PL1_R, .type = ARM_CP_CONST,
7259               .accessfn = access_aa64_tid3,
7260               .resetvalue = cpu->id_aa64afr1 },
7261             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7262               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7263               .access = PL1_R, .type = ARM_CP_CONST,
7264               .accessfn = access_aa64_tid3,
7265               .resetvalue = 0 },
7266             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7267               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7268               .access = PL1_R, .type = ARM_CP_CONST,
7269               .accessfn = access_aa64_tid3,
7270               .resetvalue = 0 },
7271             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7272               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7273               .access = PL1_R, .type = ARM_CP_CONST,
7274               .accessfn = access_aa64_tid3,
7275               .resetvalue = cpu->isar.id_aa64isar0 },
7276             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7277               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7278               .access = PL1_R, .type = ARM_CP_CONST,
7279               .accessfn = access_aa64_tid3,
7280               .resetvalue = cpu->isar.id_aa64isar1 },
7281             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7282               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7283               .access = PL1_R, .type = ARM_CP_CONST,
7284               .accessfn = access_aa64_tid3,
7285               .resetvalue = 0 },
7286             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7287               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7288               .access = PL1_R, .type = ARM_CP_CONST,
7289               .accessfn = access_aa64_tid3,
7290               .resetvalue = 0 },
7291             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7292               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7293               .access = PL1_R, .type = ARM_CP_CONST,
7294               .accessfn = access_aa64_tid3,
7295               .resetvalue = 0 },
7296             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7297               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7298               .access = PL1_R, .type = ARM_CP_CONST,
7299               .accessfn = access_aa64_tid3,
7300               .resetvalue = 0 },
7301             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7302               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7303               .access = PL1_R, .type = ARM_CP_CONST,
7304               .accessfn = access_aa64_tid3,
7305               .resetvalue = 0 },
7306             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7307               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7308               .access = PL1_R, .type = ARM_CP_CONST,
7309               .accessfn = access_aa64_tid3,
7310               .resetvalue = 0 },
7311             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7312               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7313               .access = PL1_R, .type = ARM_CP_CONST,
7314               .accessfn = access_aa64_tid3,
7315               .resetvalue = cpu->isar.id_aa64mmfr0 },
7316             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7317               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7318               .access = PL1_R, .type = ARM_CP_CONST,
7319               .accessfn = access_aa64_tid3,
7320               .resetvalue = cpu->isar.id_aa64mmfr1 },
7321             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7322               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7323               .access = PL1_R, .type = ARM_CP_CONST,
7324               .accessfn = access_aa64_tid3,
7325               .resetvalue = cpu->isar.id_aa64mmfr2 },
7326             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7327               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7328               .access = PL1_R, .type = ARM_CP_CONST,
7329               .accessfn = access_aa64_tid3,
7330               .resetvalue = 0 },
7331             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7332               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7333               .access = PL1_R, .type = ARM_CP_CONST,
7334               .accessfn = access_aa64_tid3,
7335               .resetvalue = 0 },
7336             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7337               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7338               .access = PL1_R, .type = ARM_CP_CONST,
7339               .accessfn = access_aa64_tid3,
7340               .resetvalue = 0 },
7341             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7342               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7343               .access = PL1_R, .type = ARM_CP_CONST,
7344               .accessfn = access_aa64_tid3,
7345               .resetvalue = 0 },
7346             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7347               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7348               .access = PL1_R, .type = ARM_CP_CONST,
7349               .accessfn = access_aa64_tid3,
7350               .resetvalue = 0 },
7351             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7352               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7353               .access = PL1_R, .type = ARM_CP_CONST,
7354               .accessfn = access_aa64_tid3,
7355               .resetvalue = cpu->isar.mvfr0 },
7356             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7357               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7358               .access = PL1_R, .type = ARM_CP_CONST,
7359               .accessfn = access_aa64_tid3,
7360               .resetvalue = cpu->isar.mvfr1 },
7361             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7362               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7363               .access = PL1_R, .type = ARM_CP_CONST,
7364               .accessfn = access_aa64_tid3,
7365               .resetvalue = cpu->isar.mvfr2 },
7366             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7367               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7368               .access = PL1_R, .type = ARM_CP_CONST,
7369               .accessfn = access_aa64_tid3,
7370               .resetvalue = 0 },
7371             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7372               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7373               .access = PL1_R, .type = ARM_CP_CONST,
7374               .accessfn = access_aa64_tid3,
7375               .resetvalue = 0 },
7376             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7377               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7378               .access = PL1_R, .type = ARM_CP_CONST,
7379               .accessfn = access_aa64_tid3,
7380               .resetvalue = 0 },
7381             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7382               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7383               .access = PL1_R, .type = ARM_CP_CONST,
7384               .accessfn = access_aa64_tid3,
7385               .resetvalue = 0 },
7386             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7387               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7388               .access = PL1_R, .type = ARM_CP_CONST,
7389               .accessfn = access_aa64_tid3,
7390               .resetvalue = 0 },
7391             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7392               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7393               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7394               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7395             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7396               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7397               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7398               .resetvalue = cpu->pmceid0 },
7399             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7400               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7401               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7402               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7403             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7404               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7405               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7406               .resetvalue = cpu->pmceid1 },
7407             REGINFO_SENTINEL
7408         };
7409 #ifdef CONFIG_USER_ONLY
7410         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7411             { .name = "ID_AA64PFR0_EL1",
7412               .exported_bits = 0x000f000f00ff0000,
7413               .fixed_bits    = 0x0000000000000011 },
7414             { .name = "ID_AA64PFR1_EL1",
7415               .exported_bits = 0x00000000000000f0 },
7416             { .name = "ID_AA64PFR*_EL1_RESERVED",
7417               .is_glob = true                     },
7418             { .name = "ID_AA64ZFR0_EL1"           },
7419             { .name = "ID_AA64MMFR0_EL1",
7420               .fixed_bits    = 0x00000000ff000000 },
7421             { .name = "ID_AA64MMFR1_EL1"          },
7422             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7423               .is_glob = true                     },
7424             { .name = "ID_AA64DFR0_EL1",
7425               .fixed_bits    = 0x0000000000000006 },
7426             { .name = "ID_AA64DFR1_EL1"           },
7427             { .name = "ID_AA64DFR*_EL1_RESERVED",
7428               .is_glob = true                     },
7429             { .name = "ID_AA64AFR*",
7430               .is_glob = true                     },
7431             { .name = "ID_AA64ISAR0_EL1",
7432               .exported_bits = 0x00fffffff0fffff0 },
7433             { .name = "ID_AA64ISAR1_EL1",
7434               .exported_bits = 0x000000f0ffffffff },
7435             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7436               .is_glob = true                     },
7437             REGUSERINFO_SENTINEL
7438         };
7439         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7440 #endif
7441         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7442         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7443             !arm_feature(env, ARM_FEATURE_EL2)) {
7444             ARMCPRegInfo rvbar = {
7445                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7446                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7447                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
7448             };
7449             define_one_arm_cp_reg(cpu, &rvbar);
7450         }
7451         define_arm_cp_regs(cpu, v8_idregs);
7452         define_arm_cp_regs(cpu, v8_cp_reginfo);
7453     }
7454     if (arm_feature(env, ARM_FEATURE_EL2)) {
7455         uint64_t vmpidr_def = mpidr_read_val(env);
7456         ARMCPRegInfo vpidr_regs[] = {
7457             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7458               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7459               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7460               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
7461               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7462             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7463               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7464               .access = PL2_RW, .resetvalue = cpu->midr,
7465               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7466             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7467               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7468               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7469               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
7470               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7471             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7472               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7473               .access = PL2_RW,
7474               .resetvalue = vmpidr_def,
7475               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7476             REGINFO_SENTINEL
7477         };
7478         define_arm_cp_regs(cpu, vpidr_regs);
7479         define_arm_cp_regs(cpu, el2_cp_reginfo);
7480         if (arm_feature(env, ARM_FEATURE_V8)) {
7481             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
7482         }
7483         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
7484         if (!arm_feature(env, ARM_FEATURE_EL3)) {
7485             ARMCPRegInfo rvbar = {
7486                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
7487                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
7488                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
7489             };
7490             define_one_arm_cp_reg(cpu, &rvbar);
7491         }
7492     } else {
7493         /* If EL2 is missing but higher ELs are enabled, we need to
7494          * register the no_el2 reginfos.
7495          */
7496         if (arm_feature(env, ARM_FEATURE_EL3)) {
7497             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
7498              * of MIDR_EL1 and MPIDR_EL1.
7499              */
7500             ARMCPRegInfo vpidr_regs[] = {
7501                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7502                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7503                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
7504                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
7505                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7506                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7507                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7508                   .access = PL2_RW, .accessfn = access_el3_aa32ns_aa64any,
7509                   .type = ARM_CP_NO_RAW,
7510                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
7511                 REGINFO_SENTINEL
7512             };
7513             define_arm_cp_regs(cpu, vpidr_regs);
7514             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
7515             if (arm_feature(env, ARM_FEATURE_V8)) {
7516                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
7517             }
7518         }
7519     }
7520     if (arm_feature(env, ARM_FEATURE_EL3)) {
7521         define_arm_cp_regs(cpu, el3_cp_reginfo);
7522         ARMCPRegInfo el3_regs[] = {
7523             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
7524               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
7525               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
7526             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
7527               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
7528               .access = PL3_RW,
7529               .raw_writefn = raw_write, .writefn = sctlr_write,
7530               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
7531               .resetvalue = cpu->reset_sctlr },
7532             REGINFO_SENTINEL
7533         };
7534 
7535         define_arm_cp_regs(cpu, el3_regs);
7536     }
7537     /* The behaviour of NSACR is sufficiently various that we don't
7538      * try to describe it in a single reginfo:
7539      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
7540      *     reads as constant 0xc00 from NS EL1 and NS EL2
7541      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
7542      *  if v7 without EL3, register doesn't exist
7543      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
7544      */
7545     if (arm_feature(env, ARM_FEATURE_EL3)) {
7546         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7547             ARMCPRegInfo nsacr = {
7548                 .name = "NSACR", .type = ARM_CP_CONST,
7549                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7550                 .access = PL1_RW, .accessfn = nsacr_access,
7551                 .resetvalue = 0xc00
7552             };
7553             define_one_arm_cp_reg(cpu, &nsacr);
7554         } else {
7555             ARMCPRegInfo nsacr = {
7556                 .name = "NSACR",
7557                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7558                 .access = PL3_RW | PL1_R,
7559                 .resetvalue = 0,
7560                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
7561             };
7562             define_one_arm_cp_reg(cpu, &nsacr);
7563         }
7564     } else {
7565         if (arm_feature(env, ARM_FEATURE_V8)) {
7566             ARMCPRegInfo nsacr = {
7567                 .name = "NSACR", .type = ARM_CP_CONST,
7568                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7569                 .access = PL1_R,
7570                 .resetvalue = 0xc00
7571             };
7572             define_one_arm_cp_reg(cpu, &nsacr);
7573         }
7574     }
7575 
7576     if (arm_feature(env, ARM_FEATURE_PMSA)) {
7577         if (arm_feature(env, ARM_FEATURE_V6)) {
7578             /* PMSAv6 not implemented */
7579             assert(arm_feature(env, ARM_FEATURE_V7));
7580             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7581             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
7582         } else {
7583             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
7584         }
7585     } else {
7586         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7587         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
7588         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
7589         if (cpu_isar_feature(aa32_hpd, cpu)) {
7590             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
7591         }
7592     }
7593     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
7594         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
7595     }
7596     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
7597         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
7598     }
7599     if (arm_feature(env, ARM_FEATURE_VAPA)) {
7600         define_arm_cp_regs(cpu, vapa_cp_reginfo);
7601     }
7602     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
7603         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
7604     }
7605     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
7606         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
7607     }
7608     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
7609         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
7610     }
7611     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
7612         define_arm_cp_regs(cpu, omap_cp_reginfo);
7613     }
7614     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
7615         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
7616     }
7617     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
7618         define_arm_cp_regs(cpu, xscale_cp_reginfo);
7619     }
7620     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
7621         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
7622     }
7623     if (arm_feature(env, ARM_FEATURE_LPAE)) {
7624         define_arm_cp_regs(cpu, lpae_cp_reginfo);
7625     }
7626     if (cpu_isar_feature(aa32_jazelle, cpu)) {
7627         define_arm_cp_regs(cpu, jazelle_regs);
7628     }
7629     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
7630      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
7631      * be read-only (ie write causes UNDEF exception).
7632      */
7633     {
7634         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
7635             /* Pre-v8 MIDR space.
7636              * Note that the MIDR isn't a simple constant register because
7637              * of the TI925 behaviour where writes to another register can
7638              * cause the MIDR value to change.
7639              *
7640              * Unimplemented registers in the c15 0 0 0 space default to
7641              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
7642              * and friends override accordingly.
7643              */
7644             { .name = "MIDR",
7645               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
7646               .access = PL1_R, .resetvalue = cpu->midr,
7647               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
7648               .readfn = midr_read,
7649               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7650               .type = ARM_CP_OVERRIDE },
7651             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
7652             { .name = "DUMMY",
7653               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
7654               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7655             { .name = "DUMMY",
7656               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
7657               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7658             { .name = "DUMMY",
7659               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
7660               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7661             { .name = "DUMMY",
7662               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
7663               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7664             { .name = "DUMMY",
7665               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
7666               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7667             REGINFO_SENTINEL
7668         };
7669         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
7670             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
7671               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
7672               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
7673               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7674               .readfn = midr_read },
7675             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
7676             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
7677               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
7678               .access = PL1_R, .resetvalue = cpu->midr },
7679             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
7680               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
7681               .access = PL1_R, .resetvalue = cpu->midr },
7682             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
7683               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
7684               .access = PL1_R,
7685               .accessfn = access_aa64_tid1,
7686               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
7687             REGINFO_SENTINEL
7688         };
7689         ARMCPRegInfo id_cp_reginfo[] = {
7690             /* These are common to v8 and pre-v8 */
7691             { .name = "CTR",
7692               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
7693               .access = PL1_R, .accessfn = ctr_el0_access,
7694               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
7695             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
7696               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
7697               .access = PL0_R, .accessfn = ctr_el0_access,
7698               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
7699             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
7700             { .name = "TCMTR",
7701               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
7702               .access = PL1_R,
7703               .accessfn = access_aa32_tid1,
7704               .type = ARM_CP_CONST, .resetvalue = 0 },
7705             REGINFO_SENTINEL
7706         };
7707         /* TLBTR is specific to VMSA */
7708         ARMCPRegInfo id_tlbtr_reginfo = {
7709               .name = "TLBTR",
7710               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
7711               .access = PL1_R,
7712               .accessfn = access_aa32_tid1,
7713               .type = ARM_CP_CONST, .resetvalue = 0,
7714         };
7715         /* MPUIR is specific to PMSA V6+ */
7716         ARMCPRegInfo id_mpuir_reginfo = {
7717               .name = "MPUIR",
7718               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
7719               .access = PL1_R, .type = ARM_CP_CONST,
7720               .resetvalue = cpu->pmsav7_dregion << 8
7721         };
7722         ARMCPRegInfo crn0_wi_reginfo = {
7723             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
7724             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
7725             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
7726         };
7727 #ifdef CONFIG_USER_ONLY
7728         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
7729             { .name = "MIDR_EL1",
7730               .exported_bits = 0x00000000ffffffff },
7731             { .name = "REVIDR_EL1"                },
7732             REGUSERINFO_SENTINEL
7733         };
7734         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
7735 #endif
7736         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
7737             arm_feature(env, ARM_FEATURE_STRONGARM)) {
7738             ARMCPRegInfo *r;
7739             /* Register the blanket "writes ignored" value first to cover the
7740              * whole space. Then update the specific ID registers to allow write
7741              * access, so that they ignore writes rather than causing them to
7742              * UNDEF.
7743              */
7744             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
7745             for (r = id_pre_v8_midr_cp_reginfo;
7746                  r->type != ARM_CP_SENTINEL; r++) {
7747                 r->access = PL1_RW;
7748             }
7749             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
7750                 r->access = PL1_RW;
7751             }
7752             id_mpuir_reginfo.access = PL1_RW;
7753             id_tlbtr_reginfo.access = PL1_RW;
7754         }
7755         if (arm_feature(env, ARM_FEATURE_V8)) {
7756             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
7757         } else {
7758             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
7759         }
7760         define_arm_cp_regs(cpu, id_cp_reginfo);
7761         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
7762             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
7763         } else if (arm_feature(env, ARM_FEATURE_V7)) {
7764             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
7765         }
7766     }
7767 
7768     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
7769         ARMCPRegInfo mpidr_cp_reginfo[] = {
7770             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
7771               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
7772               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
7773             REGINFO_SENTINEL
7774         };
7775 #ifdef CONFIG_USER_ONLY
7776         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
7777             { .name = "MPIDR_EL1",
7778               .fixed_bits = 0x0000000080000000 },
7779             REGUSERINFO_SENTINEL
7780         };
7781         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
7782 #endif
7783         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
7784     }
7785 
7786     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
7787         ARMCPRegInfo auxcr_reginfo[] = {
7788             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
7789               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
7790               .access = PL1_RW, .accessfn = access_tacr,
7791               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
7792             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
7793               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
7794               .access = PL2_RW, .type = ARM_CP_CONST,
7795               .resetvalue = 0 },
7796             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
7797               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
7798               .access = PL3_RW, .type = ARM_CP_CONST,
7799               .resetvalue = 0 },
7800             REGINFO_SENTINEL
7801         };
7802         define_arm_cp_regs(cpu, auxcr_reginfo);
7803         if (cpu_isar_feature(aa32_ac2, cpu)) {
7804             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
7805         }
7806     }
7807 
7808     if (arm_feature(env, ARM_FEATURE_CBAR)) {
7809         /*
7810          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
7811          * There are two flavours:
7812          *  (1) older 32-bit only cores have a simple 32-bit CBAR
7813          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
7814          *      32-bit register visible to AArch32 at a different encoding
7815          *      to the "flavour 1" register and with the bits rearranged to
7816          *      be able to squash a 64-bit address into the 32-bit view.
7817          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
7818          * in future if we support AArch32-only configs of some of the
7819          * AArch64 cores we might need to add a specific feature flag
7820          * to indicate cores with "flavour 2" CBAR.
7821          */
7822         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7823             /* 32 bit view is [31:18] 0...0 [43:32]. */
7824             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
7825                 | extract64(cpu->reset_cbar, 32, 12);
7826             ARMCPRegInfo cbar_reginfo[] = {
7827                 { .name = "CBAR",
7828                   .type = ARM_CP_CONST,
7829                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
7830                   .access = PL1_R, .resetvalue = cbar32 },
7831                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
7832                   .type = ARM_CP_CONST,
7833                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
7834                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
7835                 REGINFO_SENTINEL
7836             };
7837             /* We don't implement a r/w 64 bit CBAR currently */
7838             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
7839             define_arm_cp_regs(cpu, cbar_reginfo);
7840         } else {
7841             ARMCPRegInfo cbar = {
7842                 .name = "CBAR",
7843                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
7844                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
7845                 .fieldoffset = offsetof(CPUARMState,
7846                                         cp15.c15_config_base_address)
7847             };
7848             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
7849                 cbar.access = PL1_R;
7850                 cbar.fieldoffset = 0;
7851                 cbar.type = ARM_CP_CONST;
7852             }
7853             define_one_arm_cp_reg(cpu, &cbar);
7854         }
7855     }
7856 
7857     if (arm_feature(env, ARM_FEATURE_VBAR)) {
7858         ARMCPRegInfo vbar_cp_reginfo[] = {
7859             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
7860               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
7861               .access = PL1_RW, .writefn = vbar_write,
7862               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
7863                                      offsetof(CPUARMState, cp15.vbar_ns) },
7864               .resetvalue = 0 },
7865             REGINFO_SENTINEL
7866         };
7867         define_arm_cp_regs(cpu, vbar_cp_reginfo);
7868     }
7869 
7870     /* Generic registers whose values depend on the implementation */
7871     {
7872         ARMCPRegInfo sctlr = {
7873             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
7874             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
7875             .access = PL1_RW, .accessfn = access_tvm_trvm,
7876             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
7877                                    offsetof(CPUARMState, cp15.sctlr_ns) },
7878             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
7879             .raw_writefn = raw_write,
7880         };
7881         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
7882             /* Normally we would always end the TB on an SCTLR write, but Linux
7883              * arch/arm/mach-pxa/sleep.S expects two instructions following
7884              * an MMU enable to execute from cache.  Imitate this behaviour.
7885              */
7886             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
7887         }
7888         define_one_arm_cp_reg(cpu, &sctlr);
7889     }
7890 
7891     if (cpu_isar_feature(aa64_lor, cpu)) {
7892         define_arm_cp_regs(cpu, lor_reginfo);
7893     }
7894     if (cpu_isar_feature(aa64_pan, cpu)) {
7895         define_one_arm_cp_reg(cpu, &pan_reginfo);
7896     }
7897 #ifndef CONFIG_USER_ONLY
7898     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
7899         define_arm_cp_regs(cpu, ats1e1_reginfo);
7900     }
7901     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
7902         define_arm_cp_regs(cpu, ats1cp_reginfo);
7903     }
7904 #endif
7905     if (cpu_isar_feature(aa64_uao, cpu)) {
7906         define_one_arm_cp_reg(cpu, &uao_reginfo);
7907     }
7908 
7909     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
7910         define_arm_cp_regs(cpu, vhe_reginfo);
7911     }
7912 
7913     if (cpu_isar_feature(aa64_sve, cpu)) {
7914         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
7915         if (arm_feature(env, ARM_FEATURE_EL2)) {
7916             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
7917         } else {
7918             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
7919         }
7920         if (arm_feature(env, ARM_FEATURE_EL3)) {
7921             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
7922         }
7923     }
7924 
7925 #ifdef TARGET_AARCH64
7926     if (cpu_isar_feature(aa64_pauth, cpu)) {
7927         define_arm_cp_regs(cpu, pauth_reginfo);
7928     }
7929     if (cpu_isar_feature(aa64_rndr, cpu)) {
7930         define_arm_cp_regs(cpu, rndr_reginfo);
7931     }
7932 #ifndef CONFIG_USER_ONLY
7933     /* Data Cache clean instructions up to PoP */
7934     if (cpu_isar_feature(aa64_dcpop, cpu)) {
7935         define_one_arm_cp_reg(cpu, dcpop_reg);
7936 
7937         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
7938             define_one_arm_cp_reg(cpu, dcpodp_reg);
7939         }
7940     }
7941 #endif /*CONFIG_USER_ONLY*/
7942 #endif
7943 
7944     if (cpu_isar_feature(any_predinv, cpu)) {
7945         define_arm_cp_regs(cpu, predinv_reginfo);
7946     }
7947 
7948     if (cpu_isar_feature(any_ccidx, cpu)) {
7949         define_arm_cp_regs(cpu, ccsidr2_reginfo);
7950     }
7951 
7952 #ifndef CONFIG_USER_ONLY
7953     /*
7954      * Register redirections and aliases must be done last,
7955      * after the registers from the other extensions have been defined.
7956      */
7957     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
7958         define_arm_vh_e2h_redirects_aliases(cpu);
7959     }
7960 #endif
7961 }
7962 
7963 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
7964 {
7965     CPUState *cs = CPU(cpu);
7966     CPUARMState *env = &cpu->env;
7967 
7968     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7969         gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
7970                                  aarch64_fpu_gdb_set_reg,
7971                                  34, "aarch64-fpu.xml", 0);
7972     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
7973         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
7974                                  51, "arm-neon.xml", 0);
7975     } else if (cpu_isar_feature(aa32_simd_r32, cpu)) {
7976         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
7977                                  35, "arm-vfp3.xml", 0);
7978     } else if (cpu_isar_feature(aa32_vfp_simd, cpu)) {
7979         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
7980                                  19, "arm-vfp.xml", 0);
7981     }
7982     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
7983                              arm_gen_dynamic_xml(cs),
7984                              "system-registers.xml", 0);
7985 }
7986 
7987 /* Sort alphabetically by type name, except for "any". */
7988 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
7989 {
7990     ObjectClass *class_a = (ObjectClass *)a;
7991     ObjectClass *class_b = (ObjectClass *)b;
7992     const char *name_a, *name_b;
7993 
7994     name_a = object_class_get_name(class_a);
7995     name_b = object_class_get_name(class_b);
7996     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
7997         return 1;
7998     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
7999         return -1;
8000     } else {
8001         return strcmp(name_a, name_b);
8002     }
8003 }
8004 
8005 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8006 {
8007     ObjectClass *oc = data;
8008     const char *typename;
8009     char *name;
8010 
8011     typename = object_class_get_name(oc);
8012     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8013     qemu_printf("  %s\n", name);
8014     g_free(name);
8015 }
8016 
8017 void arm_cpu_list(void)
8018 {
8019     GSList *list;
8020 
8021     list = object_class_get_list(TYPE_ARM_CPU, false);
8022     list = g_slist_sort(list, arm_cpu_list_compare);
8023     qemu_printf("Available CPUs:\n");
8024     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8025     g_slist_free(list);
8026 }
8027 
8028 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8029 {
8030     ObjectClass *oc = data;
8031     CpuDefinitionInfoList **cpu_list = user_data;
8032     CpuDefinitionInfoList *entry;
8033     CpuDefinitionInfo *info;
8034     const char *typename;
8035 
8036     typename = object_class_get_name(oc);
8037     info = g_malloc0(sizeof(*info));
8038     info->name = g_strndup(typename,
8039                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8040     info->q_typename = g_strdup(typename);
8041 
8042     entry = g_malloc0(sizeof(*entry));
8043     entry->value = info;
8044     entry->next = *cpu_list;
8045     *cpu_list = entry;
8046 }
8047 
8048 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8049 {
8050     CpuDefinitionInfoList *cpu_list = NULL;
8051     GSList *list;
8052 
8053     list = object_class_get_list(TYPE_ARM_CPU, false);
8054     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8055     g_slist_free(list);
8056 
8057     return cpu_list;
8058 }
8059 
8060 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8061                                    void *opaque, int state, int secstate,
8062                                    int crm, int opc1, int opc2,
8063                                    const char *name)
8064 {
8065     /* Private utility function for define_one_arm_cp_reg_with_opaque():
8066      * add a single reginfo struct to the hash table.
8067      */
8068     uint32_t *key = g_new(uint32_t, 1);
8069     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
8070     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
8071     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
8072 
8073     r2->name = g_strdup(name);
8074     /* Reset the secure state to the specific incoming state.  This is
8075      * necessary as the register may have been defined with both states.
8076      */
8077     r2->secure = secstate;
8078 
8079     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8080         /* Register is banked (using both entries in array).
8081          * Overwriting fieldoffset as the array is only used to define
8082          * banked registers but later only fieldoffset is used.
8083          */
8084         r2->fieldoffset = r->bank_fieldoffsets[ns];
8085     }
8086 
8087     if (state == ARM_CP_STATE_AA32) {
8088         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8089             /* If the register is banked then we don't need to migrate or
8090              * reset the 32-bit instance in certain cases:
8091              *
8092              * 1) If the register has both 32-bit and 64-bit instances then we
8093              *    can count on the 64-bit instance taking care of the
8094              *    non-secure bank.
8095              * 2) If ARMv8 is enabled then we can count on a 64-bit version
8096              *    taking care of the secure bank.  This requires that separate
8097              *    32 and 64-bit definitions are provided.
8098              */
8099             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8100                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
8101                 r2->type |= ARM_CP_ALIAS;
8102             }
8103         } else if ((secstate != r->secure) && !ns) {
8104             /* The register is not banked so we only want to allow migration of
8105              * the non-secure instance.
8106              */
8107             r2->type |= ARM_CP_ALIAS;
8108         }
8109 
8110         if (r->state == ARM_CP_STATE_BOTH) {
8111             /* We assume it is a cp15 register if the .cp field is left unset.
8112              */
8113             if (r2->cp == 0) {
8114                 r2->cp = 15;
8115             }
8116 
8117 #ifdef HOST_WORDS_BIGENDIAN
8118             if (r2->fieldoffset) {
8119                 r2->fieldoffset += sizeof(uint32_t);
8120             }
8121 #endif
8122         }
8123     }
8124     if (state == ARM_CP_STATE_AA64) {
8125         /* To allow abbreviation of ARMCPRegInfo
8126          * definitions, we treat cp == 0 as equivalent to
8127          * the value for "standard guest-visible sysreg".
8128          * STATE_BOTH definitions are also always "standard
8129          * sysreg" in their AArch64 view (the .cp value may
8130          * be non-zero for the benefit of the AArch32 view).
8131          */
8132         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8133             r2->cp = CP_REG_ARM64_SYSREG_CP;
8134         }
8135         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
8136                                   r2->opc0, opc1, opc2);
8137     } else {
8138         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
8139     }
8140     if (opaque) {
8141         r2->opaque = opaque;
8142     }
8143     /* reginfo passed to helpers is correct for the actual access,
8144      * and is never ARM_CP_STATE_BOTH:
8145      */
8146     r2->state = state;
8147     /* Make sure reginfo passed to helpers for wildcarded regs
8148      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
8149      */
8150     r2->crm = crm;
8151     r2->opc1 = opc1;
8152     r2->opc2 = opc2;
8153     /* By convention, for wildcarded registers only the first
8154      * entry is used for migration; the others are marked as
8155      * ALIAS so we don't try to transfer the register
8156      * multiple times. Special registers (ie NOP/WFI) are
8157      * never migratable and not even raw-accessible.
8158      */
8159     if ((r->type & ARM_CP_SPECIAL)) {
8160         r2->type |= ARM_CP_NO_RAW;
8161     }
8162     if (((r->crm == CP_ANY) && crm != 0) ||
8163         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8164         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8165         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8166     }
8167 
8168     /* Check that raw accesses are either forbidden or handled. Note that
8169      * we can't assert this earlier because the setup of fieldoffset for
8170      * banked registers has to be done first.
8171      */
8172     if (!(r2->type & ARM_CP_NO_RAW)) {
8173         assert(!raw_accessors_invalid(r2));
8174     }
8175 
8176     /* Overriding of an existing definition must be explicitly
8177      * requested.
8178      */
8179     if (!(r->type & ARM_CP_OVERRIDE)) {
8180         ARMCPRegInfo *oldreg;
8181         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
8182         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
8183             fprintf(stderr, "Register redefined: cp=%d %d bit "
8184                     "crn=%d crm=%d opc1=%d opc2=%d, "
8185                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
8186                     r2->crn, r2->crm, r2->opc1, r2->opc2,
8187                     oldreg->name, r2->name);
8188             g_assert_not_reached();
8189         }
8190     }
8191     g_hash_table_insert(cpu->cp_regs, key, r2);
8192 }
8193 
8194 
8195 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8196                                        const ARMCPRegInfo *r, void *opaque)
8197 {
8198     /* Define implementations of coprocessor registers.
8199      * We store these in a hashtable because typically
8200      * there are less than 150 registers in a space which
8201      * is 16*16*16*8*8 = 262144 in size.
8202      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8203      * If a register is defined twice then the second definition is
8204      * used, so this can be used to define some generic registers and
8205      * then override them with implementation specific variations.
8206      * At least one of the original and the second definition should
8207      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8208      * against accidental use.
8209      *
8210      * The state field defines whether the register is to be
8211      * visible in the AArch32 or AArch64 execution state. If the
8212      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8213      * reginfo structure for the AArch32 view, which sees the lower
8214      * 32 bits of the 64 bit register.
8215      *
8216      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8217      * be wildcarded. AArch64 registers are always considered to be 64
8218      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8219      * the register, if any.
8220      */
8221     int crm, opc1, opc2, state;
8222     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8223     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8224     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8225     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8226     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8227     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8228     /* 64 bit registers have only CRm and Opc1 fields */
8229     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8230     /* op0 only exists in the AArch64 encodings */
8231     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8232     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8233     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8234     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8235      * encodes a minimum access level for the register. We roll this
8236      * runtime check into our general permission check code, so check
8237      * here that the reginfo's specified permissions are strict enough
8238      * to encompass the generic architectural permission check.
8239      */
8240     if (r->state != ARM_CP_STATE_AA32) {
8241         int mask = 0;
8242         switch (r->opc1) {
8243         case 0:
8244             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8245             mask = PL0U_R | PL1_RW;
8246             break;
8247         case 1: case 2:
8248             /* min_EL EL1 */
8249             mask = PL1_RW;
8250             break;
8251         case 3:
8252             /* min_EL EL0 */
8253             mask = PL0_RW;
8254             break;
8255         case 4:
8256         case 5:
8257             /* min_EL EL2 */
8258             mask = PL2_RW;
8259             break;
8260         case 6:
8261             /* min_EL EL3 */
8262             mask = PL3_RW;
8263             break;
8264         case 7:
8265             /* min_EL EL1, secure mode only (we don't check the latter) */
8266             mask = PL1_RW;
8267             break;
8268         default:
8269             /* broken reginfo with out-of-range opc1 */
8270             assert(false);
8271             break;
8272         }
8273         /* assert our permissions are not too lax (stricter is fine) */
8274         assert((r->access & ~mask) == 0);
8275     }
8276 
8277     /* Check that the register definition has enough info to handle
8278      * reads and writes if they are permitted.
8279      */
8280     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
8281         if (r->access & PL3_R) {
8282             assert((r->fieldoffset ||
8283                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8284                    r->readfn);
8285         }
8286         if (r->access & PL3_W) {
8287             assert((r->fieldoffset ||
8288                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8289                    r->writefn);
8290         }
8291     }
8292     /* Bad type field probably means missing sentinel at end of reg list */
8293     assert(cptype_valid(r->type));
8294     for (crm = crmmin; crm <= crmmax; crm++) {
8295         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8296             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8297                 for (state = ARM_CP_STATE_AA32;
8298                      state <= ARM_CP_STATE_AA64; state++) {
8299                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8300                         continue;
8301                     }
8302                     if (state == ARM_CP_STATE_AA32) {
8303                         /* Under AArch32 CP registers can be common
8304                          * (same for secure and non-secure world) or banked.
8305                          */
8306                         char *name;
8307 
8308                         switch (r->secure) {
8309                         case ARM_CP_SECSTATE_S:
8310                         case ARM_CP_SECSTATE_NS:
8311                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8312                                                    r->secure, crm, opc1, opc2,
8313                                                    r->name);
8314                             break;
8315                         default:
8316                             name = g_strdup_printf("%s_S", r->name);
8317                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8318                                                    ARM_CP_SECSTATE_S,
8319                                                    crm, opc1, opc2, name);
8320                             g_free(name);
8321                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8322                                                    ARM_CP_SECSTATE_NS,
8323                                                    crm, opc1, opc2, r->name);
8324                             break;
8325                         }
8326                     } else {
8327                         /* AArch64 registers get mapped to non-secure instance
8328                          * of AArch32 */
8329                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8330                                                ARM_CP_SECSTATE_NS,
8331                                                crm, opc1, opc2, r->name);
8332                     }
8333                 }
8334             }
8335         }
8336     }
8337 }
8338 
8339 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
8340                                     const ARMCPRegInfo *regs, void *opaque)
8341 {
8342     /* Define a whole list of registers */
8343     const ARMCPRegInfo *r;
8344     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8345         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
8346     }
8347 }
8348 
8349 /*
8350  * Modify ARMCPRegInfo for access from userspace.
8351  *
8352  * This is a data driven modification directed by
8353  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8354  * user-space cannot alter any values and dynamic values pertaining to
8355  * execution state are hidden from user space view anyway.
8356  */
8357 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
8358 {
8359     const ARMCPRegUserSpaceInfo *m;
8360     ARMCPRegInfo *r;
8361 
8362     for (m = mods; m->name; m++) {
8363         GPatternSpec *pat = NULL;
8364         if (m->is_glob) {
8365             pat = g_pattern_spec_new(m->name);
8366         }
8367         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8368             if (pat && g_pattern_match_string(pat, r->name)) {
8369                 r->type = ARM_CP_CONST;
8370                 r->access = PL0U_R;
8371                 r->resetvalue = 0;
8372                 /* continue */
8373             } else if (strcmp(r->name, m->name) == 0) {
8374                 r->type = ARM_CP_CONST;
8375                 r->access = PL0U_R;
8376                 r->resetvalue &= m->exported_bits;
8377                 r->resetvalue |= m->fixed_bits;
8378                 break;
8379             }
8380         }
8381         if (pat) {
8382             g_pattern_spec_free(pat);
8383         }
8384     }
8385 }
8386 
8387 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8388 {
8389     return g_hash_table_lookup(cpregs, &encoded_cp);
8390 }
8391 
8392 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8393                          uint64_t value)
8394 {
8395     /* Helper coprocessor write function for write-ignore registers */
8396 }
8397 
8398 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8399 {
8400     /* Helper coprocessor write function for read-as-zero registers */
8401     return 0;
8402 }
8403 
8404 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8405 {
8406     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8407 }
8408 
8409 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8410 {
8411     /* Return true if it is not valid for us to switch to
8412      * this CPU mode (ie all the UNPREDICTABLE cases in
8413      * the ARM ARM CPSRWriteByInstr pseudocode).
8414      */
8415 
8416     /* Changes to or from Hyp via MSR and CPS are illegal. */
8417     if (write_type == CPSRWriteByInstr &&
8418         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8419          mode == ARM_CPU_MODE_HYP)) {
8420         return 1;
8421     }
8422 
8423     switch (mode) {
8424     case ARM_CPU_MODE_USR:
8425         return 0;
8426     case ARM_CPU_MODE_SYS:
8427     case ARM_CPU_MODE_SVC:
8428     case ARM_CPU_MODE_ABT:
8429     case ARM_CPU_MODE_UND:
8430     case ARM_CPU_MODE_IRQ:
8431     case ARM_CPU_MODE_FIQ:
8432         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
8433          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
8434          */
8435         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
8436          * and CPS are treated as illegal mode changes.
8437          */
8438         if (write_type == CPSRWriteByInstr &&
8439             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
8440             (arm_hcr_el2_eff(env) & HCR_TGE)) {
8441             return 1;
8442         }
8443         return 0;
8444     case ARM_CPU_MODE_HYP:
8445         return !arm_feature(env, ARM_FEATURE_EL2)
8446             || arm_current_el(env) < 2 || arm_is_secure_below_el3(env);
8447     case ARM_CPU_MODE_MON:
8448         return arm_current_el(env) < 3;
8449     default:
8450         return 1;
8451     }
8452 }
8453 
8454 uint32_t cpsr_read(CPUARMState *env)
8455 {
8456     int ZF;
8457     ZF = (env->ZF == 0);
8458     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
8459         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
8460         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
8461         | ((env->condexec_bits & 0xfc) << 8)
8462         | (env->GE << 16) | (env->daif & CPSR_AIF);
8463 }
8464 
8465 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
8466                 CPSRWriteType write_type)
8467 {
8468     uint32_t changed_daif;
8469 
8470     if (mask & CPSR_NZCV) {
8471         env->ZF = (~val) & CPSR_Z;
8472         env->NF = val;
8473         env->CF = (val >> 29) & 1;
8474         env->VF = (val << 3) & 0x80000000;
8475     }
8476     if (mask & CPSR_Q)
8477         env->QF = ((val & CPSR_Q) != 0);
8478     if (mask & CPSR_T)
8479         env->thumb = ((val & CPSR_T) != 0);
8480     if (mask & CPSR_IT_0_1) {
8481         env->condexec_bits &= ~3;
8482         env->condexec_bits |= (val >> 25) & 3;
8483     }
8484     if (mask & CPSR_IT_2_7) {
8485         env->condexec_bits &= 3;
8486         env->condexec_bits |= (val >> 8) & 0xfc;
8487     }
8488     if (mask & CPSR_GE) {
8489         env->GE = (val >> 16) & 0xf;
8490     }
8491 
8492     /* In a V7 implementation that includes the security extensions but does
8493      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
8494      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
8495      * bits respectively.
8496      *
8497      * In a V8 implementation, it is permitted for privileged software to
8498      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
8499      */
8500     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
8501         arm_feature(env, ARM_FEATURE_EL3) &&
8502         !arm_feature(env, ARM_FEATURE_EL2) &&
8503         !arm_is_secure(env)) {
8504 
8505         changed_daif = (env->daif ^ val) & mask;
8506 
8507         if (changed_daif & CPSR_A) {
8508             /* Check to see if we are allowed to change the masking of async
8509              * abort exceptions from a non-secure state.
8510              */
8511             if (!(env->cp15.scr_el3 & SCR_AW)) {
8512                 qemu_log_mask(LOG_GUEST_ERROR,
8513                               "Ignoring attempt to switch CPSR_A flag from "
8514                               "non-secure world with SCR.AW bit clear\n");
8515                 mask &= ~CPSR_A;
8516             }
8517         }
8518 
8519         if (changed_daif & CPSR_F) {
8520             /* Check to see if we are allowed to change the masking of FIQ
8521              * exceptions from a non-secure state.
8522              */
8523             if (!(env->cp15.scr_el3 & SCR_FW)) {
8524                 qemu_log_mask(LOG_GUEST_ERROR,
8525                               "Ignoring attempt to switch CPSR_F flag from "
8526                               "non-secure world with SCR.FW bit clear\n");
8527                 mask &= ~CPSR_F;
8528             }
8529 
8530             /* Check whether non-maskable FIQ (NMFI) support is enabled.
8531              * If this bit is set software is not allowed to mask
8532              * FIQs, but is allowed to set CPSR_F to 0.
8533              */
8534             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
8535                 (val & CPSR_F)) {
8536                 qemu_log_mask(LOG_GUEST_ERROR,
8537                               "Ignoring attempt to enable CPSR_F flag "
8538                               "(non-maskable FIQ [NMFI] support enabled)\n");
8539                 mask &= ~CPSR_F;
8540             }
8541         }
8542     }
8543 
8544     env->daif &= ~(CPSR_AIF & mask);
8545     env->daif |= val & CPSR_AIF & mask;
8546 
8547     if (write_type != CPSRWriteRaw &&
8548         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
8549         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
8550             /* Note that we can only get here in USR mode if this is a
8551              * gdb stub write; for this case we follow the architectural
8552              * behaviour for guest writes in USR mode of ignoring an attempt
8553              * to switch mode. (Those are caught by translate.c for writes
8554              * triggered by guest instructions.)
8555              */
8556             mask &= ~CPSR_M;
8557         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
8558             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
8559              * v7, and has defined behaviour in v8:
8560              *  + leave CPSR.M untouched
8561              *  + allow changes to the other CPSR fields
8562              *  + set PSTATE.IL
8563              * For user changes via the GDB stub, we don't set PSTATE.IL,
8564              * as this would be unnecessarily harsh for a user error.
8565              */
8566             mask &= ~CPSR_M;
8567             if (write_type != CPSRWriteByGDBStub &&
8568                 arm_feature(env, ARM_FEATURE_V8)) {
8569                 mask |= CPSR_IL;
8570                 val |= CPSR_IL;
8571             }
8572             qemu_log_mask(LOG_GUEST_ERROR,
8573                           "Illegal AArch32 mode switch attempt from %s to %s\n",
8574                           aarch32_mode_name(env->uncached_cpsr),
8575                           aarch32_mode_name(val));
8576         } else {
8577             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
8578                           write_type == CPSRWriteExceptionReturn ?
8579                           "Exception return from AArch32" :
8580                           "AArch32 mode switch from",
8581                           aarch32_mode_name(env->uncached_cpsr),
8582                           aarch32_mode_name(val), env->regs[15]);
8583             switch_mode(env, val & CPSR_M);
8584         }
8585     }
8586     mask &= ~CACHED_CPSR_BITS;
8587     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
8588 }
8589 
8590 /* Sign/zero extend */
8591 uint32_t HELPER(sxtb16)(uint32_t x)
8592 {
8593     uint32_t res;
8594     res = (uint16_t)(int8_t)x;
8595     res |= (uint32_t)(int8_t)(x >> 16) << 16;
8596     return res;
8597 }
8598 
8599 uint32_t HELPER(uxtb16)(uint32_t x)
8600 {
8601     uint32_t res;
8602     res = (uint16_t)(uint8_t)x;
8603     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
8604     return res;
8605 }
8606 
8607 int32_t HELPER(sdiv)(int32_t num, int32_t den)
8608 {
8609     if (den == 0)
8610       return 0;
8611     if (num == INT_MIN && den == -1)
8612       return INT_MIN;
8613     return num / den;
8614 }
8615 
8616 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
8617 {
8618     if (den == 0)
8619       return 0;
8620     return num / den;
8621 }
8622 
8623 uint32_t HELPER(rbit)(uint32_t x)
8624 {
8625     return revbit32(x);
8626 }
8627 
8628 #ifdef CONFIG_USER_ONLY
8629 
8630 static void switch_mode(CPUARMState *env, int mode)
8631 {
8632     ARMCPU *cpu = env_archcpu(env);
8633 
8634     if (mode != ARM_CPU_MODE_USR) {
8635         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
8636     }
8637 }
8638 
8639 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
8640                                  uint32_t cur_el, bool secure)
8641 {
8642     return 1;
8643 }
8644 
8645 void aarch64_sync_64_to_32(CPUARMState *env)
8646 {
8647     g_assert_not_reached();
8648 }
8649 
8650 #else
8651 
8652 static void switch_mode(CPUARMState *env, int mode)
8653 {
8654     int old_mode;
8655     int i;
8656 
8657     old_mode = env->uncached_cpsr & CPSR_M;
8658     if (mode == old_mode)
8659         return;
8660 
8661     if (old_mode == ARM_CPU_MODE_FIQ) {
8662         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
8663         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
8664     } else if (mode == ARM_CPU_MODE_FIQ) {
8665         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
8666         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
8667     }
8668 
8669     i = bank_number(old_mode);
8670     env->banked_r13[i] = env->regs[13];
8671     env->banked_spsr[i] = env->spsr;
8672 
8673     i = bank_number(mode);
8674     env->regs[13] = env->banked_r13[i];
8675     env->spsr = env->banked_spsr[i];
8676 
8677     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
8678     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
8679 }
8680 
8681 /* Physical Interrupt Target EL Lookup Table
8682  *
8683  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
8684  *
8685  * The below multi-dimensional table is used for looking up the target
8686  * exception level given numerous condition criteria.  Specifically, the
8687  * target EL is based on SCR and HCR routing controls as well as the
8688  * currently executing EL and secure state.
8689  *
8690  *    Dimensions:
8691  *    target_el_table[2][2][2][2][2][4]
8692  *                    |  |  |  |  |  +--- Current EL
8693  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
8694  *                    |  |  |  +--------- HCR mask override
8695  *                    |  |  +------------ SCR exec state control
8696  *                    |  +--------------- SCR mask override
8697  *                    +------------------ 32-bit(0)/64-bit(1) EL3
8698  *
8699  *    The table values are as such:
8700  *    0-3 = EL0-EL3
8701  *     -1 = Cannot occur
8702  *
8703  * The ARM ARM target EL table includes entries indicating that an "exception
8704  * is not taken".  The two cases where this is applicable are:
8705  *    1) An exception is taken from EL3 but the SCR does not have the exception
8706  *    routed to EL3.
8707  *    2) An exception is taken from EL2 but the HCR does not have the exception
8708  *    routed to EL2.
8709  * In these two cases, the below table contain a target of EL1.  This value is
8710  * returned as it is expected that the consumer of the table data will check
8711  * for "target EL >= current EL" to ensure the exception is not taken.
8712  *
8713  *            SCR     HCR
8714  *         64  EA     AMO                 From
8715  *        BIT IRQ     IMO      Non-secure         Secure
8716  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
8717  */
8718 static const int8_t target_el_table[2][2][2][2][2][4] = {
8719     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
8720        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
8721       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
8722        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
8723      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
8724        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
8725       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
8726        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
8727     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
8728        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
8729       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
8730        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
8731      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
8732        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
8733       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
8734        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
8735 };
8736 
8737 /*
8738  * Determine the target EL for physical exceptions
8739  */
8740 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
8741                                  uint32_t cur_el, bool secure)
8742 {
8743     CPUARMState *env = cs->env_ptr;
8744     bool rw;
8745     bool scr;
8746     bool hcr;
8747     int target_el;
8748     /* Is the highest EL AArch64? */
8749     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
8750     uint64_t hcr_el2;
8751 
8752     if (arm_feature(env, ARM_FEATURE_EL3)) {
8753         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
8754     } else {
8755         /* Either EL2 is the highest EL (and so the EL2 register width
8756          * is given by is64); or there is no EL2 or EL3, in which case
8757          * the value of 'rw' does not affect the table lookup anyway.
8758          */
8759         rw = is64;
8760     }
8761 
8762     hcr_el2 = arm_hcr_el2_eff(env);
8763     switch (excp_idx) {
8764     case EXCP_IRQ:
8765         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
8766         hcr = hcr_el2 & HCR_IMO;
8767         break;
8768     case EXCP_FIQ:
8769         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
8770         hcr = hcr_el2 & HCR_FMO;
8771         break;
8772     default:
8773         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
8774         hcr = hcr_el2 & HCR_AMO;
8775         break;
8776     };
8777 
8778     /*
8779      * For these purposes, TGE and AMO/IMO/FMO both force the
8780      * interrupt to EL2.  Fold TGE into the bit extracted above.
8781      */
8782     hcr |= (hcr_el2 & HCR_TGE) != 0;
8783 
8784     /* Perform a table-lookup for the target EL given the current state */
8785     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
8786 
8787     assert(target_el > 0);
8788 
8789     return target_el;
8790 }
8791 
8792 void arm_log_exception(int idx)
8793 {
8794     if (qemu_loglevel_mask(CPU_LOG_INT)) {
8795         const char *exc = NULL;
8796         static const char * const excnames[] = {
8797             [EXCP_UDEF] = "Undefined Instruction",
8798             [EXCP_SWI] = "SVC",
8799             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
8800             [EXCP_DATA_ABORT] = "Data Abort",
8801             [EXCP_IRQ] = "IRQ",
8802             [EXCP_FIQ] = "FIQ",
8803             [EXCP_BKPT] = "Breakpoint",
8804             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
8805             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
8806             [EXCP_HVC] = "Hypervisor Call",
8807             [EXCP_HYP_TRAP] = "Hypervisor Trap",
8808             [EXCP_SMC] = "Secure Monitor Call",
8809             [EXCP_VIRQ] = "Virtual IRQ",
8810             [EXCP_VFIQ] = "Virtual FIQ",
8811             [EXCP_SEMIHOST] = "Semihosting call",
8812             [EXCP_NOCP] = "v7M NOCP UsageFault",
8813             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
8814             [EXCP_STKOF] = "v8M STKOF UsageFault",
8815             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
8816             [EXCP_LSERR] = "v8M LSERR UsageFault",
8817             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
8818         };
8819 
8820         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
8821             exc = excnames[idx];
8822         }
8823         if (!exc) {
8824             exc = "unknown";
8825         }
8826         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
8827     }
8828 }
8829 
8830 /*
8831  * Function used to synchronize QEMU's AArch64 register set with AArch32
8832  * register set.  This is necessary when switching between AArch32 and AArch64
8833  * execution state.
8834  */
8835 void aarch64_sync_32_to_64(CPUARMState *env)
8836 {
8837     int i;
8838     uint32_t mode = env->uncached_cpsr & CPSR_M;
8839 
8840     /* We can blanket copy R[0:7] to X[0:7] */
8841     for (i = 0; i < 8; i++) {
8842         env->xregs[i] = env->regs[i];
8843     }
8844 
8845     /*
8846      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
8847      * Otherwise, they come from the banked user regs.
8848      */
8849     if (mode == ARM_CPU_MODE_FIQ) {
8850         for (i = 8; i < 13; i++) {
8851             env->xregs[i] = env->usr_regs[i - 8];
8852         }
8853     } else {
8854         for (i = 8; i < 13; i++) {
8855             env->xregs[i] = env->regs[i];
8856         }
8857     }
8858 
8859     /*
8860      * Registers x13-x23 are the various mode SP and FP registers. Registers
8861      * r13 and r14 are only copied if we are in that mode, otherwise we copy
8862      * from the mode banked register.
8863      */
8864     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
8865         env->xregs[13] = env->regs[13];
8866         env->xregs[14] = env->regs[14];
8867     } else {
8868         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
8869         /* HYP is an exception in that it is copied from r14 */
8870         if (mode == ARM_CPU_MODE_HYP) {
8871             env->xregs[14] = env->regs[14];
8872         } else {
8873             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
8874         }
8875     }
8876 
8877     if (mode == ARM_CPU_MODE_HYP) {
8878         env->xregs[15] = env->regs[13];
8879     } else {
8880         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
8881     }
8882 
8883     if (mode == ARM_CPU_MODE_IRQ) {
8884         env->xregs[16] = env->regs[14];
8885         env->xregs[17] = env->regs[13];
8886     } else {
8887         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
8888         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
8889     }
8890 
8891     if (mode == ARM_CPU_MODE_SVC) {
8892         env->xregs[18] = env->regs[14];
8893         env->xregs[19] = env->regs[13];
8894     } else {
8895         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
8896         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
8897     }
8898 
8899     if (mode == ARM_CPU_MODE_ABT) {
8900         env->xregs[20] = env->regs[14];
8901         env->xregs[21] = env->regs[13];
8902     } else {
8903         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
8904         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
8905     }
8906 
8907     if (mode == ARM_CPU_MODE_UND) {
8908         env->xregs[22] = env->regs[14];
8909         env->xregs[23] = env->regs[13];
8910     } else {
8911         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
8912         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
8913     }
8914 
8915     /*
8916      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
8917      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
8918      * FIQ bank for r8-r14.
8919      */
8920     if (mode == ARM_CPU_MODE_FIQ) {
8921         for (i = 24; i < 31; i++) {
8922             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
8923         }
8924     } else {
8925         for (i = 24; i < 29; i++) {
8926             env->xregs[i] = env->fiq_regs[i - 24];
8927         }
8928         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
8929         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
8930     }
8931 
8932     env->pc = env->regs[15];
8933 }
8934 
8935 /*
8936  * Function used to synchronize QEMU's AArch32 register set with AArch64
8937  * register set.  This is necessary when switching between AArch32 and AArch64
8938  * execution state.
8939  */
8940 void aarch64_sync_64_to_32(CPUARMState *env)
8941 {
8942     int i;
8943     uint32_t mode = env->uncached_cpsr & CPSR_M;
8944 
8945     /* We can blanket copy X[0:7] to R[0:7] */
8946     for (i = 0; i < 8; i++) {
8947         env->regs[i] = env->xregs[i];
8948     }
8949 
8950     /*
8951      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
8952      * Otherwise, we copy x8-x12 into the banked user regs.
8953      */
8954     if (mode == ARM_CPU_MODE_FIQ) {
8955         for (i = 8; i < 13; i++) {
8956             env->usr_regs[i - 8] = env->xregs[i];
8957         }
8958     } else {
8959         for (i = 8; i < 13; i++) {
8960             env->regs[i] = env->xregs[i];
8961         }
8962     }
8963 
8964     /*
8965      * Registers r13 & r14 depend on the current mode.
8966      * If we are in a given mode, we copy the corresponding x registers to r13
8967      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
8968      * for the mode.
8969      */
8970     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
8971         env->regs[13] = env->xregs[13];
8972         env->regs[14] = env->xregs[14];
8973     } else {
8974         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
8975 
8976         /*
8977          * HYP is an exception in that it does not have its own banked r14 but
8978          * shares the USR r14
8979          */
8980         if (mode == ARM_CPU_MODE_HYP) {
8981             env->regs[14] = env->xregs[14];
8982         } else {
8983             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
8984         }
8985     }
8986 
8987     if (mode == ARM_CPU_MODE_HYP) {
8988         env->regs[13] = env->xregs[15];
8989     } else {
8990         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
8991     }
8992 
8993     if (mode == ARM_CPU_MODE_IRQ) {
8994         env->regs[14] = env->xregs[16];
8995         env->regs[13] = env->xregs[17];
8996     } else {
8997         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
8998         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
8999     }
9000 
9001     if (mode == ARM_CPU_MODE_SVC) {
9002         env->regs[14] = env->xregs[18];
9003         env->regs[13] = env->xregs[19];
9004     } else {
9005         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9006         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9007     }
9008 
9009     if (mode == ARM_CPU_MODE_ABT) {
9010         env->regs[14] = env->xregs[20];
9011         env->regs[13] = env->xregs[21];
9012     } else {
9013         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9014         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9015     }
9016 
9017     if (mode == ARM_CPU_MODE_UND) {
9018         env->regs[14] = env->xregs[22];
9019         env->regs[13] = env->xregs[23];
9020     } else {
9021         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9022         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9023     }
9024 
9025     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9026      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9027      * FIQ bank for r8-r14.
9028      */
9029     if (mode == ARM_CPU_MODE_FIQ) {
9030         for (i = 24; i < 31; i++) {
9031             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9032         }
9033     } else {
9034         for (i = 24; i < 29; i++) {
9035             env->fiq_regs[i - 24] = env->xregs[i];
9036         }
9037         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9038         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9039     }
9040 
9041     env->regs[15] = env->pc;
9042 }
9043 
9044 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9045                                    uint32_t mask, uint32_t offset,
9046                                    uint32_t newpc)
9047 {
9048     int new_el;
9049 
9050     /* Change the CPU state so as to actually take the exception. */
9051     switch_mode(env, new_mode);
9052     new_el = arm_current_el(env);
9053 
9054     /*
9055      * For exceptions taken to AArch32 we must clear the SS bit in both
9056      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9057      */
9058     env->uncached_cpsr &= ~PSTATE_SS;
9059     env->spsr = cpsr_read(env);
9060     /* Clear IT bits.  */
9061     env->condexec_bits = 0;
9062     /* Switch to the new mode, and to the correct instruction set.  */
9063     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9064     /* Set new mode endianness */
9065     env->uncached_cpsr &= ~CPSR_E;
9066     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9067         env->uncached_cpsr |= CPSR_E;
9068     }
9069     /* J and IL must always be cleared for exception entry */
9070     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9071     env->daif |= mask;
9072 
9073     if (new_mode == ARM_CPU_MODE_HYP) {
9074         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9075         env->elr_el[2] = env->regs[15];
9076     } else {
9077         /* CPSR.PAN is normally preserved preserved unless...  */
9078         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9079             switch (new_el) {
9080             case 3:
9081                 if (!arm_is_secure_below_el3(env)) {
9082                     /* ... the target is EL3, from non-secure state.  */
9083                     env->uncached_cpsr &= ~CPSR_PAN;
9084                     break;
9085                 }
9086                 /* ... the target is EL3, from secure state ... */
9087                 /* fall through */
9088             case 1:
9089                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9090                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9091                     env->uncached_cpsr |= CPSR_PAN;
9092                 }
9093                 break;
9094             }
9095         }
9096         /*
9097          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9098          * and we should just guard the thumb mode on V4
9099          */
9100         if (arm_feature(env, ARM_FEATURE_V4T)) {
9101             env->thumb =
9102                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9103         }
9104         env->regs[14] = env->regs[15] + offset;
9105     }
9106     env->regs[15] = newpc;
9107     arm_rebuild_hflags(env);
9108 }
9109 
9110 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9111 {
9112     /*
9113      * Handle exception entry to Hyp mode; this is sufficiently
9114      * different to entry to other AArch32 modes that we handle it
9115      * separately here.
9116      *
9117      * The vector table entry used is always the 0x14 Hyp mode entry point,
9118      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
9119      * The offset applied to the preferred return address is always zero
9120      * (see DDI0487C.a section G1.12.3).
9121      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9122      */
9123     uint32_t addr, mask;
9124     ARMCPU *cpu = ARM_CPU(cs);
9125     CPUARMState *env = &cpu->env;
9126 
9127     switch (cs->exception_index) {
9128     case EXCP_UDEF:
9129         addr = 0x04;
9130         break;
9131     case EXCP_SWI:
9132         addr = 0x14;
9133         break;
9134     case EXCP_BKPT:
9135         /* Fall through to prefetch abort.  */
9136     case EXCP_PREFETCH_ABORT:
9137         env->cp15.ifar_s = env->exception.vaddress;
9138         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9139                       (uint32_t)env->exception.vaddress);
9140         addr = 0x0c;
9141         break;
9142     case EXCP_DATA_ABORT:
9143         env->cp15.dfar_s = env->exception.vaddress;
9144         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9145                       (uint32_t)env->exception.vaddress);
9146         addr = 0x10;
9147         break;
9148     case EXCP_IRQ:
9149         addr = 0x18;
9150         break;
9151     case EXCP_FIQ:
9152         addr = 0x1c;
9153         break;
9154     case EXCP_HVC:
9155         addr = 0x08;
9156         break;
9157     case EXCP_HYP_TRAP:
9158         addr = 0x14;
9159         break;
9160     default:
9161         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9162     }
9163 
9164     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9165         if (!arm_feature(env, ARM_FEATURE_V8)) {
9166             /*
9167              * QEMU syndrome values are v8-style. v7 has the IL bit
9168              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9169              * If this is a v7 CPU, squash the IL bit in those cases.
9170              */
9171             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9172                 (cs->exception_index == EXCP_DATA_ABORT &&
9173                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9174                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9175                 env->exception.syndrome &= ~ARM_EL_IL;
9176             }
9177         }
9178         env->cp15.esr_el[2] = env->exception.syndrome;
9179     }
9180 
9181     if (arm_current_el(env) != 2 && addr < 0x14) {
9182         addr = 0x14;
9183     }
9184 
9185     mask = 0;
9186     if (!(env->cp15.scr_el3 & SCR_EA)) {
9187         mask |= CPSR_A;
9188     }
9189     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9190         mask |= CPSR_I;
9191     }
9192     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9193         mask |= CPSR_F;
9194     }
9195 
9196     addr += env->cp15.hvbar;
9197 
9198     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9199 }
9200 
9201 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9202 {
9203     ARMCPU *cpu = ARM_CPU(cs);
9204     CPUARMState *env = &cpu->env;
9205     uint32_t addr;
9206     uint32_t mask;
9207     int new_mode;
9208     uint32_t offset;
9209     uint32_t moe;
9210 
9211     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9212     switch (syn_get_ec(env->exception.syndrome)) {
9213     case EC_BREAKPOINT:
9214     case EC_BREAKPOINT_SAME_EL:
9215         moe = 1;
9216         break;
9217     case EC_WATCHPOINT:
9218     case EC_WATCHPOINT_SAME_EL:
9219         moe = 10;
9220         break;
9221     case EC_AA32_BKPT:
9222         moe = 3;
9223         break;
9224     case EC_VECTORCATCH:
9225         moe = 5;
9226         break;
9227     default:
9228         moe = 0;
9229         break;
9230     }
9231 
9232     if (moe) {
9233         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9234     }
9235 
9236     if (env->exception.target_el == 2) {
9237         arm_cpu_do_interrupt_aarch32_hyp(cs);
9238         return;
9239     }
9240 
9241     switch (cs->exception_index) {
9242     case EXCP_UDEF:
9243         new_mode = ARM_CPU_MODE_UND;
9244         addr = 0x04;
9245         mask = CPSR_I;
9246         if (env->thumb)
9247             offset = 2;
9248         else
9249             offset = 4;
9250         break;
9251     case EXCP_SWI:
9252         new_mode = ARM_CPU_MODE_SVC;
9253         addr = 0x08;
9254         mask = CPSR_I;
9255         /* The PC already points to the next instruction.  */
9256         offset = 0;
9257         break;
9258     case EXCP_BKPT:
9259         /* Fall through to prefetch abort.  */
9260     case EXCP_PREFETCH_ABORT:
9261         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9262         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9263         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9264                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9265         new_mode = ARM_CPU_MODE_ABT;
9266         addr = 0x0c;
9267         mask = CPSR_A | CPSR_I;
9268         offset = 4;
9269         break;
9270     case EXCP_DATA_ABORT:
9271         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9272         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9273         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9274                       env->exception.fsr,
9275                       (uint32_t)env->exception.vaddress);
9276         new_mode = ARM_CPU_MODE_ABT;
9277         addr = 0x10;
9278         mask = CPSR_A | CPSR_I;
9279         offset = 8;
9280         break;
9281     case EXCP_IRQ:
9282         new_mode = ARM_CPU_MODE_IRQ;
9283         addr = 0x18;
9284         /* Disable IRQ and imprecise data aborts.  */
9285         mask = CPSR_A | CPSR_I;
9286         offset = 4;
9287         if (env->cp15.scr_el3 & SCR_IRQ) {
9288             /* IRQ routed to monitor mode */
9289             new_mode = ARM_CPU_MODE_MON;
9290             mask |= CPSR_F;
9291         }
9292         break;
9293     case EXCP_FIQ:
9294         new_mode = ARM_CPU_MODE_FIQ;
9295         addr = 0x1c;
9296         /* Disable FIQ, IRQ and imprecise data aborts.  */
9297         mask = CPSR_A | CPSR_I | CPSR_F;
9298         if (env->cp15.scr_el3 & SCR_FIQ) {
9299             /* FIQ routed to monitor mode */
9300             new_mode = ARM_CPU_MODE_MON;
9301         }
9302         offset = 4;
9303         break;
9304     case EXCP_VIRQ:
9305         new_mode = ARM_CPU_MODE_IRQ;
9306         addr = 0x18;
9307         /* Disable IRQ and imprecise data aborts.  */
9308         mask = CPSR_A | CPSR_I;
9309         offset = 4;
9310         break;
9311     case EXCP_VFIQ:
9312         new_mode = ARM_CPU_MODE_FIQ;
9313         addr = 0x1c;
9314         /* Disable FIQ, IRQ and imprecise data aborts.  */
9315         mask = CPSR_A | CPSR_I | CPSR_F;
9316         offset = 4;
9317         break;
9318     case EXCP_SMC:
9319         new_mode = ARM_CPU_MODE_MON;
9320         addr = 0x08;
9321         mask = CPSR_A | CPSR_I | CPSR_F;
9322         offset = 0;
9323         break;
9324     default:
9325         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9326         return; /* Never happens.  Keep compiler happy.  */
9327     }
9328 
9329     if (new_mode == ARM_CPU_MODE_MON) {
9330         addr += env->cp15.mvbar;
9331     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9332         /* High vectors. When enabled, base address cannot be remapped. */
9333         addr += 0xffff0000;
9334     } else {
9335         /* ARM v7 architectures provide a vector base address register to remap
9336          * the interrupt vector table.
9337          * This register is only followed in non-monitor mode, and is banked.
9338          * Note: only bits 31:5 are valid.
9339          */
9340         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9341     }
9342 
9343     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9344         env->cp15.scr_el3 &= ~SCR_NS;
9345     }
9346 
9347     take_aarch32_exception(env, new_mode, mask, offset, addr);
9348 }
9349 
9350 /* Handle exception entry to a target EL which is using AArch64 */
9351 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
9352 {
9353     ARMCPU *cpu = ARM_CPU(cs);
9354     CPUARMState *env = &cpu->env;
9355     unsigned int new_el = env->exception.target_el;
9356     target_ulong addr = env->cp15.vbar_el[new_el];
9357     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
9358     unsigned int old_mode;
9359     unsigned int cur_el = arm_current_el(env);
9360 
9361     /*
9362      * Note that new_el can never be 0.  If cur_el is 0, then
9363      * el0_a64 is is_a64(), else el0_a64 is ignored.
9364      */
9365     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
9366 
9367     if (cur_el < new_el) {
9368         /* Entry vector offset depends on whether the implemented EL
9369          * immediately lower than the target level is using AArch32 or AArch64
9370          */
9371         bool is_aa64;
9372         uint64_t hcr;
9373 
9374         switch (new_el) {
9375         case 3:
9376             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
9377             break;
9378         case 2:
9379             hcr = arm_hcr_el2_eff(env);
9380             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
9381                 is_aa64 = (hcr & HCR_RW) != 0;
9382                 break;
9383             }
9384             /* fall through */
9385         case 1:
9386             is_aa64 = is_a64(env);
9387             break;
9388         default:
9389             g_assert_not_reached();
9390         }
9391 
9392         if (is_aa64) {
9393             addr += 0x400;
9394         } else {
9395             addr += 0x600;
9396         }
9397     } else if (pstate_read(env) & PSTATE_SP) {
9398         addr += 0x200;
9399     }
9400 
9401     switch (cs->exception_index) {
9402     case EXCP_PREFETCH_ABORT:
9403     case EXCP_DATA_ABORT:
9404         env->cp15.far_el[new_el] = env->exception.vaddress;
9405         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
9406                       env->cp15.far_el[new_el]);
9407         /* fall through */
9408     case EXCP_BKPT:
9409     case EXCP_UDEF:
9410     case EXCP_SWI:
9411     case EXCP_HVC:
9412     case EXCP_HYP_TRAP:
9413     case EXCP_SMC:
9414         if (syn_get_ec(env->exception.syndrome) == EC_ADVSIMDFPACCESSTRAP) {
9415             /*
9416              * QEMU internal FP/SIMD syndromes from AArch32 include the
9417              * TA and coproc fields which are only exposed if the exception
9418              * is taken to AArch32 Hyp mode. Mask them out to get a valid
9419              * AArch64 format syndrome.
9420              */
9421             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
9422         }
9423         env->cp15.esr_el[new_el] = env->exception.syndrome;
9424         break;
9425     case EXCP_IRQ:
9426     case EXCP_VIRQ:
9427         addr += 0x80;
9428         break;
9429     case EXCP_FIQ:
9430     case EXCP_VFIQ:
9431         addr += 0x100;
9432         break;
9433     default:
9434         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9435     }
9436 
9437     if (is_a64(env)) {
9438         old_mode = pstate_read(env);
9439         aarch64_save_sp(env, arm_current_el(env));
9440         env->elr_el[new_el] = env->pc;
9441     } else {
9442         old_mode = cpsr_read(env);
9443         env->elr_el[new_el] = env->regs[15];
9444 
9445         aarch64_sync_32_to_64(env);
9446 
9447         env->condexec_bits = 0;
9448     }
9449     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
9450 
9451     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
9452                   env->elr_el[new_el]);
9453 
9454     if (cpu_isar_feature(aa64_pan, cpu)) {
9455         /* The value of PSTATE.PAN is normally preserved, except when ... */
9456         new_mode |= old_mode & PSTATE_PAN;
9457         switch (new_el) {
9458         case 2:
9459             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
9460             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
9461                 != (HCR_E2H | HCR_TGE)) {
9462                 break;
9463             }
9464             /* fall through */
9465         case 1:
9466             /* ... the target is EL1 ... */
9467             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
9468             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
9469                 new_mode |= PSTATE_PAN;
9470             }
9471             break;
9472         }
9473     }
9474 
9475     pstate_write(env, PSTATE_DAIF | new_mode);
9476     env->aarch64 = 1;
9477     aarch64_restore_sp(env, new_el);
9478     helper_rebuild_hflags_a64(env, new_el);
9479 
9480     env->pc = addr;
9481 
9482     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
9483                   new_el, env->pc, pstate_read(env));
9484 }
9485 
9486 /*
9487  * Do semihosting call and set the appropriate return value. All the
9488  * permission and validity checks have been done at translate time.
9489  *
9490  * We only see semihosting exceptions in TCG only as they are not
9491  * trapped to the hypervisor in KVM.
9492  */
9493 #ifdef CONFIG_TCG
9494 static void handle_semihosting(CPUState *cs)
9495 {
9496     ARMCPU *cpu = ARM_CPU(cs);
9497     CPUARMState *env = &cpu->env;
9498 
9499     if (is_a64(env)) {
9500         qemu_log_mask(CPU_LOG_INT,
9501                       "...handling as semihosting call 0x%" PRIx64 "\n",
9502                       env->xregs[0]);
9503         env->xregs[0] = do_arm_semihosting(env);
9504         env->pc += 4;
9505     } else {
9506         qemu_log_mask(CPU_LOG_INT,
9507                       "...handling as semihosting call 0x%x\n",
9508                       env->regs[0]);
9509         env->regs[0] = do_arm_semihosting(env);
9510         env->regs[15] += env->thumb ? 2 : 4;
9511     }
9512 }
9513 #endif
9514 
9515 /* Handle a CPU exception for A and R profile CPUs.
9516  * Do any appropriate logging, handle PSCI calls, and then hand off
9517  * to the AArch64-entry or AArch32-entry function depending on the
9518  * target exception level's register width.
9519  */
9520 void arm_cpu_do_interrupt(CPUState *cs)
9521 {
9522     ARMCPU *cpu = ARM_CPU(cs);
9523     CPUARMState *env = &cpu->env;
9524     unsigned int new_el = env->exception.target_el;
9525 
9526     assert(!arm_feature(env, ARM_FEATURE_M));
9527 
9528     arm_log_exception(cs->exception_index);
9529     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
9530                   new_el);
9531     if (qemu_loglevel_mask(CPU_LOG_INT)
9532         && !excp_is_internal(cs->exception_index)) {
9533         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
9534                       syn_get_ec(env->exception.syndrome),
9535                       env->exception.syndrome);
9536     }
9537 
9538     if (arm_is_psci_call(cpu, cs->exception_index)) {
9539         arm_handle_psci_call(cpu);
9540         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
9541         return;
9542     }
9543 
9544     /*
9545      * Semihosting semantics depend on the register width of the code
9546      * that caused the exception, not the target exception level, so
9547      * must be handled here.
9548      */
9549 #ifdef CONFIG_TCG
9550     if (cs->exception_index == EXCP_SEMIHOST) {
9551         handle_semihosting(cs);
9552         return;
9553     }
9554 #endif
9555 
9556     /* Hooks may change global state so BQL should be held, also the
9557      * BQL needs to be held for any modification of
9558      * cs->interrupt_request.
9559      */
9560     g_assert(qemu_mutex_iothread_locked());
9561 
9562     arm_call_pre_el_change_hook(cpu);
9563 
9564     assert(!excp_is_internal(cs->exception_index));
9565     if (arm_el_is_aa64(env, new_el)) {
9566         arm_cpu_do_interrupt_aarch64(cs);
9567     } else {
9568         arm_cpu_do_interrupt_aarch32(cs);
9569     }
9570 
9571     arm_call_el_change_hook(cpu);
9572 
9573     if (!kvm_enabled()) {
9574         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
9575     }
9576 }
9577 #endif /* !CONFIG_USER_ONLY */
9578 
9579 /* Return the exception level which controls this address translation regime */
9580 static uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
9581 {
9582     switch (mmu_idx) {
9583     case ARMMMUIdx_E20_0:
9584     case ARMMMUIdx_E20_2:
9585     case ARMMMUIdx_E20_2_PAN:
9586     case ARMMMUIdx_Stage2:
9587     case ARMMMUIdx_E2:
9588         return 2;
9589     case ARMMMUIdx_SE3:
9590         return 3;
9591     case ARMMMUIdx_SE10_0:
9592         return arm_el_is_aa64(env, 3) ? 1 : 3;
9593     case ARMMMUIdx_SE10_1:
9594     case ARMMMUIdx_SE10_1_PAN:
9595     case ARMMMUIdx_Stage1_E0:
9596     case ARMMMUIdx_Stage1_E1:
9597     case ARMMMUIdx_Stage1_E1_PAN:
9598     case ARMMMUIdx_E10_0:
9599     case ARMMMUIdx_E10_1:
9600     case ARMMMUIdx_E10_1_PAN:
9601     case ARMMMUIdx_MPrivNegPri:
9602     case ARMMMUIdx_MUserNegPri:
9603     case ARMMMUIdx_MPriv:
9604     case ARMMMUIdx_MUser:
9605     case ARMMMUIdx_MSPrivNegPri:
9606     case ARMMMUIdx_MSUserNegPri:
9607     case ARMMMUIdx_MSPriv:
9608     case ARMMMUIdx_MSUser:
9609         return 1;
9610     default:
9611         g_assert_not_reached();
9612     }
9613 }
9614 
9615 uint64_t arm_sctlr(CPUARMState *env, int el)
9616 {
9617     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
9618     if (el == 0) {
9619         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
9620         el = (mmu_idx == ARMMMUIdx_E20_0 ? 2 : 1);
9621     }
9622     return env->cp15.sctlr_el[el];
9623 }
9624 
9625 /* Return the SCTLR value which controls this address translation regime */
9626 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
9627 {
9628     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
9629 }
9630 
9631 #ifndef CONFIG_USER_ONLY
9632 
9633 /* Return true if the specified stage of address translation is disabled */
9634 static inline bool regime_translation_disabled(CPUARMState *env,
9635                                                ARMMMUIdx mmu_idx)
9636 {
9637     if (arm_feature(env, ARM_FEATURE_M)) {
9638         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
9639                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
9640         case R_V7M_MPU_CTRL_ENABLE_MASK:
9641             /* Enabled, but not for HardFault and NMI */
9642             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
9643         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
9644             /* Enabled for all cases */
9645             return false;
9646         case 0:
9647         default:
9648             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
9649              * we warned about that in armv7m_nvic.c when the guest set it.
9650              */
9651             return true;
9652         }
9653     }
9654 
9655     if (mmu_idx == ARMMMUIdx_Stage2) {
9656         /* HCR.DC means HCR.VM behaves as 1 */
9657         return (env->cp15.hcr_el2 & (HCR_DC | HCR_VM)) == 0;
9658     }
9659 
9660     if (env->cp15.hcr_el2 & HCR_TGE) {
9661         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
9662         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
9663             return true;
9664         }
9665     }
9666 
9667     if ((env->cp15.hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
9668         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
9669         return true;
9670     }
9671 
9672     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
9673 }
9674 
9675 static inline bool regime_translation_big_endian(CPUARMState *env,
9676                                                  ARMMMUIdx mmu_idx)
9677 {
9678     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
9679 }
9680 
9681 /* Return the TTBR associated with this translation regime */
9682 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
9683                                    int ttbrn)
9684 {
9685     if (mmu_idx == ARMMMUIdx_Stage2) {
9686         return env->cp15.vttbr_el2;
9687     }
9688     if (ttbrn == 0) {
9689         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
9690     } else {
9691         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
9692     }
9693 }
9694 
9695 #endif /* !CONFIG_USER_ONLY */
9696 
9697 /* Return the TCR controlling this translation regime */
9698 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
9699 {
9700     if (mmu_idx == ARMMMUIdx_Stage2) {
9701         return &env->cp15.vtcr_el2;
9702     }
9703     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
9704 }
9705 
9706 /* Convert a possible stage1+2 MMU index into the appropriate
9707  * stage 1 MMU index
9708  */
9709 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
9710 {
9711     switch (mmu_idx) {
9712     case ARMMMUIdx_E10_0:
9713         return ARMMMUIdx_Stage1_E0;
9714     case ARMMMUIdx_E10_1:
9715         return ARMMMUIdx_Stage1_E1;
9716     case ARMMMUIdx_E10_1_PAN:
9717         return ARMMMUIdx_Stage1_E1_PAN;
9718     default:
9719         return mmu_idx;
9720     }
9721 }
9722 
9723 /* Return true if the translation regime is using LPAE format page tables */
9724 static inline bool regime_using_lpae_format(CPUARMState *env,
9725                                             ARMMMUIdx mmu_idx)
9726 {
9727     int el = regime_el(env, mmu_idx);
9728     if (el == 2 || arm_el_is_aa64(env, el)) {
9729         return true;
9730     }
9731     if (arm_feature(env, ARM_FEATURE_LPAE)
9732         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
9733         return true;
9734     }
9735     return false;
9736 }
9737 
9738 /* Returns true if the stage 1 translation regime is using LPAE format page
9739  * tables. Used when raising alignment exceptions, whose FSR changes depending
9740  * on whether the long or short descriptor format is in use. */
9741 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
9742 {
9743     mmu_idx = stage_1_mmu_idx(mmu_idx);
9744 
9745     return regime_using_lpae_format(env, mmu_idx);
9746 }
9747 
9748 #ifndef CONFIG_USER_ONLY
9749 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
9750 {
9751     switch (mmu_idx) {
9752     case ARMMMUIdx_SE10_0:
9753     case ARMMMUIdx_E20_0:
9754     case ARMMMUIdx_Stage1_E0:
9755     case ARMMMUIdx_MUser:
9756     case ARMMMUIdx_MSUser:
9757     case ARMMMUIdx_MUserNegPri:
9758     case ARMMMUIdx_MSUserNegPri:
9759         return true;
9760     default:
9761         return false;
9762     case ARMMMUIdx_E10_0:
9763     case ARMMMUIdx_E10_1:
9764     case ARMMMUIdx_E10_1_PAN:
9765         g_assert_not_reached();
9766     }
9767 }
9768 
9769 /* Translate section/page access permissions to page
9770  * R/W protection flags
9771  *
9772  * @env:         CPUARMState
9773  * @mmu_idx:     MMU index indicating required translation regime
9774  * @ap:          The 3-bit access permissions (AP[2:0])
9775  * @domain_prot: The 2-bit domain access permissions
9776  */
9777 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
9778                                 int ap, int domain_prot)
9779 {
9780     bool is_user = regime_is_user(env, mmu_idx);
9781 
9782     if (domain_prot == 3) {
9783         return PAGE_READ | PAGE_WRITE;
9784     }
9785 
9786     switch (ap) {
9787     case 0:
9788         if (arm_feature(env, ARM_FEATURE_V7)) {
9789             return 0;
9790         }
9791         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
9792         case SCTLR_S:
9793             return is_user ? 0 : PAGE_READ;
9794         case SCTLR_R:
9795             return PAGE_READ;
9796         default:
9797             return 0;
9798         }
9799     case 1:
9800         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
9801     case 2:
9802         if (is_user) {
9803             return PAGE_READ;
9804         } else {
9805             return PAGE_READ | PAGE_WRITE;
9806         }
9807     case 3:
9808         return PAGE_READ | PAGE_WRITE;
9809     case 4: /* Reserved.  */
9810         return 0;
9811     case 5:
9812         return is_user ? 0 : PAGE_READ;
9813     case 6:
9814         return PAGE_READ;
9815     case 7:
9816         if (!arm_feature(env, ARM_FEATURE_V6K)) {
9817             return 0;
9818         }
9819         return PAGE_READ;
9820     default:
9821         g_assert_not_reached();
9822     }
9823 }
9824 
9825 /* Translate section/page access permissions to page
9826  * R/W protection flags.
9827  *
9828  * @ap:      The 2-bit simple AP (AP[2:1])
9829  * @is_user: TRUE if accessing from PL0
9830  */
9831 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
9832 {
9833     switch (ap) {
9834     case 0:
9835         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
9836     case 1:
9837         return PAGE_READ | PAGE_WRITE;
9838     case 2:
9839         return is_user ? 0 : PAGE_READ;
9840     case 3:
9841         return PAGE_READ;
9842     default:
9843         g_assert_not_reached();
9844     }
9845 }
9846 
9847 static inline int
9848 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
9849 {
9850     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
9851 }
9852 
9853 /* Translate S2 section/page access permissions to protection flags
9854  *
9855  * @env:     CPUARMState
9856  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
9857  * @xn:      XN (execute-never) bit
9858  */
9859 static int get_S2prot(CPUARMState *env, int s2ap, int xn)
9860 {
9861     int prot = 0;
9862 
9863     if (s2ap & 1) {
9864         prot |= PAGE_READ;
9865     }
9866     if (s2ap & 2) {
9867         prot |= PAGE_WRITE;
9868     }
9869     if (!xn) {
9870         if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
9871             prot |= PAGE_EXEC;
9872         }
9873     }
9874     return prot;
9875 }
9876 
9877 /* Translate section/page access permissions to protection flags
9878  *
9879  * @env:     CPUARMState
9880  * @mmu_idx: MMU index indicating required translation regime
9881  * @is_aa64: TRUE if AArch64
9882  * @ap:      The 2-bit simple AP (AP[2:1])
9883  * @ns:      NS (non-secure) bit
9884  * @xn:      XN (execute-never) bit
9885  * @pxn:     PXN (privileged execute-never) bit
9886  */
9887 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
9888                       int ap, int ns, int xn, int pxn)
9889 {
9890     bool is_user = regime_is_user(env, mmu_idx);
9891     int prot_rw, user_rw;
9892     bool have_wxn;
9893     int wxn = 0;
9894 
9895     assert(mmu_idx != ARMMMUIdx_Stage2);
9896 
9897     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
9898     if (is_user) {
9899         prot_rw = user_rw;
9900     } else {
9901         if (user_rw && regime_is_pan(env, mmu_idx)) {
9902             return 0;
9903         }
9904         prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
9905     }
9906 
9907     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
9908         return prot_rw;
9909     }
9910 
9911     /* TODO have_wxn should be replaced with
9912      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
9913      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
9914      * compatible processors have EL2, which is required for [U]WXN.
9915      */
9916     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
9917 
9918     if (have_wxn) {
9919         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
9920     }
9921 
9922     if (is_aa64) {
9923         if (regime_has_2_ranges(mmu_idx) && !is_user) {
9924             xn = pxn || (user_rw & PAGE_WRITE);
9925         }
9926     } else if (arm_feature(env, ARM_FEATURE_V7)) {
9927         switch (regime_el(env, mmu_idx)) {
9928         case 1:
9929         case 3:
9930             if (is_user) {
9931                 xn = xn || !(user_rw & PAGE_READ);
9932             } else {
9933                 int uwxn = 0;
9934                 if (have_wxn) {
9935                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
9936                 }
9937                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
9938                      (uwxn && (user_rw & PAGE_WRITE));
9939             }
9940             break;
9941         case 2:
9942             break;
9943         }
9944     } else {
9945         xn = wxn = 0;
9946     }
9947 
9948     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
9949         return prot_rw;
9950     }
9951     return prot_rw | PAGE_EXEC;
9952 }
9953 
9954 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
9955                                      uint32_t *table, uint32_t address)
9956 {
9957     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
9958     TCR *tcr = regime_tcr(env, mmu_idx);
9959 
9960     if (address & tcr->mask) {
9961         if (tcr->raw_tcr & TTBCR_PD1) {
9962             /* Translation table walk disabled for TTBR1 */
9963             return false;
9964         }
9965         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
9966     } else {
9967         if (tcr->raw_tcr & TTBCR_PD0) {
9968             /* Translation table walk disabled for TTBR0 */
9969             return false;
9970         }
9971         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
9972     }
9973     *table |= (address >> 18) & 0x3ffc;
9974     return true;
9975 }
9976 
9977 /* Translate a S1 pagetable walk through S2 if needed.  */
9978 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
9979                                hwaddr addr, MemTxAttrs txattrs,
9980                                ARMMMUFaultInfo *fi)
9981 {
9982     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
9983         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
9984         target_ulong s2size;
9985         hwaddr s2pa;
9986         int s2prot;
9987         int ret;
9988         ARMCacheAttrs cacheattrs = {};
9989         ARMCacheAttrs *pcacheattrs = NULL;
9990 
9991         if (env->cp15.hcr_el2 & HCR_PTW) {
9992             /*
9993              * PTW means we must fault if this S1 walk touches S2 Device
9994              * memory; otherwise we don't care about the attributes and can
9995              * save the S2 translation the effort of computing them.
9996              */
9997             pcacheattrs = &cacheattrs;
9998         }
9999 
10000         ret = get_phys_addr_lpae(env, addr, 0, ARMMMUIdx_Stage2, &s2pa,
10001                                  &txattrs, &s2prot, &s2size, fi, pcacheattrs);
10002         if (ret) {
10003             assert(fi->type != ARMFault_None);
10004             fi->s2addr = addr;
10005             fi->stage2 = true;
10006             fi->s1ptw = true;
10007             return ~0;
10008         }
10009         if (pcacheattrs && (pcacheattrs->attrs & 0xf0) == 0) {
10010             /* Access was to Device memory: generate Permission fault */
10011             fi->type = ARMFault_Permission;
10012             fi->s2addr = addr;
10013             fi->stage2 = true;
10014             fi->s1ptw = true;
10015             return ~0;
10016         }
10017         addr = s2pa;
10018     }
10019     return addr;
10020 }
10021 
10022 /* All loads done in the course of a page table walk go through here. */
10023 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10024                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10025 {
10026     ARMCPU *cpu = ARM_CPU(cs);
10027     CPUARMState *env = &cpu->env;
10028     MemTxAttrs attrs = {};
10029     MemTxResult result = MEMTX_OK;
10030     AddressSpace *as;
10031     uint32_t data;
10032 
10033     attrs.secure = is_secure;
10034     as = arm_addressspace(cs, attrs);
10035     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10036     if (fi->s1ptw) {
10037         return 0;
10038     }
10039     if (regime_translation_big_endian(env, mmu_idx)) {
10040         data = address_space_ldl_be(as, addr, attrs, &result);
10041     } else {
10042         data = address_space_ldl_le(as, addr, attrs, &result);
10043     }
10044     if (result == MEMTX_OK) {
10045         return data;
10046     }
10047     fi->type = ARMFault_SyncExternalOnWalk;
10048     fi->ea = arm_extabort_type(result);
10049     return 0;
10050 }
10051 
10052 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10053                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10054 {
10055     ARMCPU *cpu = ARM_CPU(cs);
10056     CPUARMState *env = &cpu->env;
10057     MemTxAttrs attrs = {};
10058     MemTxResult result = MEMTX_OK;
10059     AddressSpace *as;
10060     uint64_t data;
10061 
10062     attrs.secure = is_secure;
10063     as = arm_addressspace(cs, attrs);
10064     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10065     if (fi->s1ptw) {
10066         return 0;
10067     }
10068     if (regime_translation_big_endian(env, mmu_idx)) {
10069         data = address_space_ldq_be(as, addr, attrs, &result);
10070     } else {
10071         data = address_space_ldq_le(as, addr, attrs, &result);
10072     }
10073     if (result == MEMTX_OK) {
10074         return data;
10075     }
10076     fi->type = ARMFault_SyncExternalOnWalk;
10077     fi->ea = arm_extabort_type(result);
10078     return 0;
10079 }
10080 
10081 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10082                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10083                              hwaddr *phys_ptr, int *prot,
10084                              target_ulong *page_size,
10085                              ARMMMUFaultInfo *fi)
10086 {
10087     CPUState *cs = env_cpu(env);
10088     int level = 1;
10089     uint32_t table;
10090     uint32_t desc;
10091     int type;
10092     int ap;
10093     int domain = 0;
10094     int domain_prot;
10095     hwaddr phys_addr;
10096     uint32_t dacr;
10097 
10098     /* Pagetable walk.  */
10099     /* Lookup l1 descriptor.  */
10100     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10101         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10102         fi->type = ARMFault_Translation;
10103         goto do_fault;
10104     }
10105     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10106                        mmu_idx, fi);
10107     if (fi->type != ARMFault_None) {
10108         goto do_fault;
10109     }
10110     type = (desc & 3);
10111     domain = (desc >> 5) & 0x0f;
10112     if (regime_el(env, mmu_idx) == 1) {
10113         dacr = env->cp15.dacr_ns;
10114     } else {
10115         dacr = env->cp15.dacr_s;
10116     }
10117     domain_prot = (dacr >> (domain * 2)) & 3;
10118     if (type == 0) {
10119         /* Section translation fault.  */
10120         fi->type = ARMFault_Translation;
10121         goto do_fault;
10122     }
10123     if (type != 2) {
10124         level = 2;
10125     }
10126     if (domain_prot == 0 || domain_prot == 2) {
10127         fi->type = ARMFault_Domain;
10128         goto do_fault;
10129     }
10130     if (type == 2) {
10131         /* 1Mb section.  */
10132         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10133         ap = (desc >> 10) & 3;
10134         *page_size = 1024 * 1024;
10135     } else {
10136         /* Lookup l2 entry.  */
10137         if (type == 1) {
10138             /* Coarse pagetable.  */
10139             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10140         } else {
10141             /* Fine pagetable.  */
10142             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10143         }
10144         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10145                            mmu_idx, fi);
10146         if (fi->type != ARMFault_None) {
10147             goto do_fault;
10148         }
10149         switch (desc & 3) {
10150         case 0: /* Page translation fault.  */
10151             fi->type = ARMFault_Translation;
10152             goto do_fault;
10153         case 1: /* 64k page.  */
10154             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10155             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10156             *page_size = 0x10000;
10157             break;
10158         case 2: /* 4k page.  */
10159             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10160             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10161             *page_size = 0x1000;
10162             break;
10163         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10164             if (type == 1) {
10165                 /* ARMv6/XScale extended small page format */
10166                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10167                     || arm_feature(env, ARM_FEATURE_V6)) {
10168                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10169                     *page_size = 0x1000;
10170                 } else {
10171                     /* UNPREDICTABLE in ARMv5; we choose to take a
10172                      * page translation fault.
10173                      */
10174                     fi->type = ARMFault_Translation;
10175                     goto do_fault;
10176                 }
10177             } else {
10178                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10179                 *page_size = 0x400;
10180             }
10181             ap = (desc >> 4) & 3;
10182             break;
10183         default:
10184             /* Never happens, but compiler isn't smart enough to tell.  */
10185             abort();
10186         }
10187     }
10188     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10189     *prot |= *prot ? PAGE_EXEC : 0;
10190     if (!(*prot & (1 << access_type))) {
10191         /* Access permission fault.  */
10192         fi->type = ARMFault_Permission;
10193         goto do_fault;
10194     }
10195     *phys_ptr = phys_addr;
10196     return false;
10197 do_fault:
10198     fi->domain = domain;
10199     fi->level = level;
10200     return true;
10201 }
10202 
10203 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10204                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10205                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10206                              target_ulong *page_size, ARMMMUFaultInfo *fi)
10207 {
10208     CPUState *cs = env_cpu(env);
10209     int level = 1;
10210     uint32_t table;
10211     uint32_t desc;
10212     uint32_t xn;
10213     uint32_t pxn = 0;
10214     int type;
10215     int ap;
10216     int domain = 0;
10217     int domain_prot;
10218     hwaddr phys_addr;
10219     uint32_t dacr;
10220     bool ns;
10221 
10222     /* Pagetable walk.  */
10223     /* Lookup l1 descriptor.  */
10224     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10225         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10226         fi->type = ARMFault_Translation;
10227         goto do_fault;
10228     }
10229     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10230                        mmu_idx, fi);
10231     if (fi->type != ARMFault_None) {
10232         goto do_fault;
10233     }
10234     type = (desc & 3);
10235     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
10236         /* Section translation fault, or attempt to use the encoding
10237          * which is Reserved on implementations without PXN.
10238          */
10239         fi->type = ARMFault_Translation;
10240         goto do_fault;
10241     }
10242     if ((type == 1) || !(desc & (1 << 18))) {
10243         /* Page or Section.  */
10244         domain = (desc >> 5) & 0x0f;
10245     }
10246     if (regime_el(env, mmu_idx) == 1) {
10247         dacr = env->cp15.dacr_ns;
10248     } else {
10249         dacr = env->cp15.dacr_s;
10250     }
10251     if (type == 1) {
10252         level = 2;
10253     }
10254     domain_prot = (dacr >> (domain * 2)) & 3;
10255     if (domain_prot == 0 || domain_prot == 2) {
10256         /* Section or Page domain fault */
10257         fi->type = ARMFault_Domain;
10258         goto do_fault;
10259     }
10260     if (type != 1) {
10261         if (desc & (1 << 18)) {
10262             /* Supersection.  */
10263             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
10264             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
10265             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
10266             *page_size = 0x1000000;
10267         } else {
10268             /* Section.  */
10269             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10270             *page_size = 0x100000;
10271         }
10272         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
10273         xn = desc & (1 << 4);
10274         pxn = desc & 1;
10275         ns = extract32(desc, 19, 1);
10276     } else {
10277         if (arm_feature(env, ARM_FEATURE_PXN)) {
10278             pxn = (desc >> 2) & 1;
10279         }
10280         ns = extract32(desc, 3, 1);
10281         /* Lookup l2 entry.  */
10282         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10283         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10284                            mmu_idx, fi);
10285         if (fi->type != ARMFault_None) {
10286             goto do_fault;
10287         }
10288         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
10289         switch (desc & 3) {
10290         case 0: /* Page translation fault.  */
10291             fi->type = ARMFault_Translation;
10292             goto do_fault;
10293         case 1: /* 64k page.  */
10294             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10295             xn = desc & (1 << 15);
10296             *page_size = 0x10000;
10297             break;
10298         case 2: case 3: /* 4k page.  */
10299             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10300             xn = desc & 1;
10301             *page_size = 0x1000;
10302             break;
10303         default:
10304             /* Never happens, but compiler isn't smart enough to tell.  */
10305             abort();
10306         }
10307     }
10308     if (domain_prot == 3) {
10309         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10310     } else {
10311         if (pxn && !regime_is_user(env, mmu_idx)) {
10312             xn = 1;
10313         }
10314         if (xn && access_type == MMU_INST_FETCH) {
10315             fi->type = ARMFault_Permission;
10316             goto do_fault;
10317         }
10318 
10319         if (arm_feature(env, ARM_FEATURE_V6K) &&
10320                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
10321             /* The simplified model uses AP[0] as an access control bit.  */
10322             if ((ap & 1) == 0) {
10323                 /* Access flag fault.  */
10324                 fi->type = ARMFault_AccessFlag;
10325                 goto do_fault;
10326             }
10327             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
10328         } else {
10329             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10330         }
10331         if (*prot && !xn) {
10332             *prot |= PAGE_EXEC;
10333         }
10334         if (!(*prot & (1 << access_type))) {
10335             /* Access permission fault.  */
10336             fi->type = ARMFault_Permission;
10337             goto do_fault;
10338         }
10339     }
10340     if (ns) {
10341         /* The NS bit will (as required by the architecture) have no effect if
10342          * the CPU doesn't support TZ or this is a non-secure translation
10343          * regime, because the attribute will already be non-secure.
10344          */
10345         attrs->secure = false;
10346     }
10347     *phys_ptr = phys_addr;
10348     return false;
10349 do_fault:
10350     fi->domain = domain;
10351     fi->level = level;
10352     return true;
10353 }
10354 
10355 /*
10356  * check_s2_mmu_setup
10357  * @cpu:        ARMCPU
10358  * @is_aa64:    True if the translation regime is in AArch64 state
10359  * @startlevel: Suggested starting level
10360  * @inputsize:  Bitsize of IPAs
10361  * @stride:     Page-table stride (See the ARM ARM)
10362  *
10363  * Returns true if the suggested S2 translation parameters are OK and
10364  * false otherwise.
10365  */
10366 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
10367                                int inputsize, int stride)
10368 {
10369     const int grainsize = stride + 3;
10370     int startsizecheck;
10371 
10372     /* Negative levels are never allowed.  */
10373     if (level < 0) {
10374         return false;
10375     }
10376 
10377     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
10378     if (startsizecheck < 1 || startsizecheck > stride + 4) {
10379         return false;
10380     }
10381 
10382     if (is_aa64) {
10383         CPUARMState *env = &cpu->env;
10384         unsigned int pamax = arm_pamax(cpu);
10385 
10386         switch (stride) {
10387         case 13: /* 64KB Pages.  */
10388             if (level == 0 || (level == 1 && pamax <= 42)) {
10389                 return false;
10390             }
10391             break;
10392         case 11: /* 16KB Pages.  */
10393             if (level == 0 || (level == 1 && pamax <= 40)) {
10394                 return false;
10395             }
10396             break;
10397         case 9: /* 4KB Pages.  */
10398             if (level == 0 && pamax <= 42) {
10399                 return false;
10400             }
10401             break;
10402         default:
10403             g_assert_not_reached();
10404         }
10405 
10406         /* Inputsize checks.  */
10407         if (inputsize > pamax &&
10408             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
10409             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
10410             return false;
10411         }
10412     } else {
10413         /* AArch32 only supports 4KB pages. Assert on that.  */
10414         assert(stride == 9);
10415 
10416         if (level == 0) {
10417             return false;
10418         }
10419     }
10420     return true;
10421 }
10422 
10423 /* Translate from the 4-bit stage 2 representation of
10424  * memory attributes (without cache-allocation hints) to
10425  * the 8-bit representation of the stage 1 MAIR registers
10426  * (which includes allocation hints).
10427  *
10428  * ref: shared/translation/attrs/S2AttrDecode()
10429  *      .../S2ConvertAttrsHints()
10430  */
10431 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
10432 {
10433     uint8_t hiattr = extract32(s2attrs, 2, 2);
10434     uint8_t loattr = extract32(s2attrs, 0, 2);
10435     uint8_t hihint = 0, lohint = 0;
10436 
10437     if (hiattr != 0) { /* normal memory */
10438         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
10439             hiattr = loattr = 1; /* non-cacheable */
10440         } else {
10441             if (hiattr != 1) { /* Write-through or write-back */
10442                 hihint = 3; /* RW allocate */
10443             }
10444             if (loattr != 1) { /* Write-through or write-back */
10445                 lohint = 3; /* RW allocate */
10446             }
10447         }
10448     }
10449 
10450     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
10451 }
10452 #endif /* !CONFIG_USER_ONLY */
10453 
10454 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
10455 {
10456     if (regime_has_2_ranges(mmu_idx)) {
10457         return extract64(tcr, 37, 2);
10458     } else if (mmu_idx == ARMMMUIdx_Stage2) {
10459         return 0; /* VTCR_EL2 */
10460     } else {
10461         /* Replicate the single TBI bit so we always have 2 bits.  */
10462         return extract32(tcr, 20, 1) * 3;
10463     }
10464 }
10465 
10466 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
10467 {
10468     if (regime_has_2_ranges(mmu_idx)) {
10469         return extract64(tcr, 51, 2);
10470     } else if (mmu_idx == ARMMMUIdx_Stage2) {
10471         return 0; /* VTCR_EL2 */
10472     } else {
10473         /* Replicate the single TBID bit so we always have 2 bits.  */
10474         return extract32(tcr, 29, 1) * 3;
10475     }
10476 }
10477 
10478 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
10479                                    ARMMMUIdx mmu_idx, bool data)
10480 {
10481     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
10482     bool epd, hpd, using16k, using64k;
10483     int select, tsz, tbi;
10484 
10485     if (!regime_has_2_ranges(mmu_idx)) {
10486         select = 0;
10487         tsz = extract32(tcr, 0, 6);
10488         using64k = extract32(tcr, 14, 1);
10489         using16k = extract32(tcr, 15, 1);
10490         if (mmu_idx == ARMMMUIdx_Stage2) {
10491             /* VTCR_EL2 */
10492             hpd = false;
10493         } else {
10494             hpd = extract32(tcr, 24, 1);
10495         }
10496         epd = false;
10497     } else {
10498         /*
10499          * Bit 55 is always between the two regions, and is canonical for
10500          * determining if address tagging is enabled.
10501          */
10502         select = extract64(va, 55, 1);
10503         if (!select) {
10504             tsz = extract32(tcr, 0, 6);
10505             epd = extract32(tcr, 7, 1);
10506             using64k = extract32(tcr, 14, 1);
10507             using16k = extract32(tcr, 15, 1);
10508             hpd = extract64(tcr, 41, 1);
10509         } else {
10510             int tg = extract32(tcr, 30, 2);
10511             using16k = tg == 1;
10512             using64k = tg == 3;
10513             tsz = extract32(tcr, 16, 6);
10514             epd = extract32(tcr, 23, 1);
10515             hpd = extract64(tcr, 42, 1);
10516         }
10517     }
10518     tsz = MIN(tsz, 39);  /* TODO: ARMv8.4-TTST */
10519     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
10520 
10521     /* Present TBI as a composite with TBID.  */
10522     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
10523     if (!data) {
10524         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
10525     }
10526     tbi = (tbi >> select) & 1;
10527 
10528     return (ARMVAParameters) {
10529         .tsz = tsz,
10530         .select = select,
10531         .tbi = tbi,
10532         .epd = epd,
10533         .hpd = hpd,
10534         .using16k = using16k,
10535         .using64k = using64k,
10536     };
10537 }
10538 
10539 #ifndef CONFIG_USER_ONLY
10540 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
10541                                           ARMMMUIdx mmu_idx)
10542 {
10543     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
10544     uint32_t el = regime_el(env, mmu_idx);
10545     int select, tsz;
10546     bool epd, hpd;
10547 
10548     if (mmu_idx == ARMMMUIdx_Stage2) {
10549         /* VTCR */
10550         bool sext = extract32(tcr, 4, 1);
10551         bool sign = extract32(tcr, 3, 1);
10552 
10553         /*
10554          * If the sign-extend bit is not the same as t0sz[3], the result
10555          * is unpredictable. Flag this as a guest error.
10556          */
10557         if (sign != sext) {
10558             qemu_log_mask(LOG_GUEST_ERROR,
10559                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
10560         }
10561         tsz = sextract32(tcr, 0, 4) + 8;
10562         select = 0;
10563         hpd = false;
10564         epd = false;
10565     } else if (el == 2) {
10566         /* HTCR */
10567         tsz = extract32(tcr, 0, 3);
10568         select = 0;
10569         hpd = extract64(tcr, 24, 1);
10570         epd = false;
10571     } else {
10572         int t0sz = extract32(tcr, 0, 3);
10573         int t1sz = extract32(tcr, 16, 3);
10574 
10575         if (t1sz == 0) {
10576             select = va > (0xffffffffu >> t0sz);
10577         } else {
10578             /* Note that we will detect errors later.  */
10579             select = va >= ~(0xffffffffu >> t1sz);
10580         }
10581         if (!select) {
10582             tsz = t0sz;
10583             epd = extract32(tcr, 7, 1);
10584             hpd = extract64(tcr, 41, 1);
10585         } else {
10586             tsz = t1sz;
10587             epd = extract32(tcr, 23, 1);
10588             hpd = extract64(tcr, 42, 1);
10589         }
10590         /* For aarch32, hpd0 is not enabled without t2e as well.  */
10591         hpd &= extract32(tcr, 6, 1);
10592     }
10593 
10594     return (ARMVAParameters) {
10595         .tsz = tsz,
10596         .select = select,
10597         .epd = epd,
10598         .hpd = hpd,
10599     };
10600 }
10601 
10602 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
10603                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
10604                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
10605                                target_ulong *page_size_ptr,
10606                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10607 {
10608     ARMCPU *cpu = env_archcpu(env);
10609     CPUState *cs = CPU(cpu);
10610     /* Read an LPAE long-descriptor translation table. */
10611     ARMFaultType fault_type = ARMFault_Translation;
10612     uint32_t level;
10613     ARMVAParameters param;
10614     uint64_t ttbr;
10615     hwaddr descaddr, indexmask, indexmask_grainsize;
10616     uint32_t tableattrs;
10617     target_ulong page_size;
10618     uint32_t attrs;
10619     int32_t stride;
10620     int addrsize, inputsize;
10621     TCR *tcr = regime_tcr(env, mmu_idx);
10622     int ap, ns, xn, pxn;
10623     uint32_t el = regime_el(env, mmu_idx);
10624     uint64_t descaddrmask;
10625     bool aarch64 = arm_el_is_aa64(env, el);
10626     bool guarded = false;
10627 
10628     /* TODO:
10629      * This code does not handle the different format TCR for VTCR_EL2.
10630      * This code also does not support shareability levels.
10631      * Attribute and permission bit handling should also be checked when adding
10632      * support for those page table walks.
10633      */
10634     if (aarch64) {
10635         param = aa64_va_parameters(env, address, mmu_idx,
10636                                    access_type != MMU_INST_FETCH);
10637         level = 0;
10638         addrsize = 64 - 8 * param.tbi;
10639         inputsize = 64 - param.tsz;
10640     } else {
10641         param = aa32_va_parameters(env, address, mmu_idx);
10642         level = 1;
10643         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
10644         inputsize = addrsize - param.tsz;
10645     }
10646 
10647     /*
10648      * We determined the region when collecting the parameters, but we
10649      * have not yet validated that the address is valid for the region.
10650      * Extract the top bits and verify that they all match select.
10651      *
10652      * For aa32, if inputsize == addrsize, then we have selected the
10653      * region by exclusion in aa32_va_parameters and there is no more
10654      * validation to do here.
10655      */
10656     if (inputsize < addrsize) {
10657         target_ulong top_bits = sextract64(address, inputsize,
10658                                            addrsize - inputsize);
10659         if (-top_bits != param.select) {
10660             /* The gap between the two regions is a Translation fault */
10661             fault_type = ARMFault_Translation;
10662             goto do_fault;
10663         }
10664     }
10665 
10666     if (param.using64k) {
10667         stride = 13;
10668     } else if (param.using16k) {
10669         stride = 11;
10670     } else {
10671         stride = 9;
10672     }
10673 
10674     /* Note that QEMU ignores shareability and cacheability attributes,
10675      * so we don't need to do anything with the SH, ORGN, IRGN fields
10676      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
10677      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
10678      * implement any ASID-like capability so we can ignore it (instead
10679      * we will always flush the TLB any time the ASID is changed).
10680      */
10681     ttbr = regime_ttbr(env, mmu_idx, param.select);
10682 
10683     /* Here we should have set up all the parameters for the translation:
10684      * inputsize, ttbr, epd, stride, tbi
10685      */
10686 
10687     if (param.epd) {
10688         /* Translation table walk disabled => Translation fault on TLB miss
10689          * Note: This is always 0 on 64-bit EL2 and EL3.
10690          */
10691         goto do_fault;
10692     }
10693 
10694     if (mmu_idx != ARMMMUIdx_Stage2) {
10695         /* The starting level depends on the virtual address size (which can
10696          * be up to 48 bits) and the translation granule size. It indicates
10697          * the number of strides (stride bits at a time) needed to
10698          * consume the bits of the input address. In the pseudocode this is:
10699          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
10700          * where their 'inputsize' is our 'inputsize', 'grainsize' is
10701          * our 'stride + 3' and 'stride' is our 'stride'.
10702          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
10703          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
10704          * = 4 - (inputsize - 4) / stride;
10705          */
10706         level = 4 - (inputsize - 4) / stride;
10707     } else {
10708         /* For stage 2 translations the starting level is specified by the
10709          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
10710          */
10711         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
10712         uint32_t startlevel;
10713         bool ok;
10714 
10715         if (!aarch64 || stride == 9) {
10716             /* AArch32 or 4KB pages */
10717             startlevel = 2 - sl0;
10718         } else {
10719             /* 16KB or 64KB pages */
10720             startlevel = 3 - sl0;
10721         }
10722 
10723         /* Check that the starting level is valid. */
10724         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
10725                                 inputsize, stride);
10726         if (!ok) {
10727             fault_type = ARMFault_Translation;
10728             goto do_fault;
10729         }
10730         level = startlevel;
10731     }
10732 
10733     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
10734     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
10735 
10736     /* Now we can extract the actual base address from the TTBR */
10737     descaddr = extract64(ttbr, 0, 48);
10738     /*
10739      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
10740      * and also to mask out CnP (bit 0) which could validly be non-zero.
10741      */
10742     descaddr &= ~indexmask;
10743 
10744     /* The address field in the descriptor goes up to bit 39 for ARMv7
10745      * but up to bit 47 for ARMv8, but we use the descaddrmask
10746      * up to bit 39 for AArch32, because we don't need other bits in that case
10747      * to construct next descriptor address (anyway they should be all zeroes).
10748      */
10749     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
10750                    ~indexmask_grainsize;
10751 
10752     /* Secure accesses start with the page table in secure memory and
10753      * can be downgraded to non-secure at any step. Non-secure accesses
10754      * remain non-secure. We implement this by just ORing in the NSTable/NS
10755      * bits at each step.
10756      */
10757     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
10758     for (;;) {
10759         uint64_t descriptor;
10760         bool nstable;
10761 
10762         descaddr |= (address >> (stride * (4 - level))) & indexmask;
10763         descaddr &= ~7ULL;
10764         nstable = extract32(tableattrs, 4, 1);
10765         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
10766         if (fi->type != ARMFault_None) {
10767             goto do_fault;
10768         }
10769 
10770         if (!(descriptor & 1) ||
10771             (!(descriptor & 2) && (level == 3))) {
10772             /* Invalid, or the Reserved level 3 encoding */
10773             goto do_fault;
10774         }
10775         descaddr = descriptor & descaddrmask;
10776 
10777         if ((descriptor & 2) && (level < 3)) {
10778             /* Table entry. The top five bits are attributes which may
10779              * propagate down through lower levels of the table (and
10780              * which are all arranged so that 0 means "no effect", so
10781              * we can gather them up by ORing in the bits at each level).
10782              */
10783             tableattrs |= extract64(descriptor, 59, 5);
10784             level++;
10785             indexmask = indexmask_grainsize;
10786             continue;
10787         }
10788         /* Block entry at level 1 or 2, or page entry at level 3.
10789          * These are basically the same thing, although the number
10790          * of bits we pull in from the vaddr varies.
10791          */
10792         page_size = (1ULL << ((stride * (4 - level)) + 3));
10793         descaddr |= (address & (page_size - 1));
10794         /* Extract attributes from the descriptor */
10795         attrs = extract64(descriptor, 2, 10)
10796             | (extract64(descriptor, 52, 12) << 10);
10797 
10798         if (mmu_idx == ARMMMUIdx_Stage2) {
10799             /* Stage 2 table descriptors do not include any attribute fields */
10800             break;
10801         }
10802         /* Merge in attributes from table descriptors */
10803         attrs |= nstable << 3; /* NS */
10804         guarded = extract64(descriptor, 50, 1);  /* GP */
10805         if (param.hpd) {
10806             /* HPD disables all the table attributes except NSTable.  */
10807             break;
10808         }
10809         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
10810         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
10811          * means "force PL1 access only", which means forcing AP[1] to 0.
10812          */
10813         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
10814         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
10815         break;
10816     }
10817     /* Here descaddr is the final physical address, and attributes
10818      * are all in attrs.
10819      */
10820     fault_type = ARMFault_AccessFlag;
10821     if ((attrs & (1 << 8)) == 0) {
10822         /* Access flag */
10823         goto do_fault;
10824     }
10825 
10826     ap = extract32(attrs, 4, 2);
10827     xn = extract32(attrs, 12, 1);
10828 
10829     if (mmu_idx == ARMMMUIdx_Stage2) {
10830         ns = true;
10831         *prot = get_S2prot(env, ap, xn);
10832     } else {
10833         ns = extract32(attrs, 3, 1);
10834         pxn = extract32(attrs, 11, 1);
10835         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
10836     }
10837 
10838     fault_type = ARMFault_Permission;
10839     if (!(*prot & (1 << access_type))) {
10840         goto do_fault;
10841     }
10842 
10843     if (ns) {
10844         /* The NS bit will (as required by the architecture) have no effect if
10845          * the CPU doesn't support TZ or this is a non-secure translation
10846          * regime, because the attribute will already be non-secure.
10847          */
10848         txattrs->secure = false;
10849     }
10850     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
10851     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
10852         txattrs->target_tlb_bit0 = true;
10853     }
10854 
10855     if (cacheattrs != NULL) {
10856         if (mmu_idx == ARMMMUIdx_Stage2) {
10857             cacheattrs->attrs = convert_stage2_attrs(env,
10858                                                      extract32(attrs, 0, 4));
10859         } else {
10860             /* Index into MAIR registers for cache attributes */
10861             uint8_t attrindx = extract32(attrs, 0, 3);
10862             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
10863             assert(attrindx <= 7);
10864             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
10865         }
10866         cacheattrs->shareability = extract32(attrs, 6, 2);
10867     }
10868 
10869     *phys_ptr = descaddr;
10870     *page_size_ptr = page_size;
10871     return false;
10872 
10873 do_fault:
10874     fi->type = fault_type;
10875     fi->level = level;
10876     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
10877     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2);
10878     return true;
10879 }
10880 
10881 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
10882                                                 ARMMMUIdx mmu_idx,
10883                                                 int32_t address, int *prot)
10884 {
10885     if (!arm_feature(env, ARM_FEATURE_M)) {
10886         *prot = PAGE_READ | PAGE_WRITE;
10887         switch (address) {
10888         case 0xF0000000 ... 0xFFFFFFFF:
10889             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
10890                 /* hivecs execing is ok */
10891                 *prot |= PAGE_EXEC;
10892             }
10893             break;
10894         case 0x00000000 ... 0x7FFFFFFF:
10895             *prot |= PAGE_EXEC;
10896             break;
10897         }
10898     } else {
10899         /* Default system address map for M profile cores.
10900          * The architecture specifies which regions are execute-never;
10901          * at the MPU level no other checks are defined.
10902          */
10903         switch (address) {
10904         case 0x00000000 ... 0x1fffffff: /* ROM */
10905         case 0x20000000 ... 0x3fffffff: /* SRAM */
10906         case 0x60000000 ... 0x7fffffff: /* RAM */
10907         case 0x80000000 ... 0x9fffffff: /* RAM */
10908             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10909             break;
10910         case 0x40000000 ... 0x5fffffff: /* Peripheral */
10911         case 0xa0000000 ... 0xbfffffff: /* Device */
10912         case 0xc0000000 ... 0xdfffffff: /* Device */
10913         case 0xe0000000 ... 0xffffffff: /* System */
10914             *prot = PAGE_READ | PAGE_WRITE;
10915             break;
10916         default:
10917             g_assert_not_reached();
10918         }
10919     }
10920 }
10921 
10922 static bool pmsav7_use_background_region(ARMCPU *cpu,
10923                                          ARMMMUIdx mmu_idx, bool is_user)
10924 {
10925     /* Return true if we should use the default memory map as a
10926      * "background" region if there are no hits against any MPU regions.
10927      */
10928     CPUARMState *env = &cpu->env;
10929 
10930     if (is_user) {
10931         return false;
10932     }
10933 
10934     if (arm_feature(env, ARM_FEATURE_M)) {
10935         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
10936             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
10937     } else {
10938         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
10939     }
10940 }
10941 
10942 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
10943 {
10944     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
10945     return arm_feature(env, ARM_FEATURE_M) &&
10946         extract32(address, 20, 12) == 0xe00;
10947 }
10948 
10949 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
10950 {
10951     /* True if address is in the M profile system region
10952      * 0xe0000000 - 0xffffffff
10953      */
10954     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
10955 }
10956 
10957 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
10958                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
10959                                  hwaddr *phys_ptr, int *prot,
10960                                  target_ulong *page_size,
10961                                  ARMMMUFaultInfo *fi)
10962 {
10963     ARMCPU *cpu = env_archcpu(env);
10964     int n;
10965     bool is_user = regime_is_user(env, mmu_idx);
10966 
10967     *phys_ptr = address;
10968     *page_size = TARGET_PAGE_SIZE;
10969     *prot = 0;
10970 
10971     if (regime_translation_disabled(env, mmu_idx) ||
10972         m_is_ppb_region(env, address)) {
10973         /* MPU disabled or M profile PPB access: use default memory map.
10974          * The other case which uses the default memory map in the
10975          * v7M ARM ARM pseudocode is exception vector reads from the vector
10976          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
10977          * which always does a direct read using address_space_ldl(), rather
10978          * than going via this function, so we don't need to check that here.
10979          */
10980         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
10981     } else { /* MPU enabled */
10982         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
10983             /* region search */
10984             uint32_t base = env->pmsav7.drbar[n];
10985             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
10986             uint32_t rmask;
10987             bool srdis = false;
10988 
10989             if (!(env->pmsav7.drsr[n] & 0x1)) {
10990                 continue;
10991             }
10992 
10993             if (!rsize) {
10994                 qemu_log_mask(LOG_GUEST_ERROR,
10995                               "DRSR[%d]: Rsize field cannot be 0\n", n);
10996                 continue;
10997             }
10998             rsize++;
10999             rmask = (1ull << rsize) - 1;
11000 
11001             if (base & rmask) {
11002                 qemu_log_mask(LOG_GUEST_ERROR,
11003                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11004                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11005                               n, base, rmask);
11006                 continue;
11007             }
11008 
11009             if (address < base || address > base + rmask) {
11010                 /*
11011                  * Address not in this region. We must check whether the
11012                  * region covers addresses in the same page as our address.
11013                  * In that case we must not report a size that covers the
11014                  * whole page for a subsequent hit against a different MPU
11015                  * region or the background region, because it would result in
11016                  * incorrect TLB hits for subsequent accesses to addresses that
11017                  * are in this MPU region.
11018                  */
11019                 if (ranges_overlap(base, rmask,
11020                                    address & TARGET_PAGE_MASK,
11021                                    TARGET_PAGE_SIZE)) {
11022                     *page_size = 1;
11023                 }
11024                 continue;
11025             }
11026 
11027             /* Region matched */
11028 
11029             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11030                 int i, snd;
11031                 uint32_t srdis_mask;
11032 
11033                 rsize -= 3; /* sub region size (power of 2) */
11034                 snd = ((address - base) >> rsize) & 0x7;
11035                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11036 
11037                 srdis_mask = srdis ? 0x3 : 0x0;
11038                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11039                     /* This will check in groups of 2, 4 and then 8, whether
11040                      * the subregion bits are consistent. rsize is incremented
11041                      * back up to give the region size, considering consistent
11042                      * adjacent subregions as one region. Stop testing if rsize
11043                      * is already big enough for an entire QEMU page.
11044                      */
11045                     int snd_rounded = snd & ~(i - 1);
11046                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11047                                                      snd_rounded + 8, i);
11048                     if (srdis_mask ^ srdis_multi) {
11049                         break;
11050                     }
11051                     srdis_mask = (srdis_mask << i) | srdis_mask;
11052                     rsize++;
11053                 }
11054             }
11055             if (srdis) {
11056                 continue;
11057             }
11058             if (rsize < TARGET_PAGE_BITS) {
11059                 *page_size = 1 << rsize;
11060             }
11061             break;
11062         }
11063 
11064         if (n == -1) { /* no hits */
11065             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11066                 /* background fault */
11067                 fi->type = ARMFault_Background;
11068                 return true;
11069             }
11070             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11071         } else { /* a MPU hit! */
11072             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
11073             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
11074 
11075             if (m_is_system_region(env, address)) {
11076                 /* System space is always execute never */
11077                 xn = 1;
11078             }
11079 
11080             if (is_user) { /* User mode AP bit decoding */
11081                 switch (ap) {
11082                 case 0:
11083                 case 1:
11084                 case 5:
11085                     break; /* no access */
11086                 case 3:
11087                     *prot |= PAGE_WRITE;
11088                     /* fall through */
11089                 case 2:
11090                 case 6:
11091                     *prot |= PAGE_READ | PAGE_EXEC;
11092                     break;
11093                 case 7:
11094                     /* for v7M, same as 6; for R profile a reserved value */
11095                     if (arm_feature(env, ARM_FEATURE_M)) {
11096                         *prot |= PAGE_READ | PAGE_EXEC;
11097                         break;
11098                     }
11099                     /* fall through */
11100                 default:
11101                     qemu_log_mask(LOG_GUEST_ERROR,
11102                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11103                                   PRIx32 "\n", n, ap);
11104                 }
11105             } else { /* Priv. mode AP bits decoding */
11106                 switch (ap) {
11107                 case 0:
11108                     break; /* no access */
11109                 case 1:
11110                 case 2:
11111                 case 3:
11112                     *prot |= PAGE_WRITE;
11113                     /* fall through */
11114                 case 5:
11115                 case 6:
11116                     *prot |= PAGE_READ | PAGE_EXEC;
11117                     break;
11118                 case 7:
11119                     /* for v7M, same as 6; for R profile a reserved value */
11120                     if (arm_feature(env, ARM_FEATURE_M)) {
11121                         *prot |= PAGE_READ | PAGE_EXEC;
11122                         break;
11123                     }
11124                     /* fall through */
11125                 default:
11126                     qemu_log_mask(LOG_GUEST_ERROR,
11127                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11128                                   PRIx32 "\n", n, ap);
11129                 }
11130             }
11131 
11132             /* execute never */
11133             if (xn) {
11134                 *prot &= ~PAGE_EXEC;
11135             }
11136         }
11137     }
11138 
11139     fi->type = ARMFault_Permission;
11140     fi->level = 1;
11141     return !(*prot & (1 << access_type));
11142 }
11143 
11144 static bool v8m_is_sau_exempt(CPUARMState *env,
11145                               uint32_t address, MMUAccessType access_type)
11146 {
11147     /* The architecture specifies that certain address ranges are
11148      * exempt from v8M SAU/IDAU checks.
11149      */
11150     return
11151         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
11152         (address >= 0xe0000000 && address <= 0xe0002fff) ||
11153         (address >= 0xe000e000 && address <= 0xe000efff) ||
11154         (address >= 0xe002e000 && address <= 0xe002efff) ||
11155         (address >= 0xe0040000 && address <= 0xe0041fff) ||
11156         (address >= 0xe00ff000 && address <= 0xe00fffff);
11157 }
11158 
11159 void v8m_security_lookup(CPUARMState *env, uint32_t address,
11160                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
11161                                 V8M_SAttributes *sattrs)
11162 {
11163     /* Look up the security attributes for this address. Compare the
11164      * pseudocode SecurityCheck() function.
11165      * We assume the caller has zero-initialized *sattrs.
11166      */
11167     ARMCPU *cpu = env_archcpu(env);
11168     int r;
11169     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
11170     int idau_region = IREGION_NOTVALID;
11171     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11172     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11173 
11174     if (cpu->idau) {
11175         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
11176         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
11177 
11178         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
11179                    &idau_nsc);
11180     }
11181 
11182     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
11183         /* 0xf0000000..0xffffffff is always S for insn fetches */
11184         return;
11185     }
11186 
11187     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
11188         sattrs->ns = !regime_is_secure(env, mmu_idx);
11189         return;
11190     }
11191 
11192     if (idau_region != IREGION_NOTVALID) {
11193         sattrs->irvalid = true;
11194         sattrs->iregion = idau_region;
11195     }
11196 
11197     switch (env->sau.ctrl & 3) {
11198     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
11199         break;
11200     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
11201         sattrs->ns = true;
11202         break;
11203     default: /* SAU.ENABLE == 1 */
11204         for (r = 0; r < cpu->sau_sregion; r++) {
11205             if (env->sau.rlar[r] & 1) {
11206                 uint32_t base = env->sau.rbar[r] & ~0x1f;
11207                 uint32_t limit = env->sau.rlar[r] | 0x1f;
11208 
11209                 if (base <= address && limit >= address) {
11210                     if (base > addr_page_base || limit < addr_page_limit) {
11211                         sattrs->subpage = true;
11212                     }
11213                     if (sattrs->srvalid) {
11214                         /* If we hit in more than one region then we must report
11215                          * as Secure, not NS-Callable, with no valid region
11216                          * number info.
11217                          */
11218                         sattrs->ns = false;
11219                         sattrs->nsc = false;
11220                         sattrs->sregion = 0;
11221                         sattrs->srvalid = false;
11222                         break;
11223                     } else {
11224                         if (env->sau.rlar[r] & 2) {
11225                             sattrs->nsc = true;
11226                         } else {
11227                             sattrs->ns = true;
11228                         }
11229                         sattrs->srvalid = true;
11230                         sattrs->sregion = r;
11231                     }
11232                 } else {
11233                     /*
11234                      * Address not in this region. We must check whether the
11235                      * region covers addresses in the same page as our address.
11236                      * In that case we must not report a size that covers the
11237                      * whole page for a subsequent hit against a different MPU
11238                      * region or the background region, because it would result
11239                      * in incorrect TLB hits for subsequent accesses to
11240                      * addresses that are in this MPU region.
11241                      */
11242                     if (limit >= base &&
11243                         ranges_overlap(base, limit - base + 1,
11244                                        addr_page_base,
11245                                        TARGET_PAGE_SIZE)) {
11246                         sattrs->subpage = true;
11247                     }
11248                 }
11249             }
11250         }
11251         break;
11252     }
11253 
11254     /*
11255      * The IDAU will override the SAU lookup results if it specifies
11256      * higher security than the SAU does.
11257      */
11258     if (!idau_ns) {
11259         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
11260             sattrs->ns = false;
11261             sattrs->nsc = idau_nsc;
11262         }
11263     }
11264 }
11265 
11266 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
11267                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
11268                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
11269                               int *prot, bool *is_subpage,
11270                               ARMMMUFaultInfo *fi, uint32_t *mregion)
11271 {
11272     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
11273      * that a full phys-to-virt translation does).
11274      * mregion is (if not NULL) set to the region number which matched,
11275      * or -1 if no region number is returned (MPU off, address did not
11276      * hit a region, address hit in multiple regions).
11277      * We set is_subpage to true if the region hit doesn't cover the
11278      * entire TARGET_PAGE the address is within.
11279      */
11280     ARMCPU *cpu = env_archcpu(env);
11281     bool is_user = regime_is_user(env, mmu_idx);
11282     uint32_t secure = regime_is_secure(env, mmu_idx);
11283     int n;
11284     int matchregion = -1;
11285     bool hit = false;
11286     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11287     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11288 
11289     *is_subpage = false;
11290     *phys_ptr = address;
11291     *prot = 0;
11292     if (mregion) {
11293         *mregion = -1;
11294     }
11295 
11296     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
11297      * was an exception vector read from the vector table (which is always
11298      * done using the default system address map), because those accesses
11299      * are done in arm_v7m_load_vector(), which always does a direct
11300      * read using address_space_ldl(), rather than going via this function.
11301      */
11302     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
11303         hit = true;
11304     } else if (m_is_ppb_region(env, address)) {
11305         hit = true;
11306     } else {
11307         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11308             hit = true;
11309         }
11310 
11311         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11312             /* region search */
11313             /* Note that the base address is bits [31:5] from the register
11314              * with bits [4:0] all zeroes, but the limit address is bits
11315              * [31:5] from the register with bits [4:0] all ones.
11316              */
11317             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
11318             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
11319 
11320             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
11321                 /* Region disabled */
11322                 continue;
11323             }
11324 
11325             if (address < base || address > limit) {
11326                 /*
11327                  * Address not in this region. We must check whether the
11328                  * region covers addresses in the same page as our address.
11329                  * In that case we must not report a size that covers the
11330                  * whole page for a subsequent hit against a different MPU
11331                  * region or the background region, because it would result in
11332                  * incorrect TLB hits for subsequent accesses to addresses that
11333                  * are in this MPU region.
11334                  */
11335                 if (limit >= base &&
11336                     ranges_overlap(base, limit - base + 1,
11337                                    addr_page_base,
11338                                    TARGET_PAGE_SIZE)) {
11339                     *is_subpage = true;
11340                 }
11341                 continue;
11342             }
11343 
11344             if (base > addr_page_base || limit < addr_page_limit) {
11345                 *is_subpage = true;
11346             }
11347 
11348             if (matchregion != -1) {
11349                 /* Multiple regions match -- always a failure (unlike
11350                  * PMSAv7 where highest-numbered-region wins)
11351                  */
11352                 fi->type = ARMFault_Permission;
11353                 fi->level = 1;
11354                 return true;
11355             }
11356 
11357             matchregion = n;
11358             hit = true;
11359         }
11360     }
11361 
11362     if (!hit) {
11363         /* background fault */
11364         fi->type = ARMFault_Background;
11365         return true;
11366     }
11367 
11368     if (matchregion == -1) {
11369         /* hit using the background region */
11370         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11371     } else {
11372         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
11373         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
11374 
11375         if (m_is_system_region(env, address)) {
11376             /* System space is always execute never */
11377             xn = 1;
11378         }
11379 
11380         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
11381         if (*prot && !xn) {
11382             *prot |= PAGE_EXEC;
11383         }
11384         /* We don't need to look the attribute up in the MAIR0/MAIR1
11385          * registers because that only tells us about cacheability.
11386          */
11387         if (mregion) {
11388             *mregion = matchregion;
11389         }
11390     }
11391 
11392     fi->type = ARMFault_Permission;
11393     fi->level = 1;
11394     return !(*prot & (1 << access_type));
11395 }
11396 
11397 
11398 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
11399                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11400                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
11401                                  int *prot, target_ulong *page_size,
11402                                  ARMMMUFaultInfo *fi)
11403 {
11404     uint32_t secure = regime_is_secure(env, mmu_idx);
11405     V8M_SAttributes sattrs = {};
11406     bool ret;
11407     bool mpu_is_subpage;
11408 
11409     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
11410         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
11411         if (access_type == MMU_INST_FETCH) {
11412             /* Instruction fetches always use the MMU bank and the
11413              * transaction attribute determined by the fetch address,
11414              * regardless of CPU state. This is painful for QEMU
11415              * to handle, because it would mean we need to encode
11416              * into the mmu_idx not just the (user, negpri) information
11417              * for the current security state but also that for the
11418              * other security state, which would balloon the number
11419              * of mmu_idx values needed alarmingly.
11420              * Fortunately we can avoid this because it's not actually
11421              * possible to arbitrarily execute code from memory with
11422              * the wrong security attribute: it will always generate
11423              * an exception of some kind or another, apart from the
11424              * special case of an NS CPU executing an SG instruction
11425              * in S&NSC memory. So we always just fail the translation
11426              * here and sort things out in the exception handler
11427              * (including possibly emulating an SG instruction).
11428              */
11429             if (sattrs.ns != !secure) {
11430                 if (sattrs.nsc) {
11431                     fi->type = ARMFault_QEMU_NSCExec;
11432                 } else {
11433                     fi->type = ARMFault_QEMU_SFault;
11434                 }
11435                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
11436                 *phys_ptr = address;
11437                 *prot = 0;
11438                 return true;
11439             }
11440         } else {
11441             /* For data accesses we always use the MMU bank indicated
11442              * by the current CPU state, but the security attributes
11443              * might downgrade a secure access to nonsecure.
11444              */
11445             if (sattrs.ns) {
11446                 txattrs->secure = false;
11447             } else if (!secure) {
11448                 /* NS access to S memory must fault.
11449                  * Architecturally we should first check whether the
11450                  * MPU information for this address indicates that we
11451                  * are doing an unaligned access to Device memory, which
11452                  * should generate a UsageFault instead. QEMU does not
11453                  * currently check for that kind of unaligned access though.
11454                  * If we added it we would need to do so as a special case
11455                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
11456                  */
11457                 fi->type = ARMFault_QEMU_SFault;
11458                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
11459                 *phys_ptr = address;
11460                 *prot = 0;
11461                 return true;
11462             }
11463         }
11464     }
11465 
11466     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
11467                             txattrs, prot, &mpu_is_subpage, fi, NULL);
11468     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
11469     return ret;
11470 }
11471 
11472 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
11473                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11474                                  hwaddr *phys_ptr, int *prot,
11475                                  ARMMMUFaultInfo *fi)
11476 {
11477     int n;
11478     uint32_t mask;
11479     uint32_t base;
11480     bool is_user = regime_is_user(env, mmu_idx);
11481 
11482     if (regime_translation_disabled(env, mmu_idx)) {
11483         /* MPU disabled.  */
11484         *phys_ptr = address;
11485         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11486         return false;
11487     }
11488 
11489     *phys_ptr = address;
11490     for (n = 7; n >= 0; n--) {
11491         base = env->cp15.c6_region[n];
11492         if ((base & 1) == 0) {
11493             continue;
11494         }
11495         mask = 1 << ((base >> 1) & 0x1f);
11496         /* Keep this shift separate from the above to avoid an
11497            (undefined) << 32.  */
11498         mask = (mask << 1) - 1;
11499         if (((base ^ address) & ~mask) == 0) {
11500             break;
11501         }
11502     }
11503     if (n < 0) {
11504         fi->type = ARMFault_Background;
11505         return true;
11506     }
11507 
11508     if (access_type == MMU_INST_FETCH) {
11509         mask = env->cp15.pmsav5_insn_ap;
11510     } else {
11511         mask = env->cp15.pmsav5_data_ap;
11512     }
11513     mask = (mask >> (n * 4)) & 0xf;
11514     switch (mask) {
11515     case 0:
11516         fi->type = ARMFault_Permission;
11517         fi->level = 1;
11518         return true;
11519     case 1:
11520         if (is_user) {
11521             fi->type = ARMFault_Permission;
11522             fi->level = 1;
11523             return true;
11524         }
11525         *prot = PAGE_READ | PAGE_WRITE;
11526         break;
11527     case 2:
11528         *prot = PAGE_READ;
11529         if (!is_user) {
11530             *prot |= PAGE_WRITE;
11531         }
11532         break;
11533     case 3:
11534         *prot = PAGE_READ | PAGE_WRITE;
11535         break;
11536     case 5:
11537         if (is_user) {
11538             fi->type = ARMFault_Permission;
11539             fi->level = 1;
11540             return true;
11541         }
11542         *prot = PAGE_READ;
11543         break;
11544     case 6:
11545         *prot = PAGE_READ;
11546         break;
11547     default:
11548         /* Bad permission.  */
11549         fi->type = ARMFault_Permission;
11550         fi->level = 1;
11551         return true;
11552     }
11553     *prot |= PAGE_EXEC;
11554     return false;
11555 }
11556 
11557 /* Combine either inner or outer cacheability attributes for normal
11558  * memory, according to table D4-42 and pseudocode procedure
11559  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
11560  *
11561  * NB: only stage 1 includes allocation hints (RW bits), leading to
11562  * some asymmetry.
11563  */
11564 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
11565 {
11566     if (s1 == 4 || s2 == 4) {
11567         /* non-cacheable has precedence */
11568         return 4;
11569     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
11570         /* stage 1 write-through takes precedence */
11571         return s1;
11572     } else if (extract32(s2, 2, 2) == 2) {
11573         /* stage 2 write-through takes precedence, but the allocation hint
11574          * is still taken from stage 1
11575          */
11576         return (2 << 2) | extract32(s1, 0, 2);
11577     } else { /* write-back */
11578         return s1;
11579     }
11580 }
11581 
11582 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
11583  * and CombineS1S2Desc()
11584  *
11585  * @s1:      Attributes from stage 1 walk
11586  * @s2:      Attributes from stage 2 walk
11587  */
11588 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
11589 {
11590     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
11591     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
11592     ARMCacheAttrs ret;
11593 
11594     /* Combine shareability attributes (table D4-43) */
11595     if (s1.shareability == 2 || s2.shareability == 2) {
11596         /* if either are outer-shareable, the result is outer-shareable */
11597         ret.shareability = 2;
11598     } else if (s1.shareability == 3 || s2.shareability == 3) {
11599         /* if either are inner-shareable, the result is inner-shareable */
11600         ret.shareability = 3;
11601     } else {
11602         /* both non-shareable */
11603         ret.shareability = 0;
11604     }
11605 
11606     /* Combine memory type and cacheability attributes */
11607     if (s1hi == 0 || s2hi == 0) {
11608         /* Device has precedence over normal */
11609         if (s1lo == 0 || s2lo == 0) {
11610             /* nGnRnE has precedence over anything */
11611             ret.attrs = 0;
11612         } else if (s1lo == 4 || s2lo == 4) {
11613             /* non-Reordering has precedence over Reordering */
11614             ret.attrs = 4;  /* nGnRE */
11615         } else if (s1lo == 8 || s2lo == 8) {
11616             /* non-Gathering has precedence over Gathering */
11617             ret.attrs = 8;  /* nGRE */
11618         } else {
11619             ret.attrs = 0xc; /* GRE */
11620         }
11621 
11622         /* Any location for which the resultant memory type is any
11623          * type of Device memory is always treated as Outer Shareable.
11624          */
11625         ret.shareability = 2;
11626     } else { /* Normal memory */
11627         /* Outer/inner cacheability combine independently */
11628         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
11629                   | combine_cacheattr_nibble(s1lo, s2lo);
11630 
11631         if (ret.attrs == 0x44) {
11632             /* Any location for which the resultant memory type is Normal
11633              * Inner Non-cacheable, Outer Non-cacheable is always treated
11634              * as Outer Shareable.
11635              */
11636             ret.shareability = 2;
11637         }
11638     }
11639 
11640     return ret;
11641 }
11642 
11643 
11644 /* get_phys_addr - get the physical address for this virtual address
11645  *
11646  * Find the physical address corresponding to the given virtual address,
11647  * by doing a translation table walk on MMU based systems or using the
11648  * MPU state on MPU based systems.
11649  *
11650  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11651  * prot and page_size may not be filled in, and the populated fsr value provides
11652  * information on why the translation aborted, in the format of a
11653  * DFSR/IFSR fault register, with the following caveats:
11654  *  * we honour the short vs long DFSR format differences.
11655  *  * the WnR bit is never set (the caller must do this).
11656  *  * for PSMAv5 based systems we don't bother to return a full FSR format
11657  *    value.
11658  *
11659  * @env: CPUARMState
11660  * @address: virtual address to get physical address for
11661  * @access_type: 0 for read, 1 for write, 2 for execute
11662  * @mmu_idx: MMU index indicating required translation regime
11663  * @phys_ptr: set to the physical address corresponding to the virtual address
11664  * @attrs: set to the memory transaction attributes to use
11665  * @prot: set to the permissions for the page containing phys_ptr
11666  * @page_size: set to the size of the page containing phys_ptr
11667  * @fi: set to fault info if the translation fails
11668  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11669  */
11670 bool get_phys_addr(CPUARMState *env, target_ulong address,
11671                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
11672                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
11673                    target_ulong *page_size,
11674                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11675 {
11676     if (mmu_idx == ARMMMUIdx_E10_0 ||
11677         mmu_idx == ARMMMUIdx_E10_1 ||
11678         mmu_idx == ARMMMUIdx_E10_1_PAN) {
11679         /* Call ourselves recursively to do the stage 1 and then stage 2
11680          * translations.
11681          */
11682         if (arm_feature(env, ARM_FEATURE_EL2)) {
11683             hwaddr ipa;
11684             int s2_prot;
11685             int ret;
11686             ARMCacheAttrs cacheattrs2 = {};
11687 
11688             ret = get_phys_addr(env, address, access_type,
11689                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
11690                                 prot, page_size, fi, cacheattrs);
11691 
11692             /* If S1 fails or S2 is disabled, return early.  */
11693             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
11694                 *phys_ptr = ipa;
11695                 return ret;
11696             }
11697 
11698             /* S1 is done. Now do S2 translation.  */
11699             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_Stage2,
11700                                      phys_ptr, attrs, &s2_prot,
11701                                      page_size, fi,
11702                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
11703             fi->s2addr = ipa;
11704             /* Combine the S1 and S2 perms.  */
11705             *prot &= s2_prot;
11706 
11707             /* Combine the S1 and S2 cache attributes, if needed */
11708             if (!ret && cacheattrs != NULL) {
11709                 if (env->cp15.hcr_el2 & HCR_DC) {
11710                     /*
11711                      * HCR.DC forces the first stage attributes to
11712                      *  Normal Non-Shareable,
11713                      *  Inner Write-Back Read-Allocate Write-Allocate,
11714                      *  Outer Write-Back Read-Allocate Write-Allocate.
11715                      */
11716                     cacheattrs->attrs = 0xff;
11717                     cacheattrs->shareability = 0;
11718                 }
11719                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
11720             }
11721 
11722             return ret;
11723         } else {
11724             /*
11725              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
11726              */
11727             mmu_idx = stage_1_mmu_idx(mmu_idx);
11728         }
11729     }
11730 
11731     /* The page table entries may downgrade secure to non-secure, but
11732      * cannot upgrade an non-secure translation regime's attributes
11733      * to secure.
11734      */
11735     attrs->secure = regime_is_secure(env, mmu_idx);
11736     attrs->user = regime_is_user(env, mmu_idx);
11737 
11738     /* Fast Context Switch Extension. This doesn't exist at all in v8.
11739      * In v7 and earlier it affects all stage 1 translations.
11740      */
11741     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
11742         && !arm_feature(env, ARM_FEATURE_V8)) {
11743         if (regime_el(env, mmu_idx) == 3) {
11744             address += env->cp15.fcseidr_s;
11745         } else {
11746             address += env->cp15.fcseidr_ns;
11747         }
11748     }
11749 
11750     if (arm_feature(env, ARM_FEATURE_PMSA)) {
11751         bool ret;
11752         *page_size = TARGET_PAGE_SIZE;
11753 
11754         if (arm_feature(env, ARM_FEATURE_V8)) {
11755             /* PMSAv8 */
11756             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
11757                                        phys_ptr, attrs, prot, page_size, fi);
11758         } else if (arm_feature(env, ARM_FEATURE_V7)) {
11759             /* PMSAv7 */
11760             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
11761                                        phys_ptr, prot, page_size, fi);
11762         } else {
11763             /* Pre-v7 MPU */
11764             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
11765                                        phys_ptr, prot, fi);
11766         }
11767         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
11768                       " mmu_idx %u -> %s (prot %c%c%c)\n",
11769                       access_type == MMU_DATA_LOAD ? "reading" :
11770                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
11771                       (uint32_t)address, mmu_idx,
11772                       ret ? "Miss" : "Hit",
11773                       *prot & PAGE_READ ? 'r' : '-',
11774                       *prot & PAGE_WRITE ? 'w' : '-',
11775                       *prot & PAGE_EXEC ? 'x' : '-');
11776 
11777         return ret;
11778     }
11779 
11780     /* Definitely a real MMU, not an MPU */
11781 
11782     if (regime_translation_disabled(env, mmu_idx)) {
11783         /* MMU disabled. */
11784         *phys_ptr = address;
11785         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11786         *page_size = TARGET_PAGE_SIZE;
11787         return 0;
11788     }
11789 
11790     if (regime_using_lpae_format(env, mmu_idx)) {
11791         return get_phys_addr_lpae(env, address, access_type, mmu_idx,
11792                                   phys_ptr, attrs, prot, page_size,
11793                                   fi, cacheattrs);
11794     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
11795         return get_phys_addr_v6(env, address, access_type, mmu_idx,
11796                                 phys_ptr, attrs, prot, page_size, fi);
11797     } else {
11798         return get_phys_addr_v5(env, address, access_type, mmu_idx,
11799                                     phys_ptr, prot, page_size, fi);
11800     }
11801 }
11802 
11803 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
11804                                          MemTxAttrs *attrs)
11805 {
11806     ARMCPU *cpu = ARM_CPU(cs);
11807     CPUARMState *env = &cpu->env;
11808     hwaddr phys_addr;
11809     target_ulong page_size;
11810     int prot;
11811     bool ret;
11812     ARMMMUFaultInfo fi = {};
11813     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
11814 
11815     *attrs = (MemTxAttrs) {};
11816 
11817     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
11818                         attrs, &prot, &page_size, &fi, NULL);
11819 
11820     if (ret) {
11821         return -1;
11822     }
11823     return phys_addr;
11824 }
11825 
11826 #endif
11827 
11828 /* Note that signed overflow is undefined in C.  The following routines are
11829    careful to use unsigned types where modulo arithmetic is required.
11830    Failure to do so _will_ break on newer gcc.  */
11831 
11832 /* Signed saturating arithmetic.  */
11833 
11834 /* Perform 16-bit signed saturating addition.  */
11835 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
11836 {
11837     uint16_t res;
11838 
11839     res = a + b;
11840     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
11841         if (a & 0x8000)
11842             res = 0x8000;
11843         else
11844             res = 0x7fff;
11845     }
11846     return res;
11847 }
11848 
11849 /* Perform 8-bit signed saturating addition.  */
11850 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
11851 {
11852     uint8_t res;
11853 
11854     res = a + b;
11855     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
11856         if (a & 0x80)
11857             res = 0x80;
11858         else
11859             res = 0x7f;
11860     }
11861     return res;
11862 }
11863 
11864 /* Perform 16-bit signed saturating subtraction.  */
11865 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
11866 {
11867     uint16_t res;
11868 
11869     res = a - b;
11870     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
11871         if (a & 0x8000)
11872             res = 0x8000;
11873         else
11874             res = 0x7fff;
11875     }
11876     return res;
11877 }
11878 
11879 /* Perform 8-bit signed saturating subtraction.  */
11880 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
11881 {
11882     uint8_t res;
11883 
11884     res = a - b;
11885     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
11886         if (a & 0x80)
11887             res = 0x80;
11888         else
11889             res = 0x7f;
11890     }
11891     return res;
11892 }
11893 
11894 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
11895 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
11896 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
11897 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
11898 #define PFX q
11899 
11900 #include "op_addsub.h"
11901 
11902 /* Unsigned saturating arithmetic.  */
11903 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
11904 {
11905     uint16_t res;
11906     res = a + b;
11907     if (res < a)
11908         res = 0xffff;
11909     return res;
11910 }
11911 
11912 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
11913 {
11914     if (a > b)
11915         return a - b;
11916     else
11917         return 0;
11918 }
11919 
11920 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
11921 {
11922     uint8_t res;
11923     res = a + b;
11924     if (res < a)
11925         res = 0xff;
11926     return res;
11927 }
11928 
11929 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
11930 {
11931     if (a > b)
11932         return a - b;
11933     else
11934         return 0;
11935 }
11936 
11937 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
11938 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
11939 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
11940 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
11941 #define PFX uq
11942 
11943 #include "op_addsub.h"
11944 
11945 /* Signed modulo arithmetic.  */
11946 #define SARITH16(a, b, n, op) do { \
11947     int32_t sum; \
11948     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
11949     RESULT(sum, n, 16); \
11950     if (sum >= 0) \
11951         ge |= 3 << (n * 2); \
11952     } while(0)
11953 
11954 #define SARITH8(a, b, n, op) do { \
11955     int32_t sum; \
11956     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
11957     RESULT(sum, n, 8); \
11958     if (sum >= 0) \
11959         ge |= 1 << n; \
11960     } while(0)
11961 
11962 
11963 #define ADD16(a, b, n) SARITH16(a, b, n, +)
11964 #define SUB16(a, b, n) SARITH16(a, b, n, -)
11965 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
11966 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
11967 #define PFX s
11968 #define ARITH_GE
11969 
11970 #include "op_addsub.h"
11971 
11972 /* Unsigned modulo arithmetic.  */
11973 #define ADD16(a, b, n) do { \
11974     uint32_t sum; \
11975     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
11976     RESULT(sum, n, 16); \
11977     if ((sum >> 16) == 1) \
11978         ge |= 3 << (n * 2); \
11979     } while(0)
11980 
11981 #define ADD8(a, b, n) do { \
11982     uint32_t sum; \
11983     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
11984     RESULT(sum, n, 8); \
11985     if ((sum >> 8) == 1) \
11986         ge |= 1 << n; \
11987     } while(0)
11988 
11989 #define SUB16(a, b, n) do { \
11990     uint32_t sum; \
11991     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
11992     RESULT(sum, n, 16); \
11993     if ((sum >> 16) == 0) \
11994         ge |= 3 << (n * 2); \
11995     } while(0)
11996 
11997 #define SUB8(a, b, n) do { \
11998     uint32_t sum; \
11999     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
12000     RESULT(sum, n, 8); \
12001     if ((sum >> 8) == 0) \
12002         ge |= 1 << n; \
12003     } while(0)
12004 
12005 #define PFX u
12006 #define ARITH_GE
12007 
12008 #include "op_addsub.h"
12009 
12010 /* Halved signed arithmetic.  */
12011 #define ADD16(a, b, n) \
12012   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
12013 #define SUB16(a, b, n) \
12014   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
12015 #define ADD8(a, b, n) \
12016   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
12017 #define SUB8(a, b, n) \
12018   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
12019 #define PFX sh
12020 
12021 #include "op_addsub.h"
12022 
12023 /* Halved unsigned arithmetic.  */
12024 #define ADD16(a, b, n) \
12025   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12026 #define SUB16(a, b, n) \
12027   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12028 #define ADD8(a, b, n) \
12029   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12030 #define SUB8(a, b, n) \
12031   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12032 #define PFX uh
12033 
12034 #include "op_addsub.h"
12035 
12036 static inline uint8_t do_usad(uint8_t a, uint8_t b)
12037 {
12038     if (a > b)
12039         return a - b;
12040     else
12041         return b - a;
12042 }
12043 
12044 /* Unsigned sum of absolute byte differences.  */
12045 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
12046 {
12047     uint32_t sum;
12048     sum = do_usad(a, b);
12049     sum += do_usad(a >> 8, b >> 8);
12050     sum += do_usad(a >> 16, b >>16);
12051     sum += do_usad(a >> 24, b >> 24);
12052     return sum;
12053 }
12054 
12055 /* For ARMv6 SEL instruction.  */
12056 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
12057 {
12058     uint32_t mask;
12059 
12060     mask = 0;
12061     if (flags & 1)
12062         mask |= 0xff;
12063     if (flags & 2)
12064         mask |= 0xff00;
12065     if (flags & 4)
12066         mask |= 0xff0000;
12067     if (flags & 8)
12068         mask |= 0xff000000;
12069     return (a & mask) | (b & ~mask);
12070 }
12071 
12072 /* CRC helpers.
12073  * The upper bytes of val (above the number specified by 'bytes') must have
12074  * been zeroed out by the caller.
12075  */
12076 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12077 {
12078     uint8_t buf[4];
12079 
12080     stl_le_p(buf, val);
12081 
12082     /* zlib crc32 converts the accumulator and output to one's complement.  */
12083     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12084 }
12085 
12086 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12087 {
12088     uint8_t buf[4];
12089 
12090     stl_le_p(buf, val);
12091 
12092     /* Linux crc32c converts the output to one's complement.  */
12093     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12094 }
12095 
12096 /* Return the exception level to which FP-disabled exceptions should
12097  * be taken, or 0 if FP is enabled.
12098  */
12099 int fp_exception_el(CPUARMState *env, int cur_el)
12100 {
12101 #ifndef CONFIG_USER_ONLY
12102     /* CPACR and the CPTR registers don't exist before v6, so FP is
12103      * always accessible
12104      */
12105     if (!arm_feature(env, ARM_FEATURE_V6)) {
12106         return 0;
12107     }
12108 
12109     if (arm_feature(env, ARM_FEATURE_M)) {
12110         /* CPACR can cause a NOCP UsageFault taken to current security state */
12111         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
12112             return 1;
12113         }
12114 
12115         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
12116             if (!extract32(env->v7m.nsacr, 10, 1)) {
12117                 /* FP insns cause a NOCP UsageFault taken to Secure */
12118                 return 3;
12119             }
12120         }
12121 
12122         return 0;
12123     }
12124 
12125     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12126      * 0, 2 : trap EL0 and EL1/PL1 accesses
12127      * 1    : trap only EL0 accesses
12128      * 3    : trap no accesses
12129      * This register is ignored if E2H+TGE are both set.
12130      */
12131     if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
12132         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12133 
12134         switch (fpen) {
12135         case 0:
12136         case 2:
12137             if (cur_el == 0 || cur_el == 1) {
12138                 /* Trap to PL1, which might be EL1 or EL3 */
12139                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12140                     return 3;
12141                 }
12142                 return 1;
12143             }
12144             if (cur_el == 3 && !is_a64(env)) {
12145                 /* Secure PL1 running at EL3 */
12146                 return 3;
12147             }
12148             break;
12149         case 1:
12150             if (cur_el == 0) {
12151                 return 1;
12152             }
12153             break;
12154         case 3:
12155             break;
12156         }
12157     }
12158 
12159     /*
12160      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
12161      * to control non-secure access to the FPU. It doesn't have any
12162      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
12163      */
12164     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
12165          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
12166         if (!extract32(env->cp15.nsacr, 10, 1)) {
12167             /* FP insns act as UNDEF */
12168             return cur_el == 2 ? 2 : 1;
12169         }
12170     }
12171 
12172     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12173      * check because zero bits in the registers mean "don't trap".
12174      */
12175 
12176     /* CPTR_EL2 : present in v7VE or v8 */
12177     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12178         && !arm_is_secure_below_el3(env)) {
12179         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12180         return 2;
12181     }
12182 
12183     /* CPTR_EL3 : present in v8 */
12184     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12185         /* Trap all FP ops to EL3 */
12186         return 3;
12187     }
12188 #endif
12189     return 0;
12190 }
12191 
12192 /* Return the exception level we're running at if this is our mmu_idx */
12193 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
12194 {
12195     if (mmu_idx & ARM_MMU_IDX_M) {
12196         return mmu_idx & ARM_MMU_IDX_M_PRIV;
12197     }
12198 
12199     switch (mmu_idx) {
12200     case ARMMMUIdx_E10_0:
12201     case ARMMMUIdx_E20_0:
12202     case ARMMMUIdx_SE10_0:
12203         return 0;
12204     case ARMMMUIdx_E10_1:
12205     case ARMMMUIdx_E10_1_PAN:
12206     case ARMMMUIdx_SE10_1:
12207     case ARMMMUIdx_SE10_1_PAN:
12208         return 1;
12209     case ARMMMUIdx_E2:
12210     case ARMMMUIdx_E20_2:
12211     case ARMMMUIdx_E20_2_PAN:
12212         return 2;
12213     case ARMMMUIdx_SE3:
12214         return 3;
12215     default:
12216         g_assert_not_reached();
12217     }
12218 }
12219 
12220 #ifndef CONFIG_TCG
12221 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
12222 {
12223     g_assert_not_reached();
12224 }
12225 #endif
12226 
12227 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
12228 {
12229     if (arm_feature(env, ARM_FEATURE_M)) {
12230         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
12231     }
12232 
12233     /* See ARM pseudo-function ELIsInHost.  */
12234     switch (el) {
12235     case 0:
12236         if (arm_is_secure_below_el3(env)) {
12237             return ARMMMUIdx_SE10_0;
12238         }
12239         if ((env->cp15.hcr_el2 & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)
12240             && arm_el_is_aa64(env, 2)) {
12241             return ARMMMUIdx_E20_0;
12242         }
12243         return ARMMMUIdx_E10_0;
12244     case 1:
12245         if (arm_is_secure_below_el3(env)) {
12246             if (env->pstate & PSTATE_PAN) {
12247                 return ARMMMUIdx_SE10_1_PAN;
12248             }
12249             return ARMMMUIdx_SE10_1;
12250         }
12251         if (env->pstate & PSTATE_PAN) {
12252             return ARMMMUIdx_E10_1_PAN;
12253         }
12254         return ARMMMUIdx_E10_1;
12255     case 2:
12256         /* TODO: ARMv8.4-SecEL2 */
12257         /* Note that TGE does not apply at EL2.  */
12258         if ((env->cp15.hcr_el2 & HCR_E2H) && arm_el_is_aa64(env, 2)) {
12259             if (env->pstate & PSTATE_PAN) {
12260                 return ARMMMUIdx_E20_2_PAN;
12261             }
12262             return ARMMMUIdx_E20_2;
12263         }
12264         return ARMMMUIdx_E2;
12265     case 3:
12266         return ARMMMUIdx_SE3;
12267     default:
12268         g_assert_not_reached();
12269     }
12270 }
12271 
12272 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
12273 {
12274     return arm_mmu_idx_el(env, arm_current_el(env));
12275 }
12276 
12277 #ifndef CONFIG_USER_ONLY
12278 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
12279 {
12280     return stage_1_mmu_idx(arm_mmu_idx(env));
12281 }
12282 #endif
12283 
12284 static uint32_t rebuild_hflags_common(CPUARMState *env, int fp_el,
12285                                       ARMMMUIdx mmu_idx, uint32_t flags)
12286 {
12287     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
12288     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX,
12289                        arm_to_core_mmu_idx(mmu_idx));
12290 
12291     if (arm_singlestep_active(env)) {
12292         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
12293     }
12294     return flags;
12295 }
12296 
12297 static uint32_t rebuild_hflags_common_32(CPUARMState *env, int fp_el,
12298                                          ARMMMUIdx mmu_idx, uint32_t flags)
12299 {
12300     bool sctlr_b = arm_sctlr_b(env);
12301 
12302     if (sctlr_b) {
12303         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, 1);
12304     }
12305     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
12306         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
12307     }
12308     flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
12309 
12310     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
12311 }
12312 
12313 static uint32_t rebuild_hflags_m32(CPUARMState *env, int fp_el,
12314                                    ARMMMUIdx mmu_idx)
12315 {
12316     uint32_t flags = 0;
12317 
12318     if (arm_v7m_is_handler_mode(env)) {
12319         flags = FIELD_DP32(flags, TBFLAG_M32, HANDLER, 1);
12320     }
12321 
12322     /*
12323      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
12324      * is suppressing them because the requested execution priority
12325      * is less than 0.
12326      */
12327     if (arm_feature(env, ARM_FEATURE_V8) &&
12328         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
12329           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
12330         flags = FIELD_DP32(flags, TBFLAG_M32, STACKCHECK, 1);
12331     }
12332 
12333     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
12334 }
12335 
12336 static uint32_t rebuild_hflags_aprofile(CPUARMState *env)
12337 {
12338     int flags = 0;
12339 
12340     flags = FIELD_DP32(flags, TBFLAG_ANY, DEBUG_TARGET_EL,
12341                        arm_debug_target_el(env));
12342     return flags;
12343 }
12344 
12345 static uint32_t rebuild_hflags_a32(CPUARMState *env, int fp_el,
12346                                    ARMMMUIdx mmu_idx)
12347 {
12348     uint32_t flags = rebuild_hflags_aprofile(env);
12349 
12350     if (arm_el_is_aa64(env, 1)) {
12351         flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
12352     }
12353 
12354     if (arm_current_el(env) < 2 && env->cp15.hstr_el2 &&
12355         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
12356         flags = FIELD_DP32(flags, TBFLAG_A32, HSTR_ACTIVE, 1);
12357     }
12358 
12359     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
12360 }
12361 
12362 static uint32_t rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
12363                                    ARMMMUIdx mmu_idx)
12364 {
12365     uint32_t flags = rebuild_hflags_aprofile(env);
12366     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
12367     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
12368     uint64_t sctlr;
12369     int tbii, tbid;
12370 
12371     flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
12372 
12373     /* Get control bits for tagged addresses.  */
12374     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
12375     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
12376 
12377     flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
12378     flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
12379 
12380     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
12381         int sve_el = sve_exception_el(env, el);
12382         uint32_t zcr_len;
12383 
12384         /*
12385          * If SVE is disabled, but FP is enabled,
12386          * then the effective len is 0.
12387          */
12388         if (sve_el != 0 && fp_el == 0) {
12389             zcr_len = 0;
12390         } else {
12391             zcr_len = sve_zcr_len_for_el(env, el);
12392         }
12393         flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
12394         flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
12395     }
12396 
12397     sctlr = regime_sctlr(env, stage1);
12398 
12399     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
12400         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
12401     }
12402 
12403     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
12404         /*
12405          * In order to save space in flags, we record only whether
12406          * pauth is "inactive", meaning all insns are implemented as
12407          * a nop, or "active" when some action must be performed.
12408          * The decision of which action to take is left to a helper.
12409          */
12410         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
12411             flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
12412         }
12413     }
12414 
12415     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
12416         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
12417         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
12418             flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
12419         }
12420     }
12421 
12422     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
12423     if (!(env->pstate & PSTATE_UAO)) {
12424         switch (mmu_idx) {
12425         case ARMMMUIdx_E10_1:
12426         case ARMMMUIdx_E10_1_PAN:
12427         case ARMMMUIdx_SE10_1:
12428         case ARMMMUIdx_SE10_1_PAN:
12429             /* TODO: ARMv8.3-NV */
12430             flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
12431             break;
12432         case ARMMMUIdx_E20_2:
12433         case ARMMMUIdx_E20_2_PAN:
12434             /* TODO: ARMv8.4-SecEL2 */
12435             /*
12436              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
12437              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
12438              */
12439             if (env->cp15.hcr_el2 & HCR_TGE) {
12440                 flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
12441             }
12442             break;
12443         default:
12444             break;
12445         }
12446     }
12447 
12448     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
12449 }
12450 
12451 static uint32_t rebuild_hflags_internal(CPUARMState *env)
12452 {
12453     int el = arm_current_el(env);
12454     int fp_el = fp_exception_el(env, el);
12455     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12456 
12457     if (is_a64(env)) {
12458         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
12459     } else if (arm_feature(env, ARM_FEATURE_M)) {
12460         return rebuild_hflags_m32(env, fp_el, mmu_idx);
12461     } else {
12462         return rebuild_hflags_a32(env, fp_el, mmu_idx);
12463     }
12464 }
12465 
12466 void arm_rebuild_hflags(CPUARMState *env)
12467 {
12468     env->hflags = rebuild_hflags_internal(env);
12469 }
12470 
12471 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
12472 {
12473     int fp_el = fp_exception_el(env, el);
12474     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12475 
12476     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
12477 }
12478 
12479 /*
12480  * If we have triggered a EL state change we can't rely on the
12481  * translator having passed it too us, we need to recompute.
12482  */
12483 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
12484 {
12485     int el = arm_current_el(env);
12486     int fp_el = fp_exception_el(env, el);
12487     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12488     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
12489 }
12490 
12491 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
12492 {
12493     int fp_el = fp_exception_el(env, el);
12494     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12495 
12496     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
12497 }
12498 
12499 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
12500 {
12501     int fp_el = fp_exception_el(env, el);
12502     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12503 
12504     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
12505 }
12506 
12507 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
12508 {
12509 #ifdef CONFIG_DEBUG_TCG
12510     uint32_t env_flags_current = env->hflags;
12511     uint32_t env_flags_rebuilt = rebuild_hflags_internal(env);
12512 
12513     if (unlikely(env_flags_current != env_flags_rebuilt)) {
12514         fprintf(stderr, "TCG hflags mismatch (current:0x%08x rebuilt:0x%08x)\n",
12515                 env_flags_current, env_flags_rebuilt);
12516         abort();
12517     }
12518 #endif
12519 }
12520 
12521 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
12522                           target_ulong *cs_base, uint32_t *pflags)
12523 {
12524     uint32_t flags = env->hflags;
12525     uint32_t pstate_for_ss;
12526 
12527     *cs_base = 0;
12528     assert_hflags_rebuild_correctly(env);
12529 
12530     if (FIELD_EX32(flags, TBFLAG_ANY, AARCH64_STATE)) {
12531         *pc = env->pc;
12532         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
12533             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
12534         }
12535         pstate_for_ss = env->pstate;
12536     } else {
12537         *pc = env->regs[15];
12538 
12539         if (arm_feature(env, ARM_FEATURE_M)) {
12540             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
12541                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
12542                 != env->v7m.secure) {
12543                 flags = FIELD_DP32(flags, TBFLAG_M32, FPCCR_S_WRONG, 1);
12544             }
12545 
12546             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
12547                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
12548                  (env->v7m.secure &&
12549                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
12550                 /*
12551                  * ASPEN is set, but FPCA/SFPA indicate that there is no
12552                  * active FP context; we must create a new FP context before
12553                  * executing any FP insn.
12554                  */
12555                 flags = FIELD_DP32(flags, TBFLAG_M32, NEW_FP_CTXT_NEEDED, 1);
12556             }
12557 
12558             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
12559             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
12560                 flags = FIELD_DP32(flags, TBFLAG_M32, LSPACT, 1);
12561             }
12562         } else {
12563             /*
12564              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
12565              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
12566              */
12567             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
12568                 flags = FIELD_DP32(flags, TBFLAG_A32,
12569                                    XSCALE_CPAR, env->cp15.c15_cpar);
12570             } else {
12571                 flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN,
12572                                    env->vfp.vec_len);
12573                 flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE,
12574                                    env->vfp.vec_stride);
12575             }
12576             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
12577                 flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
12578             }
12579         }
12580 
12581         flags = FIELD_DP32(flags, TBFLAG_AM32, THUMB, env->thumb);
12582         flags = FIELD_DP32(flags, TBFLAG_AM32, CONDEXEC, env->condexec_bits);
12583         pstate_for_ss = env->uncached_cpsr;
12584     }
12585 
12586     /*
12587      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
12588      * states defined in the ARM ARM for software singlestep:
12589      *  SS_ACTIVE   PSTATE.SS   State
12590      *     0            x       Inactive (the TB flag for SS is always 0)
12591      *     1            0       Active-pending
12592      *     1            1       Active-not-pending
12593      * SS_ACTIVE is set in hflags; PSTATE_SS is computed every TB.
12594      */
12595     if (FIELD_EX32(flags, TBFLAG_ANY, SS_ACTIVE) &&
12596         (pstate_for_ss & PSTATE_SS)) {
12597         flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
12598     }
12599 
12600     *pflags = flags;
12601 }
12602 
12603 #ifdef TARGET_AARCH64
12604 /*
12605  * The manual says that when SVE is enabled and VQ is widened the
12606  * implementation is allowed to zero the previously inaccessible
12607  * portion of the registers.  The corollary to that is that when
12608  * SVE is enabled and VQ is narrowed we are also allowed to zero
12609  * the now inaccessible portion of the registers.
12610  *
12611  * The intent of this is that no predicate bit beyond VQ is ever set.
12612  * Which means that some operations on predicate registers themselves
12613  * may operate on full uint64_t or even unrolled across the maximum
12614  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
12615  * may well be cheaper than conditionals to restrict the operation
12616  * to the relevant portion of a uint16_t[16].
12617  */
12618 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
12619 {
12620     int i, j;
12621     uint64_t pmask;
12622 
12623     assert(vq >= 1 && vq <= ARM_MAX_VQ);
12624     assert(vq <= env_archcpu(env)->sve_max_vq);
12625 
12626     /* Zap the high bits of the zregs.  */
12627     for (i = 0; i < 32; i++) {
12628         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
12629     }
12630 
12631     /* Zap the high bits of the pregs and ffr.  */
12632     pmask = 0;
12633     if (vq & 3) {
12634         pmask = ~(-1ULL << (16 * (vq & 3)));
12635     }
12636     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
12637         for (i = 0; i < 17; ++i) {
12638             env->vfp.pregs[i].p[j] &= pmask;
12639         }
12640         pmask = 0;
12641     }
12642 }
12643 
12644 /*
12645  * Notice a change in SVE vector size when changing EL.
12646  */
12647 void aarch64_sve_change_el(CPUARMState *env, int old_el,
12648                            int new_el, bool el0_a64)
12649 {
12650     ARMCPU *cpu = env_archcpu(env);
12651     int old_len, new_len;
12652     bool old_a64, new_a64;
12653 
12654     /* Nothing to do if no SVE.  */
12655     if (!cpu_isar_feature(aa64_sve, cpu)) {
12656         return;
12657     }
12658 
12659     /* Nothing to do if FP is disabled in either EL.  */
12660     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
12661         return;
12662     }
12663 
12664     /*
12665      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
12666      * at ELx, or not available because the EL is in AArch32 state, then
12667      * for all purposes other than a direct read, the ZCR_ELx.LEN field
12668      * has an effective value of 0".
12669      *
12670      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
12671      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
12672      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
12673      * we already have the correct register contents when encountering the
12674      * vq0->vq0 transition between EL0->EL1.
12675      */
12676     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
12677     old_len = (old_a64 && !sve_exception_el(env, old_el)
12678                ? sve_zcr_len_for_el(env, old_el) : 0);
12679     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
12680     new_len = (new_a64 && !sve_exception_el(env, new_el)
12681                ? sve_zcr_len_for_el(env, new_el) : 0);
12682 
12683     /* When changing vector length, clear inaccessible state.  */
12684     if (new_len < old_len) {
12685         aarch64_sve_narrow_vq(env, new_len + 1);
12686     }
12687 }
12688 #endif
12689