xref: /qemu/target/arm/helper.c (revision e3a6e0da)
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                                bool s1_is_el0,
45                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
46                                target_ulong *page_size_ptr,
47                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
48     __attribute__((nonnull));
49 #endif
50 
51 static void switch_mode(CPUARMState *env, int mode);
52 
53 static int vfp_gdb_get_reg(CPUARMState *env, GByteArray *buf, int reg)
54 {
55     ARMCPU *cpu = env_archcpu(env);
56     int nregs = cpu_isar_feature(aa32_simd_r32, cpu) ? 32 : 16;
57 
58     /* VFP data registers are always little-endian.  */
59     if (reg < nregs) {
60         return gdb_get_reg64(buf, *aa32_vfp_dreg(env, reg));
61     }
62     if (arm_feature(env, ARM_FEATURE_NEON)) {
63         /* Aliases for Q regs.  */
64         nregs += 16;
65         if (reg < nregs) {
66             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
67             return gdb_get_reg128(buf, q[0], q[1]);
68         }
69     }
70     switch (reg - nregs) {
71     case 0: return gdb_get_reg32(buf, env->vfp.xregs[ARM_VFP_FPSID]); break;
72     case 1: return gdb_get_reg32(buf, vfp_get_fpscr(env)); break;
73     case 2: return gdb_get_reg32(buf, env->vfp.xregs[ARM_VFP_FPEXC]); break;
74     }
75     return 0;
76 }
77 
78 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
79 {
80     ARMCPU *cpu = env_archcpu(env);
81     int nregs = cpu_isar_feature(aa32_simd_r32, cpu) ? 32 : 16;
82 
83     if (reg < nregs) {
84         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
85         return 8;
86     }
87     if (arm_feature(env, ARM_FEATURE_NEON)) {
88         nregs += 16;
89         if (reg < nregs) {
90             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
91             q[0] = ldq_le_p(buf);
92             q[1] = ldq_le_p(buf + 8);
93             return 16;
94         }
95     }
96     switch (reg - nregs) {
97     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
98     case 1: vfp_set_fpscr(env, ldl_p(buf)); return 4;
99     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
100     }
101     return 0;
102 }
103 
104 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, GByteArray *buf, int reg)
105 {
106     switch (reg) {
107     case 0 ... 31:
108     {
109         /* 128 bit FP register - quads are in LE order */
110         uint64_t *q = aa64_vfp_qreg(env, reg);
111         return gdb_get_reg128(buf, q[1], q[0]);
112     }
113     case 32:
114         /* FPSR */
115         return gdb_get_reg32(buf, vfp_get_fpsr(env));
116     case 33:
117         /* FPCR */
118         return gdb_get_reg32(buf,vfp_get_fpcr(env));
119     default:
120         return 0;
121     }
122 }
123 
124 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
125 {
126     switch (reg) {
127     case 0 ... 31:
128         /* 128 bit FP register */
129         {
130             uint64_t *q = aa64_vfp_qreg(env, reg);
131             q[0] = ldq_le_p(buf);
132             q[1] = ldq_le_p(buf + 8);
133             return 16;
134         }
135     case 32:
136         /* FPSR */
137         vfp_set_fpsr(env, ldl_p(buf));
138         return 4;
139     case 33:
140         /* FPCR */
141         vfp_set_fpcr(env, ldl_p(buf));
142         return 4;
143     default:
144         return 0;
145     }
146 }
147 
148 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
149 {
150     assert(ri->fieldoffset);
151     if (cpreg_field_is_64bit(ri)) {
152         return CPREG_FIELD64(env, ri);
153     } else {
154         return CPREG_FIELD32(env, ri);
155     }
156 }
157 
158 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
159                       uint64_t value)
160 {
161     assert(ri->fieldoffset);
162     if (cpreg_field_is_64bit(ri)) {
163         CPREG_FIELD64(env, ri) = value;
164     } else {
165         CPREG_FIELD32(env, ri) = value;
166     }
167 }
168 
169 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
170 {
171     return (char *)env + ri->fieldoffset;
172 }
173 
174 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
175 {
176     /* Raw read of a coprocessor register (as needed for migration, etc). */
177     if (ri->type & ARM_CP_CONST) {
178         return ri->resetvalue;
179     } else if (ri->raw_readfn) {
180         return ri->raw_readfn(env, ri);
181     } else if (ri->readfn) {
182         return ri->readfn(env, ri);
183     } else {
184         return raw_read(env, ri);
185     }
186 }
187 
188 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
189                              uint64_t v)
190 {
191     /* Raw write of a coprocessor register (as needed for migration, etc).
192      * Note that constant registers are treated as write-ignored; the
193      * caller should check for success by whether a readback gives the
194      * value written.
195      */
196     if (ri->type & ARM_CP_CONST) {
197         return;
198     } else if (ri->raw_writefn) {
199         ri->raw_writefn(env, ri, v);
200     } else if (ri->writefn) {
201         ri->writefn(env, ri, v);
202     } else {
203         raw_write(env, ri, v);
204     }
205 }
206 
207 /**
208  * arm_get/set_gdb_*: get/set a gdb register
209  * @env: the CPU state
210  * @buf: a buffer to copy to/from
211  * @reg: register number (offset from start of group)
212  *
213  * We return the number of bytes copied
214  */
215 
216 static int arm_gdb_get_sysreg(CPUARMState *env, GByteArray *buf, int reg)
217 {
218     ARMCPU *cpu = env_archcpu(env);
219     const ARMCPRegInfo *ri;
220     uint32_t key;
221 
222     key = cpu->dyn_sysreg_xml.data.cpregs.keys[reg];
223     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
224     if (ri) {
225         if (cpreg_field_is_64bit(ri)) {
226             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
227         } else {
228             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
229         }
230     }
231     return 0;
232 }
233 
234 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
235 {
236     return 0;
237 }
238 
239 #ifdef TARGET_AARCH64
240 static int arm_gdb_get_svereg(CPUARMState *env, GByteArray *buf, int reg)
241 {
242     ARMCPU *cpu = env_archcpu(env);
243 
244     switch (reg) {
245     /* The first 32 registers are the zregs */
246     case 0 ... 31:
247     {
248         int vq, len = 0;
249         for (vq = 0; vq < cpu->sve_max_vq; vq++) {
250             len += gdb_get_reg128(buf,
251                                   env->vfp.zregs[reg].d[vq * 2 + 1],
252                                   env->vfp.zregs[reg].d[vq * 2]);
253         }
254         return len;
255     }
256     case 32:
257         return gdb_get_reg32(buf, vfp_get_fpsr(env));
258     case 33:
259         return gdb_get_reg32(buf, vfp_get_fpcr(env));
260     /* then 16 predicates and the ffr */
261     case 34 ... 50:
262     {
263         int preg = reg - 34;
264         int vq, len = 0;
265         for (vq = 0; vq < cpu->sve_max_vq; vq = vq + 4) {
266             len += gdb_get_reg64(buf, env->vfp.pregs[preg].p[vq / 4]);
267         }
268         return len;
269     }
270     case 51:
271     {
272         /*
273          * We report in Vector Granules (VG) which is 64bit in a Z reg
274          * while the ZCR works in Vector Quads (VQ) which is 128bit chunks.
275          */
276         int vq = sve_zcr_len_for_el(env, arm_current_el(env)) + 1;
277         return gdb_get_reg32(buf, vq * 2);
278     }
279     default:
280         /* gdbstub asked for something out our range */
281         qemu_log_mask(LOG_UNIMP, "%s: out of range register %d", __func__, reg);
282         break;
283     }
284 
285     return 0;
286 }
287 
288 static int arm_gdb_set_svereg(CPUARMState *env, uint8_t *buf, int reg)
289 {
290     ARMCPU *cpu = env_archcpu(env);
291 
292     /* The first 32 registers are the zregs */
293     switch (reg) {
294     /* The first 32 registers are the zregs */
295     case 0 ... 31:
296     {
297         int vq, len = 0;
298         uint64_t *p = (uint64_t *) buf;
299         for (vq = 0; vq < cpu->sve_max_vq; vq++) {
300             env->vfp.zregs[reg].d[vq * 2 + 1] = *p++;
301             env->vfp.zregs[reg].d[vq * 2] = *p++;
302             len += 16;
303         }
304         return len;
305     }
306     case 32:
307         vfp_set_fpsr(env, *(uint32_t *)buf);
308         return 4;
309     case 33:
310         vfp_set_fpcr(env, *(uint32_t *)buf);
311         return 4;
312     case 34 ... 50:
313     {
314         int preg = reg - 34;
315         int vq, len = 0;
316         uint64_t *p = (uint64_t *) buf;
317         for (vq = 0; vq < cpu->sve_max_vq; vq = vq + 4) {
318             env->vfp.pregs[preg].p[vq / 4] = *p++;
319             len += 8;
320         }
321         return len;
322     }
323     case 51:
324         /* cannot set vg via gdbstub */
325         return 0;
326     default:
327         /* gdbstub asked for something out our range */
328         break;
329     }
330 
331     return 0;
332 }
333 #endif /* TARGET_AARCH64 */
334 
335 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
336 {
337    /* Return true if the regdef would cause an assertion if you called
338     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
339     * program bug for it not to have the NO_RAW flag).
340     * NB that returning false here doesn't necessarily mean that calling
341     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
342     * read/write access functions which are safe for raw use" from "has
343     * read/write access functions which have side effects but has forgotten
344     * to provide raw access functions".
345     * The tests here line up with the conditions in read/write_raw_cp_reg()
346     * and assertions in raw_read()/raw_write().
347     */
348     if ((ri->type & ARM_CP_CONST) ||
349         ri->fieldoffset ||
350         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
351         return false;
352     }
353     return true;
354 }
355 
356 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
357 {
358     /* Write the coprocessor state from cpu->env to the (index,value) list. */
359     int i;
360     bool ok = true;
361 
362     for (i = 0; i < cpu->cpreg_array_len; i++) {
363         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
364         const ARMCPRegInfo *ri;
365         uint64_t newval;
366 
367         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
368         if (!ri) {
369             ok = false;
370             continue;
371         }
372         if (ri->type & ARM_CP_NO_RAW) {
373             continue;
374         }
375 
376         newval = read_raw_cp_reg(&cpu->env, ri);
377         if (kvm_sync) {
378             /*
379              * Only sync if the previous list->cpustate sync succeeded.
380              * Rather than tracking the success/failure state for every
381              * item in the list, we just recheck "does the raw write we must
382              * have made in write_list_to_cpustate() read back OK" here.
383              */
384             uint64_t oldval = cpu->cpreg_values[i];
385 
386             if (oldval == newval) {
387                 continue;
388             }
389 
390             write_raw_cp_reg(&cpu->env, ri, oldval);
391             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
392                 continue;
393             }
394 
395             write_raw_cp_reg(&cpu->env, ri, newval);
396         }
397         cpu->cpreg_values[i] = newval;
398     }
399     return ok;
400 }
401 
402 bool write_list_to_cpustate(ARMCPU *cpu)
403 {
404     int i;
405     bool ok = true;
406 
407     for (i = 0; i < cpu->cpreg_array_len; i++) {
408         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
409         uint64_t v = cpu->cpreg_values[i];
410         const ARMCPRegInfo *ri;
411 
412         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
413         if (!ri) {
414             ok = false;
415             continue;
416         }
417         if (ri->type & ARM_CP_NO_RAW) {
418             continue;
419         }
420         /* Write value and confirm it reads back as written
421          * (to catch read-only registers and partially read-only
422          * registers where the incoming migration value doesn't match)
423          */
424         write_raw_cp_reg(&cpu->env, ri, v);
425         if (read_raw_cp_reg(&cpu->env, ri) != v) {
426             ok = false;
427         }
428     }
429     return ok;
430 }
431 
432 static void add_cpreg_to_list(gpointer key, gpointer opaque)
433 {
434     ARMCPU *cpu = opaque;
435     uint64_t regidx;
436     const ARMCPRegInfo *ri;
437 
438     regidx = *(uint32_t *)key;
439     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
440 
441     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
442         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
443         /* The value array need not be initialized at this point */
444         cpu->cpreg_array_len++;
445     }
446 }
447 
448 static void count_cpreg(gpointer key, gpointer opaque)
449 {
450     ARMCPU *cpu = opaque;
451     uint64_t regidx;
452     const ARMCPRegInfo *ri;
453 
454     regidx = *(uint32_t *)key;
455     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
456 
457     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
458         cpu->cpreg_array_len++;
459     }
460 }
461 
462 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
463 {
464     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
465     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
466 
467     if (aidx > bidx) {
468         return 1;
469     }
470     if (aidx < bidx) {
471         return -1;
472     }
473     return 0;
474 }
475 
476 void init_cpreg_list(ARMCPU *cpu)
477 {
478     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
479      * Note that we require cpreg_tuples[] to be sorted by key ID.
480      */
481     GList *keys;
482     int arraylen;
483 
484     keys = g_hash_table_get_keys(cpu->cp_regs);
485     keys = g_list_sort(keys, cpreg_key_compare);
486 
487     cpu->cpreg_array_len = 0;
488 
489     g_list_foreach(keys, count_cpreg, cpu);
490 
491     arraylen = cpu->cpreg_array_len;
492     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
493     cpu->cpreg_values = g_new(uint64_t, arraylen);
494     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
495     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
496     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
497     cpu->cpreg_array_len = 0;
498 
499     g_list_foreach(keys, add_cpreg_to_list, cpu);
500 
501     assert(cpu->cpreg_array_len == arraylen);
502 
503     g_list_free(keys);
504 }
505 
506 /*
507  * Some registers are not accessible from AArch32 EL3 if SCR.NS == 0.
508  */
509 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
510                                         const ARMCPRegInfo *ri,
511                                         bool isread)
512 {
513     if (!is_a64(env) && arm_current_el(env) == 3 &&
514         arm_is_secure_below_el3(env)) {
515         return CP_ACCESS_TRAP_UNCATEGORIZED;
516     }
517     return CP_ACCESS_OK;
518 }
519 
520 /* Some secure-only AArch32 registers trap to EL3 if used from
521  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
522  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
523  * We assume that the .access field is set to PL1_RW.
524  */
525 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
526                                             const ARMCPRegInfo *ri,
527                                             bool isread)
528 {
529     if (arm_current_el(env) == 3) {
530         return CP_ACCESS_OK;
531     }
532     if (arm_is_secure_below_el3(env)) {
533         return CP_ACCESS_TRAP_EL3;
534     }
535     /* This will be EL1 NS and EL2 NS, which just UNDEF */
536     return CP_ACCESS_TRAP_UNCATEGORIZED;
537 }
538 
539 /* Check for traps to "powerdown debug" registers, which are controlled
540  * by MDCR.TDOSA
541  */
542 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
543                                    bool isread)
544 {
545     int el = arm_current_el(env);
546     bool mdcr_el2_tdosa = (env->cp15.mdcr_el2 & MDCR_TDOSA) ||
547         (env->cp15.mdcr_el2 & MDCR_TDE) ||
548         (arm_hcr_el2_eff(env) & HCR_TGE);
549 
550     if (el < 2 && mdcr_el2_tdosa && !arm_is_secure_below_el3(env)) {
551         return CP_ACCESS_TRAP_EL2;
552     }
553     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
554         return CP_ACCESS_TRAP_EL3;
555     }
556     return CP_ACCESS_OK;
557 }
558 
559 /* Check for traps to "debug ROM" registers, which are controlled
560  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
561  */
562 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
563                                   bool isread)
564 {
565     int el = arm_current_el(env);
566     bool mdcr_el2_tdra = (env->cp15.mdcr_el2 & MDCR_TDRA) ||
567         (env->cp15.mdcr_el2 & MDCR_TDE) ||
568         (arm_hcr_el2_eff(env) & HCR_TGE);
569 
570     if (el < 2 && mdcr_el2_tdra && !arm_is_secure_below_el3(env)) {
571         return CP_ACCESS_TRAP_EL2;
572     }
573     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
574         return CP_ACCESS_TRAP_EL3;
575     }
576     return CP_ACCESS_OK;
577 }
578 
579 /* Check for traps to general debug registers, which are controlled
580  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
581  */
582 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
583                                   bool isread)
584 {
585     int el = arm_current_el(env);
586     bool mdcr_el2_tda = (env->cp15.mdcr_el2 & MDCR_TDA) ||
587         (env->cp15.mdcr_el2 & MDCR_TDE) ||
588         (arm_hcr_el2_eff(env) & HCR_TGE);
589 
590     if (el < 2 && mdcr_el2_tda && !arm_is_secure_below_el3(env)) {
591         return CP_ACCESS_TRAP_EL2;
592     }
593     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
594         return CP_ACCESS_TRAP_EL3;
595     }
596     return CP_ACCESS_OK;
597 }
598 
599 /* Check for traps to performance monitor registers, which are controlled
600  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
601  */
602 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
603                                  bool isread)
604 {
605     int el = arm_current_el(env);
606 
607     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
608         && !arm_is_secure_below_el3(env)) {
609         return CP_ACCESS_TRAP_EL2;
610     }
611     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
612         return CP_ACCESS_TRAP_EL3;
613     }
614     return CP_ACCESS_OK;
615 }
616 
617 /* Check for traps from EL1 due to HCR_EL2.TVM and HCR_EL2.TRVM.  */
618 static CPAccessResult access_tvm_trvm(CPUARMState *env, const ARMCPRegInfo *ri,
619                                       bool isread)
620 {
621     if (arm_current_el(env) == 1) {
622         uint64_t trap = isread ? HCR_TRVM : HCR_TVM;
623         if (arm_hcr_el2_eff(env) & trap) {
624             return CP_ACCESS_TRAP_EL2;
625         }
626     }
627     return CP_ACCESS_OK;
628 }
629 
630 /* Check for traps from EL1 due to HCR_EL2.TSW.  */
631 static CPAccessResult access_tsw(CPUARMState *env, const ARMCPRegInfo *ri,
632                                  bool isread)
633 {
634     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TSW)) {
635         return CP_ACCESS_TRAP_EL2;
636     }
637     return CP_ACCESS_OK;
638 }
639 
640 /* Check for traps from EL1 due to HCR_EL2.TACR.  */
641 static CPAccessResult access_tacr(CPUARMState *env, const ARMCPRegInfo *ri,
642                                   bool isread)
643 {
644     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TACR)) {
645         return CP_ACCESS_TRAP_EL2;
646     }
647     return CP_ACCESS_OK;
648 }
649 
650 /* Check for traps from EL1 due to HCR_EL2.TTLB. */
651 static CPAccessResult access_ttlb(CPUARMState *env, const ARMCPRegInfo *ri,
652                                   bool isread)
653 {
654     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TTLB)) {
655         return CP_ACCESS_TRAP_EL2;
656     }
657     return CP_ACCESS_OK;
658 }
659 
660 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
661 {
662     ARMCPU *cpu = env_archcpu(env);
663 
664     raw_write(env, ri, value);
665     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
666 }
667 
668 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
669 {
670     ARMCPU *cpu = env_archcpu(env);
671 
672     if (raw_read(env, ri) != value) {
673         /* Unlike real hardware the qemu TLB uses virtual addresses,
674          * not modified virtual addresses, so this causes a TLB flush.
675          */
676         tlb_flush(CPU(cpu));
677         raw_write(env, ri, value);
678     }
679 }
680 
681 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
682                              uint64_t value)
683 {
684     ARMCPU *cpu = env_archcpu(env);
685 
686     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
687         && !extended_addresses_enabled(env)) {
688         /* For VMSA (when not using the LPAE long descriptor page table
689          * format) this register includes the ASID, so do a TLB flush.
690          * For PMSA it is purely a process ID and no action is needed.
691          */
692         tlb_flush(CPU(cpu));
693     }
694     raw_write(env, ri, value);
695 }
696 
697 /* IS variants of TLB operations must affect all cores */
698 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
699                              uint64_t value)
700 {
701     CPUState *cs = env_cpu(env);
702 
703     tlb_flush_all_cpus_synced(cs);
704 }
705 
706 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
707                              uint64_t value)
708 {
709     CPUState *cs = env_cpu(env);
710 
711     tlb_flush_all_cpus_synced(cs);
712 }
713 
714 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
715                              uint64_t value)
716 {
717     CPUState *cs = env_cpu(env);
718 
719     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
720 }
721 
722 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
723                              uint64_t value)
724 {
725     CPUState *cs = env_cpu(env);
726 
727     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
728 }
729 
730 /*
731  * Non-IS variants of TLB operations are upgraded to
732  * IS versions if we are at NS EL1 and HCR_EL2.FB is set to
733  * force broadcast of these operations.
734  */
735 static bool tlb_force_broadcast(CPUARMState *env)
736 {
737     return (env->cp15.hcr_el2 & HCR_FB) &&
738         arm_current_el(env) == 1 && arm_is_secure_below_el3(env);
739 }
740 
741 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
742                           uint64_t value)
743 {
744     /* Invalidate all (TLBIALL) */
745     CPUState *cs = env_cpu(env);
746 
747     if (tlb_force_broadcast(env)) {
748         tlb_flush_all_cpus_synced(cs);
749     } else {
750         tlb_flush(cs);
751     }
752 }
753 
754 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
755                           uint64_t value)
756 {
757     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
758     CPUState *cs = env_cpu(env);
759 
760     value &= TARGET_PAGE_MASK;
761     if (tlb_force_broadcast(env)) {
762         tlb_flush_page_all_cpus_synced(cs, value);
763     } else {
764         tlb_flush_page(cs, value);
765     }
766 }
767 
768 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
769                            uint64_t value)
770 {
771     /* Invalidate by ASID (TLBIASID) */
772     CPUState *cs = env_cpu(env);
773 
774     if (tlb_force_broadcast(env)) {
775         tlb_flush_all_cpus_synced(cs);
776     } else {
777         tlb_flush(cs);
778     }
779 }
780 
781 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
782                            uint64_t value)
783 {
784     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
785     CPUState *cs = env_cpu(env);
786 
787     value &= TARGET_PAGE_MASK;
788     if (tlb_force_broadcast(env)) {
789         tlb_flush_page_all_cpus_synced(cs, value);
790     } else {
791         tlb_flush_page(cs, value);
792     }
793 }
794 
795 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
796                                uint64_t value)
797 {
798     CPUState *cs = env_cpu(env);
799 
800     tlb_flush_by_mmuidx(cs,
801                         ARMMMUIdxBit_E10_1 |
802                         ARMMMUIdxBit_E10_1_PAN |
803                         ARMMMUIdxBit_E10_0);
804 }
805 
806 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
807                                   uint64_t value)
808 {
809     CPUState *cs = env_cpu(env);
810 
811     tlb_flush_by_mmuidx_all_cpus_synced(cs,
812                                         ARMMMUIdxBit_E10_1 |
813                                         ARMMMUIdxBit_E10_1_PAN |
814                                         ARMMMUIdxBit_E10_0);
815 }
816 
817 
818 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
819                               uint64_t value)
820 {
821     CPUState *cs = env_cpu(env);
822 
823     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_E2);
824 }
825 
826 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
827                                  uint64_t value)
828 {
829     CPUState *cs = env_cpu(env);
830 
831     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_E2);
832 }
833 
834 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
835                               uint64_t value)
836 {
837     CPUState *cs = env_cpu(env);
838     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
839 
840     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_E2);
841 }
842 
843 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
844                                  uint64_t value)
845 {
846     CPUState *cs = env_cpu(env);
847     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
848 
849     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
850                                              ARMMMUIdxBit_E2);
851 }
852 
853 static const ARMCPRegInfo cp_reginfo[] = {
854     /* Define the secure and non-secure FCSE identifier CP registers
855      * separately because there is no secure bank in V8 (no _EL3).  This allows
856      * the secure register to be properly reset and migrated. There is also no
857      * v8 EL1 version of the register so the non-secure instance stands alone.
858      */
859     { .name = "FCSEIDR",
860       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
861       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
862       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
863       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
864     { .name = "FCSEIDR_S",
865       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
866       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
867       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
868       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
869     /* Define the secure and non-secure context identifier CP registers
870      * separately because there is no secure bank in V8 (no _EL3).  This allows
871      * the secure register to be properly reset and migrated.  In the
872      * non-secure case, the 32-bit register will have reset and migration
873      * disabled during registration as it is handled by the 64-bit instance.
874      */
875     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
876       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
877       .access = PL1_RW, .accessfn = access_tvm_trvm,
878       .secure = ARM_CP_SECSTATE_NS,
879       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
880       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
881     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
882       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
883       .access = PL1_RW, .accessfn = access_tvm_trvm,
884       .secure = ARM_CP_SECSTATE_S,
885       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
886       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
887     REGINFO_SENTINEL
888 };
889 
890 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
891     /* NB: Some of these registers exist in v8 but with more precise
892      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
893      */
894     /* MMU Domain access control / MPU write buffer control */
895     { .name = "DACR",
896       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
897       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
898       .writefn = dacr_write, .raw_writefn = raw_write,
899       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
900                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
901     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
902      * For v6 and v5, these mappings are overly broad.
903      */
904     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
905       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
906     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
907       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
908     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
909       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
910     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
911       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
912     /* Cache maintenance ops; some of this space may be overridden later. */
913     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
914       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
915       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
916     REGINFO_SENTINEL
917 };
918 
919 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
920     /* Not all pre-v6 cores implemented this WFI, so this is slightly
921      * over-broad.
922      */
923     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
924       .access = PL1_W, .type = ARM_CP_WFI },
925     REGINFO_SENTINEL
926 };
927 
928 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
929     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
930      * is UNPREDICTABLE; we choose to NOP as most implementations do).
931      */
932     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
933       .access = PL1_W, .type = ARM_CP_WFI },
934     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
935      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
936      * OMAPCP will override this space.
937      */
938     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
939       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
940       .resetvalue = 0 },
941     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
942       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
943       .resetvalue = 0 },
944     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
945     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
946       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
947       .resetvalue = 0 },
948     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
949      * implementing it as RAZ means the "debug architecture version" bits
950      * will read as a reserved value, which should cause Linux to not try
951      * to use the debug hardware.
952      */
953     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
954       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
955     /* MMU TLB control. Note that the wildcarding means we cover not just
956      * the unified TLB ops but also the dside/iside/inner-shareable variants.
957      */
958     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
959       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
960       .type = ARM_CP_NO_RAW },
961     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
962       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
963       .type = ARM_CP_NO_RAW },
964     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
965       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
966       .type = ARM_CP_NO_RAW },
967     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
968       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
969       .type = ARM_CP_NO_RAW },
970     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
971       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
972     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
973       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
974     REGINFO_SENTINEL
975 };
976 
977 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
978                         uint64_t value)
979 {
980     uint32_t mask = 0;
981 
982     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
983     if (!arm_feature(env, ARM_FEATURE_V8)) {
984         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
985          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
986          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
987          */
988         if (cpu_isar_feature(aa32_vfp_simd, env_archcpu(env))) {
989             /* VFP coprocessor: cp10 & cp11 [23:20] */
990             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
991 
992             if (!arm_feature(env, ARM_FEATURE_NEON)) {
993                 /* ASEDIS [31] bit is RAO/WI */
994                 value |= (1 << 31);
995             }
996 
997             /* VFPv3 and upwards with NEON implement 32 double precision
998              * registers (D0-D31).
999              */
1000             if (!cpu_isar_feature(aa32_simd_r32, env_archcpu(env))) {
1001                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
1002                 value |= (1 << 30);
1003             }
1004         }
1005         value &= mask;
1006     }
1007 
1008     /*
1009      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
1010      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
1011      */
1012     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
1013         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
1014         value &= ~(0xf << 20);
1015         value |= env->cp15.cpacr_el1 & (0xf << 20);
1016     }
1017 
1018     env->cp15.cpacr_el1 = value;
1019 }
1020 
1021 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1022 {
1023     /*
1024      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
1025      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
1026      */
1027     uint64_t value = env->cp15.cpacr_el1;
1028 
1029     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
1030         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
1031         value &= ~(0xf << 20);
1032     }
1033     return value;
1034 }
1035 
1036 
1037 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1038 {
1039     /* Call cpacr_write() so that we reset with the correct RAO bits set
1040      * for our CPU features.
1041      */
1042     cpacr_write(env, ri, 0);
1043 }
1044 
1045 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1046                                    bool isread)
1047 {
1048     if (arm_feature(env, ARM_FEATURE_V8)) {
1049         /* Check if CPACR accesses are to be trapped to EL2 */
1050         if (arm_current_el(env) == 1 &&
1051             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
1052             return CP_ACCESS_TRAP_EL2;
1053         /* Check if CPACR accesses are to be trapped to EL3 */
1054         } else if (arm_current_el(env) < 3 &&
1055                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
1056             return CP_ACCESS_TRAP_EL3;
1057         }
1058     }
1059 
1060     return CP_ACCESS_OK;
1061 }
1062 
1063 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1064                                   bool isread)
1065 {
1066     /* Check if CPTR accesses are set to trap to EL3 */
1067     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
1068         return CP_ACCESS_TRAP_EL3;
1069     }
1070 
1071     return CP_ACCESS_OK;
1072 }
1073 
1074 static const ARMCPRegInfo v6_cp_reginfo[] = {
1075     /* prefetch by MVA in v6, NOP in v7 */
1076     { .name = "MVA_prefetch",
1077       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
1078       .access = PL1_W, .type = ARM_CP_NOP },
1079     /* We need to break the TB after ISB to execute self-modifying code
1080      * correctly and also to take any pending interrupts immediately.
1081      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
1082      */
1083     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
1084       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
1085     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
1086       .access = PL0_W, .type = ARM_CP_NOP },
1087     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
1088       .access = PL0_W, .type = ARM_CP_NOP },
1089     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
1090       .access = PL1_RW, .accessfn = access_tvm_trvm,
1091       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
1092                              offsetof(CPUARMState, cp15.ifar_ns) },
1093       .resetvalue = 0, },
1094     /* Watchpoint Fault Address Register : should actually only be present
1095      * for 1136, 1176, 11MPCore.
1096      */
1097     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
1098       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
1099     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
1100       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
1101       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
1102       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
1103     REGINFO_SENTINEL
1104 };
1105 
1106 /* Definitions for the PMU registers */
1107 #define PMCRN_MASK  0xf800
1108 #define PMCRN_SHIFT 11
1109 #define PMCRLC  0x40
1110 #define PMCRDP  0x20
1111 #define PMCRX   0x10
1112 #define PMCRD   0x8
1113 #define PMCRC   0x4
1114 #define PMCRP   0x2
1115 #define PMCRE   0x1
1116 /*
1117  * Mask of PMCR bits writeable by guest (not including WO bits like C, P,
1118  * which can be written as 1 to trigger behaviour but which stay RAZ).
1119  */
1120 #define PMCR_WRITEABLE_MASK (PMCRLC | PMCRDP | PMCRX | PMCRD | PMCRE)
1121 
1122 #define PMXEVTYPER_P          0x80000000
1123 #define PMXEVTYPER_U          0x40000000
1124 #define PMXEVTYPER_NSK        0x20000000
1125 #define PMXEVTYPER_NSU        0x10000000
1126 #define PMXEVTYPER_NSH        0x08000000
1127 #define PMXEVTYPER_M          0x04000000
1128 #define PMXEVTYPER_MT         0x02000000
1129 #define PMXEVTYPER_EVTCOUNT   0x0000ffff
1130 #define PMXEVTYPER_MASK       (PMXEVTYPER_P | PMXEVTYPER_U | PMXEVTYPER_NSK | \
1131                                PMXEVTYPER_NSU | PMXEVTYPER_NSH | \
1132                                PMXEVTYPER_M | PMXEVTYPER_MT | \
1133                                PMXEVTYPER_EVTCOUNT)
1134 
1135 #define PMCCFILTR             0xf8000000
1136 #define PMCCFILTR_M           PMXEVTYPER_M
1137 #define PMCCFILTR_EL0         (PMCCFILTR | PMCCFILTR_M)
1138 
1139 static inline uint32_t pmu_num_counters(CPUARMState *env)
1140 {
1141   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
1142 }
1143 
1144 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1145 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1146 {
1147   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1148 }
1149 
1150 typedef struct pm_event {
1151     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1152     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1153     bool (*supported)(CPUARMState *);
1154     /*
1155      * Retrieve the current count of the underlying event. The programmed
1156      * counters hold a difference from the return value from this function
1157      */
1158     uint64_t (*get_count)(CPUARMState *);
1159     /*
1160      * Return how many nanoseconds it will take (at a minimum) for count events
1161      * to occur. A negative value indicates the counter will never overflow, or
1162      * that the counter has otherwise arranged for the overflow bit to be set
1163      * and the PMU interrupt to be raised on overflow.
1164      */
1165     int64_t (*ns_per_count)(uint64_t);
1166 } pm_event;
1167 
1168 static bool event_always_supported(CPUARMState *env)
1169 {
1170     return true;
1171 }
1172 
1173 static uint64_t swinc_get_count(CPUARMState *env)
1174 {
1175     /*
1176      * SW_INCR events are written directly to the pmevcntr's by writes to
1177      * PMSWINC, so there is no underlying count maintained by the PMU itself
1178      */
1179     return 0;
1180 }
1181 
1182 static int64_t swinc_ns_per(uint64_t ignored)
1183 {
1184     return -1;
1185 }
1186 
1187 /*
1188  * Return the underlying cycle count for the PMU cycle counters. If we're in
1189  * usermode, simply return 0.
1190  */
1191 static uint64_t cycles_get_count(CPUARMState *env)
1192 {
1193 #ifndef CONFIG_USER_ONLY
1194     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1195                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1196 #else
1197     return cpu_get_host_ticks();
1198 #endif
1199 }
1200 
1201 #ifndef CONFIG_USER_ONLY
1202 static int64_t cycles_ns_per(uint64_t cycles)
1203 {
1204     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1205 }
1206 
1207 static bool instructions_supported(CPUARMState *env)
1208 {
1209     return use_icount == 1 /* Precise instruction counting */;
1210 }
1211 
1212 static uint64_t instructions_get_count(CPUARMState *env)
1213 {
1214     return (uint64_t)cpu_get_icount_raw();
1215 }
1216 
1217 static int64_t instructions_ns_per(uint64_t icount)
1218 {
1219     return cpu_icount_to_ns((int64_t)icount);
1220 }
1221 #endif
1222 
1223 static bool pmu_8_1_events_supported(CPUARMState *env)
1224 {
1225     /* For events which are supported in any v8.1 PMU */
1226     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
1227 }
1228 
1229 static bool pmu_8_4_events_supported(CPUARMState *env)
1230 {
1231     /* For events which are supported in any v8.1 PMU */
1232     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
1233 }
1234 
1235 static uint64_t zero_event_get_count(CPUARMState *env)
1236 {
1237     /* For events which on QEMU never fire, so their count is always zero */
1238     return 0;
1239 }
1240 
1241 static int64_t zero_event_ns_per(uint64_t cycles)
1242 {
1243     /* An event which never fires can never overflow */
1244     return -1;
1245 }
1246 
1247 static const pm_event pm_events[] = {
1248     { .number = 0x000, /* SW_INCR */
1249       .supported = event_always_supported,
1250       .get_count = swinc_get_count,
1251       .ns_per_count = swinc_ns_per,
1252     },
1253 #ifndef CONFIG_USER_ONLY
1254     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1255       .supported = instructions_supported,
1256       .get_count = instructions_get_count,
1257       .ns_per_count = instructions_ns_per,
1258     },
1259     { .number = 0x011, /* CPU_CYCLES, Cycle */
1260       .supported = event_always_supported,
1261       .get_count = cycles_get_count,
1262       .ns_per_count = cycles_ns_per,
1263     },
1264 #endif
1265     { .number = 0x023, /* STALL_FRONTEND */
1266       .supported = pmu_8_1_events_supported,
1267       .get_count = zero_event_get_count,
1268       .ns_per_count = zero_event_ns_per,
1269     },
1270     { .number = 0x024, /* STALL_BACKEND */
1271       .supported = pmu_8_1_events_supported,
1272       .get_count = zero_event_get_count,
1273       .ns_per_count = zero_event_ns_per,
1274     },
1275     { .number = 0x03c, /* STALL */
1276       .supported = pmu_8_4_events_supported,
1277       .get_count = zero_event_get_count,
1278       .ns_per_count = zero_event_ns_per,
1279     },
1280 };
1281 
1282 /*
1283  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1284  * events (i.e. the statistical profiling extension), this implementation
1285  * should first be updated to something sparse instead of the current
1286  * supported_event_map[] array.
1287  */
1288 #define MAX_EVENT_ID 0x3c
1289 #define UNSUPPORTED_EVENT UINT16_MAX
1290 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1291 
1292 /*
1293  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1294  * of ARM event numbers to indices in our pm_events array.
1295  *
1296  * Note: Events in the 0x40XX range are not currently supported.
1297  */
1298 void pmu_init(ARMCPU *cpu)
1299 {
1300     unsigned int i;
1301 
1302     /*
1303      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1304      * events to them
1305      */
1306     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1307         supported_event_map[i] = UNSUPPORTED_EVENT;
1308     }
1309     cpu->pmceid0 = 0;
1310     cpu->pmceid1 = 0;
1311 
1312     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1313         const pm_event *cnt = &pm_events[i];
1314         assert(cnt->number <= MAX_EVENT_ID);
1315         /* We do not currently support events in the 0x40xx range */
1316         assert(cnt->number <= 0x3f);
1317 
1318         if (cnt->supported(&cpu->env)) {
1319             supported_event_map[cnt->number] = i;
1320             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1321             if (cnt->number & 0x20) {
1322                 cpu->pmceid1 |= event_mask;
1323             } else {
1324                 cpu->pmceid0 |= event_mask;
1325             }
1326         }
1327     }
1328 }
1329 
1330 /*
1331  * Check at runtime whether a PMU event is supported for the current machine
1332  */
1333 static bool event_supported(uint16_t number)
1334 {
1335     if (number > MAX_EVENT_ID) {
1336         return false;
1337     }
1338     return supported_event_map[number] != UNSUPPORTED_EVENT;
1339 }
1340 
1341 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1342                                    bool isread)
1343 {
1344     /* Performance monitor registers user accessibility is controlled
1345      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1346      * trapping to EL2 or EL3 for other accesses.
1347      */
1348     int el = arm_current_el(env);
1349 
1350     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1351         return CP_ACCESS_TRAP;
1352     }
1353     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
1354         && !arm_is_secure_below_el3(env)) {
1355         return CP_ACCESS_TRAP_EL2;
1356     }
1357     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1358         return CP_ACCESS_TRAP_EL3;
1359     }
1360 
1361     return CP_ACCESS_OK;
1362 }
1363 
1364 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1365                                            const ARMCPRegInfo *ri,
1366                                            bool isread)
1367 {
1368     /* ER: event counter read trap control */
1369     if (arm_feature(env, ARM_FEATURE_V8)
1370         && arm_current_el(env) == 0
1371         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1372         && isread) {
1373         return CP_ACCESS_OK;
1374     }
1375 
1376     return pmreg_access(env, ri, isread);
1377 }
1378 
1379 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1380                                          const ARMCPRegInfo *ri,
1381                                          bool isread)
1382 {
1383     /* SW: software increment write trap control */
1384     if (arm_feature(env, ARM_FEATURE_V8)
1385         && arm_current_el(env) == 0
1386         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1387         && !isread) {
1388         return CP_ACCESS_OK;
1389     }
1390 
1391     return pmreg_access(env, ri, isread);
1392 }
1393 
1394 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1395                                         const ARMCPRegInfo *ri,
1396                                         bool isread)
1397 {
1398     /* ER: event counter read trap control */
1399     if (arm_feature(env, ARM_FEATURE_V8)
1400         && arm_current_el(env) == 0
1401         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1402         return CP_ACCESS_OK;
1403     }
1404 
1405     return pmreg_access(env, ri, isread);
1406 }
1407 
1408 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1409                                          const ARMCPRegInfo *ri,
1410                                          bool isread)
1411 {
1412     /* CR: cycle counter read trap control */
1413     if (arm_feature(env, ARM_FEATURE_V8)
1414         && arm_current_el(env) == 0
1415         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1416         && isread) {
1417         return CP_ACCESS_OK;
1418     }
1419 
1420     return pmreg_access(env, ri, isread);
1421 }
1422 
1423 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1424  * the current EL, security state, and register configuration.
1425  */
1426 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1427 {
1428     uint64_t filter;
1429     bool e, p, u, nsk, nsu, nsh, m;
1430     bool enabled, prohibited, filtered;
1431     bool secure = arm_is_secure(env);
1432     int el = arm_current_el(env);
1433     uint8_t hpmn = env->cp15.mdcr_el2 & MDCR_HPMN;
1434 
1435     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1436         return false;
1437     }
1438 
1439     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1440             (counter < hpmn || counter == 31)) {
1441         e = env->cp15.c9_pmcr & PMCRE;
1442     } else {
1443         e = env->cp15.mdcr_el2 & MDCR_HPME;
1444     }
1445     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1446 
1447     if (!secure) {
1448         if (el == 2 && (counter < hpmn || counter == 31)) {
1449             prohibited = env->cp15.mdcr_el2 & MDCR_HPMD;
1450         } else {
1451             prohibited = false;
1452         }
1453     } else {
1454         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1455            !(env->cp15.mdcr_el3 & MDCR_SPME);
1456     }
1457 
1458     if (prohibited && counter == 31) {
1459         prohibited = env->cp15.c9_pmcr & PMCRDP;
1460     }
1461 
1462     if (counter == 31) {
1463         filter = env->cp15.pmccfiltr_el0;
1464     } else {
1465         filter = env->cp15.c14_pmevtyper[counter];
1466     }
1467 
1468     p   = filter & PMXEVTYPER_P;
1469     u   = filter & PMXEVTYPER_U;
1470     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1471     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1472     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1473     m   = arm_el_is_aa64(env, 1) &&
1474               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1475 
1476     if (el == 0) {
1477         filtered = secure ? u : u != nsu;
1478     } else if (el == 1) {
1479         filtered = secure ? p : p != nsk;
1480     } else if (el == 2) {
1481         filtered = !nsh;
1482     } else { /* EL3 */
1483         filtered = m != p;
1484     }
1485 
1486     if (counter != 31) {
1487         /*
1488          * If not checking PMCCNTR, ensure the counter is setup to an event we
1489          * support
1490          */
1491         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1492         if (!event_supported(event)) {
1493             return false;
1494         }
1495     }
1496 
1497     return enabled && !prohibited && !filtered;
1498 }
1499 
1500 static void pmu_update_irq(CPUARMState *env)
1501 {
1502     ARMCPU *cpu = env_archcpu(env);
1503     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1504             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1505 }
1506 
1507 /*
1508  * Ensure c15_ccnt is the guest-visible count so that operations such as
1509  * enabling/disabling the counter or filtering, modifying the count itself,
1510  * etc. can be done logically. This is essentially a no-op if the counter is
1511  * not enabled at the time of the call.
1512  */
1513 static void pmccntr_op_start(CPUARMState *env)
1514 {
1515     uint64_t cycles = cycles_get_count(env);
1516 
1517     if (pmu_counter_enabled(env, 31)) {
1518         uint64_t eff_cycles = cycles;
1519         if (env->cp15.c9_pmcr & PMCRD) {
1520             /* Increment once every 64 processor clock cycles */
1521             eff_cycles /= 64;
1522         }
1523 
1524         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1525 
1526         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1527                                  1ull << 63 : 1ull << 31;
1528         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1529             env->cp15.c9_pmovsr |= (1 << 31);
1530             pmu_update_irq(env);
1531         }
1532 
1533         env->cp15.c15_ccnt = new_pmccntr;
1534     }
1535     env->cp15.c15_ccnt_delta = cycles;
1536 }
1537 
1538 /*
1539  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1540  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1541  * pmccntr_op_start.
1542  */
1543 static void pmccntr_op_finish(CPUARMState *env)
1544 {
1545     if (pmu_counter_enabled(env, 31)) {
1546 #ifndef CONFIG_USER_ONLY
1547         /* Calculate when the counter will next overflow */
1548         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1549         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1550             remaining_cycles = (uint32_t)remaining_cycles;
1551         }
1552         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1553 
1554         if (overflow_in > 0) {
1555             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1556                 overflow_in;
1557             ARMCPU *cpu = env_archcpu(env);
1558             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1559         }
1560 #endif
1561 
1562         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1563         if (env->cp15.c9_pmcr & PMCRD) {
1564             /* Increment once every 64 processor clock cycles */
1565             prev_cycles /= 64;
1566         }
1567         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1568     }
1569 }
1570 
1571 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1572 {
1573 
1574     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1575     uint64_t count = 0;
1576     if (event_supported(event)) {
1577         uint16_t event_idx = supported_event_map[event];
1578         count = pm_events[event_idx].get_count(env);
1579     }
1580 
1581     if (pmu_counter_enabled(env, counter)) {
1582         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1583 
1584         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1585             env->cp15.c9_pmovsr |= (1 << counter);
1586             pmu_update_irq(env);
1587         }
1588         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1589     }
1590     env->cp15.c14_pmevcntr_delta[counter] = count;
1591 }
1592 
1593 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1594 {
1595     if (pmu_counter_enabled(env, counter)) {
1596 #ifndef CONFIG_USER_ONLY
1597         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1598         uint16_t event_idx = supported_event_map[event];
1599         uint64_t delta = UINT32_MAX -
1600             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1601         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1602 
1603         if (overflow_in > 0) {
1604             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1605                 overflow_in;
1606             ARMCPU *cpu = env_archcpu(env);
1607             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1608         }
1609 #endif
1610 
1611         env->cp15.c14_pmevcntr_delta[counter] -=
1612             env->cp15.c14_pmevcntr[counter];
1613     }
1614 }
1615 
1616 void pmu_op_start(CPUARMState *env)
1617 {
1618     unsigned int i;
1619     pmccntr_op_start(env);
1620     for (i = 0; i < pmu_num_counters(env); i++) {
1621         pmevcntr_op_start(env, i);
1622     }
1623 }
1624 
1625 void pmu_op_finish(CPUARMState *env)
1626 {
1627     unsigned int i;
1628     pmccntr_op_finish(env);
1629     for (i = 0; i < pmu_num_counters(env); i++) {
1630         pmevcntr_op_finish(env, i);
1631     }
1632 }
1633 
1634 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1635 {
1636     pmu_op_start(&cpu->env);
1637 }
1638 
1639 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1640 {
1641     pmu_op_finish(&cpu->env);
1642 }
1643 
1644 void arm_pmu_timer_cb(void *opaque)
1645 {
1646     ARMCPU *cpu = opaque;
1647 
1648     /*
1649      * Update all the counter values based on the current underlying counts,
1650      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1651      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1652      * counter may expire.
1653      */
1654     pmu_op_start(&cpu->env);
1655     pmu_op_finish(&cpu->env);
1656 }
1657 
1658 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1659                        uint64_t value)
1660 {
1661     pmu_op_start(env);
1662 
1663     if (value & PMCRC) {
1664         /* The counter has been reset */
1665         env->cp15.c15_ccnt = 0;
1666     }
1667 
1668     if (value & PMCRP) {
1669         unsigned int i;
1670         for (i = 0; i < pmu_num_counters(env); i++) {
1671             env->cp15.c14_pmevcntr[i] = 0;
1672         }
1673     }
1674 
1675     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1676     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1677 
1678     pmu_op_finish(env);
1679 }
1680 
1681 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1682                           uint64_t value)
1683 {
1684     unsigned int i;
1685     for (i = 0; i < pmu_num_counters(env); i++) {
1686         /* Increment a counter's count iff: */
1687         if ((value & (1 << i)) && /* counter's bit is set */
1688                 /* counter is enabled and not filtered */
1689                 pmu_counter_enabled(env, i) &&
1690                 /* counter is SW_INCR */
1691                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1692             pmevcntr_op_start(env, i);
1693 
1694             /*
1695              * Detect if this write causes an overflow since we can't predict
1696              * PMSWINC overflows like we can for other events
1697              */
1698             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1699 
1700             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1701                 env->cp15.c9_pmovsr |= (1 << i);
1702                 pmu_update_irq(env);
1703             }
1704 
1705             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1706 
1707             pmevcntr_op_finish(env, i);
1708         }
1709     }
1710 }
1711 
1712 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1713 {
1714     uint64_t ret;
1715     pmccntr_op_start(env);
1716     ret = env->cp15.c15_ccnt;
1717     pmccntr_op_finish(env);
1718     return ret;
1719 }
1720 
1721 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1722                          uint64_t value)
1723 {
1724     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1725      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1726      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1727      * accessed.
1728      */
1729     env->cp15.c9_pmselr = value & 0x1f;
1730 }
1731 
1732 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1733                         uint64_t value)
1734 {
1735     pmccntr_op_start(env);
1736     env->cp15.c15_ccnt = value;
1737     pmccntr_op_finish(env);
1738 }
1739 
1740 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1741                             uint64_t value)
1742 {
1743     uint64_t cur_val = pmccntr_read(env, NULL);
1744 
1745     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1746 }
1747 
1748 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1749                             uint64_t value)
1750 {
1751     pmccntr_op_start(env);
1752     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1753     pmccntr_op_finish(env);
1754 }
1755 
1756 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1757                             uint64_t value)
1758 {
1759     pmccntr_op_start(env);
1760     /* M is not accessible from AArch32 */
1761     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1762         (value & PMCCFILTR);
1763     pmccntr_op_finish(env);
1764 }
1765 
1766 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1767 {
1768     /* M is not visible in AArch32 */
1769     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1770 }
1771 
1772 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1773                             uint64_t value)
1774 {
1775     value &= pmu_counter_mask(env);
1776     env->cp15.c9_pmcnten |= value;
1777 }
1778 
1779 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1780                              uint64_t value)
1781 {
1782     value &= pmu_counter_mask(env);
1783     env->cp15.c9_pmcnten &= ~value;
1784 }
1785 
1786 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1787                          uint64_t value)
1788 {
1789     value &= pmu_counter_mask(env);
1790     env->cp15.c9_pmovsr &= ~value;
1791     pmu_update_irq(env);
1792 }
1793 
1794 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1795                          uint64_t value)
1796 {
1797     value &= pmu_counter_mask(env);
1798     env->cp15.c9_pmovsr |= value;
1799     pmu_update_irq(env);
1800 }
1801 
1802 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1803                              uint64_t value, const uint8_t counter)
1804 {
1805     if (counter == 31) {
1806         pmccfiltr_write(env, ri, value);
1807     } else if (counter < pmu_num_counters(env)) {
1808         pmevcntr_op_start(env, counter);
1809 
1810         /*
1811          * If this counter's event type is changing, store the current
1812          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1813          * pmevcntr_op_finish has the correct baseline when it converts back to
1814          * a delta.
1815          */
1816         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1817             PMXEVTYPER_EVTCOUNT;
1818         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1819         if (old_event != new_event) {
1820             uint64_t count = 0;
1821             if (event_supported(new_event)) {
1822                 uint16_t event_idx = supported_event_map[new_event];
1823                 count = pm_events[event_idx].get_count(env);
1824             }
1825             env->cp15.c14_pmevcntr_delta[counter] = count;
1826         }
1827 
1828         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1829         pmevcntr_op_finish(env, counter);
1830     }
1831     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1832      * PMSELR value is equal to or greater than the number of implemented
1833      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1834      */
1835 }
1836 
1837 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1838                                const uint8_t counter)
1839 {
1840     if (counter == 31) {
1841         return env->cp15.pmccfiltr_el0;
1842     } else if (counter < pmu_num_counters(env)) {
1843         return env->cp15.c14_pmevtyper[counter];
1844     } else {
1845       /*
1846        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1847        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1848        */
1849         return 0;
1850     }
1851 }
1852 
1853 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1854                               uint64_t value)
1855 {
1856     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1857     pmevtyper_write(env, ri, value, counter);
1858 }
1859 
1860 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1861                                uint64_t value)
1862 {
1863     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1864     env->cp15.c14_pmevtyper[counter] = value;
1865 
1866     /*
1867      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1868      * pmu_op_finish calls when loading saved state for a migration. Because
1869      * we're potentially updating the type of event here, the value written to
1870      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1871      * different counter type. Therefore, we need to set this value to the
1872      * current count for the counter type we're writing so that pmu_op_finish
1873      * has the correct count for its calculation.
1874      */
1875     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1876     if (event_supported(event)) {
1877         uint16_t event_idx = supported_event_map[event];
1878         env->cp15.c14_pmevcntr_delta[counter] =
1879             pm_events[event_idx].get_count(env);
1880     }
1881 }
1882 
1883 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1884 {
1885     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1886     return pmevtyper_read(env, ri, counter);
1887 }
1888 
1889 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1890                              uint64_t value)
1891 {
1892     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1893 }
1894 
1895 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1896 {
1897     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1898 }
1899 
1900 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1901                              uint64_t value, uint8_t counter)
1902 {
1903     if (counter < pmu_num_counters(env)) {
1904         pmevcntr_op_start(env, counter);
1905         env->cp15.c14_pmevcntr[counter] = value;
1906         pmevcntr_op_finish(env, counter);
1907     }
1908     /*
1909      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1910      * are CONSTRAINED UNPREDICTABLE.
1911      */
1912 }
1913 
1914 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1915                               uint8_t counter)
1916 {
1917     if (counter < pmu_num_counters(env)) {
1918         uint64_t ret;
1919         pmevcntr_op_start(env, counter);
1920         ret = env->cp15.c14_pmevcntr[counter];
1921         pmevcntr_op_finish(env, counter);
1922         return ret;
1923     } else {
1924       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1925        * are CONSTRAINED UNPREDICTABLE. */
1926         return 0;
1927     }
1928 }
1929 
1930 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1931                              uint64_t value)
1932 {
1933     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1934     pmevcntr_write(env, ri, value, counter);
1935 }
1936 
1937 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1938 {
1939     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1940     return pmevcntr_read(env, ri, counter);
1941 }
1942 
1943 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1944                              uint64_t value)
1945 {
1946     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1947     assert(counter < pmu_num_counters(env));
1948     env->cp15.c14_pmevcntr[counter] = value;
1949     pmevcntr_write(env, ri, value, counter);
1950 }
1951 
1952 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1953 {
1954     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1955     assert(counter < pmu_num_counters(env));
1956     return env->cp15.c14_pmevcntr[counter];
1957 }
1958 
1959 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1960                              uint64_t value)
1961 {
1962     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1963 }
1964 
1965 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1966 {
1967     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1968 }
1969 
1970 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1971                             uint64_t value)
1972 {
1973     if (arm_feature(env, ARM_FEATURE_V8)) {
1974         env->cp15.c9_pmuserenr = value & 0xf;
1975     } else {
1976         env->cp15.c9_pmuserenr = value & 1;
1977     }
1978 }
1979 
1980 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1981                              uint64_t value)
1982 {
1983     /* We have no event counters so only the C bit can be changed */
1984     value &= pmu_counter_mask(env);
1985     env->cp15.c9_pminten |= value;
1986     pmu_update_irq(env);
1987 }
1988 
1989 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1990                              uint64_t value)
1991 {
1992     value &= pmu_counter_mask(env);
1993     env->cp15.c9_pminten &= ~value;
1994     pmu_update_irq(env);
1995 }
1996 
1997 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1998                        uint64_t value)
1999 {
2000     /* Note that even though the AArch64 view of this register has bits
2001      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
2002      * architectural requirements for bits which are RES0 only in some
2003      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
2004      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
2005      */
2006     raw_write(env, ri, value & ~0x1FULL);
2007 }
2008 
2009 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2010 {
2011     /* Begin with base v8.0 state.  */
2012     uint32_t valid_mask = 0x3fff;
2013     ARMCPU *cpu = env_archcpu(env);
2014 
2015     if (ri->state == ARM_CP_STATE_AA64) {
2016         value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
2017         valid_mask &= ~SCR_NET;
2018 
2019         if (cpu_isar_feature(aa64_lor, cpu)) {
2020             valid_mask |= SCR_TLOR;
2021         }
2022         if (cpu_isar_feature(aa64_pauth, cpu)) {
2023             valid_mask |= SCR_API | SCR_APK;
2024         }
2025         if (cpu_isar_feature(aa64_mte, cpu)) {
2026             valid_mask |= SCR_ATA;
2027         }
2028     } else {
2029         valid_mask &= ~(SCR_RW | SCR_ST);
2030     }
2031 
2032     if (!arm_feature(env, ARM_FEATURE_EL2)) {
2033         valid_mask &= ~SCR_HCE;
2034 
2035         /* On ARMv7, SMD (or SCD as it is called in v7) is only
2036          * supported if EL2 exists. The bit is UNK/SBZP when
2037          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
2038          * when EL2 is unavailable.
2039          * On ARMv8, this bit is always available.
2040          */
2041         if (arm_feature(env, ARM_FEATURE_V7) &&
2042             !arm_feature(env, ARM_FEATURE_V8)) {
2043             valid_mask &= ~SCR_SMD;
2044         }
2045     }
2046 
2047     /* Clear all-context RES0 bits.  */
2048     value &= valid_mask;
2049     raw_write(env, ri, value);
2050 }
2051 
2052 static CPAccessResult access_aa64_tid2(CPUARMState *env,
2053                                        const ARMCPRegInfo *ri,
2054                                        bool isread)
2055 {
2056     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
2057         return CP_ACCESS_TRAP_EL2;
2058     }
2059 
2060     return CP_ACCESS_OK;
2061 }
2062 
2063 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2064 {
2065     ARMCPU *cpu = env_archcpu(env);
2066 
2067     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
2068      * bank
2069      */
2070     uint32_t index = A32_BANKED_REG_GET(env, csselr,
2071                                         ri->secure & ARM_CP_SECSTATE_S);
2072 
2073     return cpu->ccsidr[index];
2074 }
2075 
2076 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2077                          uint64_t value)
2078 {
2079     raw_write(env, ri, value & 0xf);
2080 }
2081 
2082 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2083 {
2084     CPUState *cs = env_cpu(env);
2085     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
2086     uint64_t ret = 0;
2087     bool allow_virt = (arm_current_el(env) == 1 &&
2088                        (!arm_is_secure_below_el3(env) ||
2089                         (env->cp15.scr_el3 & SCR_EEL2)));
2090 
2091     if (allow_virt && (hcr_el2 & HCR_IMO)) {
2092         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
2093             ret |= CPSR_I;
2094         }
2095     } else {
2096         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
2097             ret |= CPSR_I;
2098         }
2099     }
2100 
2101     if (allow_virt && (hcr_el2 & HCR_FMO)) {
2102         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
2103             ret |= CPSR_F;
2104         }
2105     } else {
2106         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
2107             ret |= CPSR_F;
2108         }
2109     }
2110 
2111     /* External aborts are not possible in QEMU so A bit is always clear */
2112     return ret;
2113 }
2114 
2115 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2116                                        bool isread)
2117 {
2118     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
2119         return CP_ACCESS_TRAP_EL2;
2120     }
2121 
2122     return CP_ACCESS_OK;
2123 }
2124 
2125 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2126                                        bool isread)
2127 {
2128     if (arm_feature(env, ARM_FEATURE_V8)) {
2129         return access_aa64_tid1(env, ri, isread);
2130     }
2131 
2132     return CP_ACCESS_OK;
2133 }
2134 
2135 static const ARMCPRegInfo v7_cp_reginfo[] = {
2136     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
2137     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
2138       .access = PL1_W, .type = ARM_CP_NOP },
2139     /* Performance monitors are implementation defined in v7,
2140      * but with an ARM recommended set of registers, which we
2141      * follow.
2142      *
2143      * Performance registers fall into three categories:
2144      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
2145      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
2146      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
2147      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
2148      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
2149      */
2150     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
2151       .access = PL0_RW, .type = ARM_CP_ALIAS,
2152       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2153       .writefn = pmcntenset_write,
2154       .accessfn = pmreg_access,
2155       .raw_writefn = raw_write },
2156     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
2157       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
2158       .access = PL0_RW, .accessfn = pmreg_access,
2159       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
2160       .writefn = pmcntenset_write, .raw_writefn = raw_write },
2161     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
2162       .access = PL0_RW,
2163       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2164       .accessfn = pmreg_access,
2165       .writefn = pmcntenclr_write,
2166       .type = ARM_CP_ALIAS },
2167     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
2168       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
2169       .access = PL0_RW, .accessfn = pmreg_access,
2170       .type = ARM_CP_ALIAS,
2171       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
2172       .writefn = pmcntenclr_write },
2173     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
2174       .access = PL0_RW, .type = ARM_CP_IO,
2175       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2176       .accessfn = pmreg_access,
2177       .writefn = pmovsr_write,
2178       .raw_writefn = raw_write },
2179     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2180       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2181       .access = PL0_RW, .accessfn = pmreg_access,
2182       .type = ARM_CP_ALIAS | ARM_CP_IO,
2183       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2184       .writefn = pmovsr_write,
2185       .raw_writefn = raw_write },
2186     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2187       .access = PL0_W, .accessfn = pmreg_access_swinc,
2188       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2189       .writefn = pmswinc_write },
2190     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2191       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2192       .access = PL0_W, .accessfn = pmreg_access_swinc,
2193       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2194       .writefn = pmswinc_write },
2195     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2196       .access = PL0_RW, .type = ARM_CP_ALIAS,
2197       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2198       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2199       .raw_writefn = raw_write},
2200     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2201       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2202       .access = PL0_RW, .accessfn = pmreg_access_selr,
2203       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2204       .writefn = pmselr_write, .raw_writefn = raw_write, },
2205     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2206       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2207       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2208       .accessfn = pmreg_access_ccntr },
2209     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2210       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2211       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2212       .type = ARM_CP_IO,
2213       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2214       .readfn = pmccntr_read, .writefn = pmccntr_write,
2215       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2216     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2217       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2218       .access = PL0_RW, .accessfn = pmreg_access,
2219       .type = ARM_CP_ALIAS | ARM_CP_IO,
2220       .resetvalue = 0, },
2221     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2222       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2223       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2224       .access = PL0_RW, .accessfn = pmreg_access,
2225       .type = ARM_CP_IO,
2226       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2227       .resetvalue = 0, },
2228     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2229       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2230       .accessfn = pmreg_access,
2231       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2232     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2233       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2234       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2235       .accessfn = pmreg_access,
2236       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2237     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2238       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2239       .accessfn = pmreg_access_xevcntr,
2240       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2241     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2242       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2243       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2244       .accessfn = pmreg_access_xevcntr,
2245       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2246     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2247       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2248       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2249       .resetvalue = 0,
2250       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2251     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2252       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2253       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2254       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2255       .resetvalue = 0,
2256       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2257     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2258       .access = PL1_RW, .accessfn = access_tpm,
2259       .type = ARM_CP_ALIAS | ARM_CP_IO,
2260       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2261       .resetvalue = 0,
2262       .writefn = pmintenset_write, .raw_writefn = raw_write },
2263     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2264       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2265       .access = PL1_RW, .accessfn = access_tpm,
2266       .type = ARM_CP_IO,
2267       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2268       .writefn = pmintenset_write, .raw_writefn = raw_write,
2269       .resetvalue = 0x0 },
2270     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2271       .access = PL1_RW, .accessfn = access_tpm,
2272       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2273       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2274       .writefn = pmintenclr_write, },
2275     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2276       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2277       .access = PL1_RW, .accessfn = access_tpm,
2278       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2279       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2280       .writefn = pmintenclr_write },
2281     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2282       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2283       .access = PL1_R,
2284       .accessfn = access_aa64_tid2,
2285       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2286     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2287       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2288       .access = PL1_RW,
2289       .accessfn = access_aa64_tid2,
2290       .writefn = csselr_write, .resetvalue = 0,
2291       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2292                              offsetof(CPUARMState, cp15.csselr_ns) } },
2293     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2294      * just RAZ for all cores:
2295      */
2296     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2297       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2298       .access = PL1_R, .type = ARM_CP_CONST,
2299       .accessfn = access_aa64_tid1,
2300       .resetvalue = 0 },
2301     /* Auxiliary fault status registers: these also are IMPDEF, and we
2302      * choose to RAZ/WI for all cores.
2303      */
2304     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2305       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2306       .access = PL1_RW, .accessfn = access_tvm_trvm,
2307       .type = ARM_CP_CONST, .resetvalue = 0 },
2308     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2309       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2310       .access = PL1_RW, .accessfn = access_tvm_trvm,
2311       .type = ARM_CP_CONST, .resetvalue = 0 },
2312     /* MAIR can just read-as-written because we don't implement caches
2313      * and so don't need to care about memory attributes.
2314      */
2315     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2316       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2317       .access = PL1_RW, .accessfn = access_tvm_trvm,
2318       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2319       .resetvalue = 0 },
2320     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2321       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2322       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2323       .resetvalue = 0 },
2324     /* For non-long-descriptor page tables these are PRRR and NMRR;
2325      * regardless they still act as reads-as-written for QEMU.
2326      */
2327      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2328       * allows them to assign the correct fieldoffset based on the endianness
2329       * handled in the field definitions.
2330       */
2331     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2332       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2333       .access = PL1_RW, .accessfn = access_tvm_trvm,
2334       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2335                              offsetof(CPUARMState, cp15.mair0_ns) },
2336       .resetfn = arm_cp_reset_ignore },
2337     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2338       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2339       .access = PL1_RW, .accessfn = access_tvm_trvm,
2340       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2341                              offsetof(CPUARMState, cp15.mair1_ns) },
2342       .resetfn = arm_cp_reset_ignore },
2343     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2344       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2345       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2346     /* 32 bit ITLB invalidates */
2347     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2348       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2349       .writefn = tlbiall_write },
2350     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2351       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2352       .writefn = tlbimva_write },
2353     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2354       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2355       .writefn = tlbiasid_write },
2356     /* 32 bit DTLB invalidates */
2357     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2358       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2359       .writefn = tlbiall_write },
2360     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2361       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2362       .writefn = tlbimva_write },
2363     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2364       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2365       .writefn = tlbiasid_write },
2366     /* 32 bit TLB invalidates */
2367     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2368       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2369       .writefn = tlbiall_write },
2370     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2371       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2372       .writefn = tlbimva_write },
2373     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2374       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2375       .writefn = tlbiasid_write },
2376     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2377       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2378       .writefn = tlbimvaa_write },
2379     REGINFO_SENTINEL
2380 };
2381 
2382 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2383     /* 32 bit TLB invalidates, Inner Shareable */
2384     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2385       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2386       .writefn = tlbiall_is_write },
2387     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2388       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2389       .writefn = tlbimva_is_write },
2390     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2391       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2392       .writefn = tlbiasid_is_write },
2393     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2394       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2395       .writefn = tlbimvaa_is_write },
2396     REGINFO_SENTINEL
2397 };
2398 
2399 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2400     /* PMOVSSET is not implemented in v7 before v7ve */
2401     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2402       .access = PL0_RW, .accessfn = pmreg_access,
2403       .type = ARM_CP_ALIAS | ARM_CP_IO,
2404       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2405       .writefn = pmovsset_write,
2406       .raw_writefn = raw_write },
2407     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2408       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2409       .access = PL0_RW, .accessfn = pmreg_access,
2410       .type = ARM_CP_ALIAS | ARM_CP_IO,
2411       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2412       .writefn = pmovsset_write,
2413       .raw_writefn = raw_write },
2414     REGINFO_SENTINEL
2415 };
2416 
2417 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2418                         uint64_t value)
2419 {
2420     value &= 1;
2421     env->teecr = value;
2422 }
2423 
2424 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2425                                     bool isread)
2426 {
2427     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2428         return CP_ACCESS_TRAP;
2429     }
2430     return CP_ACCESS_OK;
2431 }
2432 
2433 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2434     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2435       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2436       .resetvalue = 0,
2437       .writefn = teecr_write },
2438     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2439       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2440       .accessfn = teehbr_access, .resetvalue = 0 },
2441     REGINFO_SENTINEL
2442 };
2443 
2444 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2445     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2446       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2447       .access = PL0_RW,
2448       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2449     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2450       .access = PL0_RW,
2451       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2452                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2453       .resetfn = arm_cp_reset_ignore },
2454     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2455       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2456       .access = PL0_R|PL1_W,
2457       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2458       .resetvalue = 0},
2459     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2460       .access = PL0_R|PL1_W,
2461       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2462                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2463       .resetfn = arm_cp_reset_ignore },
2464     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2465       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2466       .access = PL1_RW,
2467       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2468     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2469       .access = PL1_RW,
2470       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2471                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2472       .resetvalue = 0 },
2473     REGINFO_SENTINEL
2474 };
2475 
2476 #ifndef CONFIG_USER_ONLY
2477 
2478 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2479                                        bool isread)
2480 {
2481     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2482      * Writable only at the highest implemented exception level.
2483      */
2484     int el = arm_current_el(env);
2485     uint64_t hcr;
2486     uint32_t cntkctl;
2487 
2488     switch (el) {
2489     case 0:
2490         hcr = arm_hcr_el2_eff(env);
2491         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2492             cntkctl = env->cp15.cnthctl_el2;
2493         } else {
2494             cntkctl = env->cp15.c14_cntkctl;
2495         }
2496         if (!extract32(cntkctl, 0, 2)) {
2497             return CP_ACCESS_TRAP;
2498         }
2499         break;
2500     case 1:
2501         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2502             arm_is_secure_below_el3(env)) {
2503             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2504             return CP_ACCESS_TRAP_UNCATEGORIZED;
2505         }
2506         break;
2507     case 2:
2508     case 3:
2509         break;
2510     }
2511 
2512     if (!isread && el < arm_highest_el(env)) {
2513         return CP_ACCESS_TRAP_UNCATEGORIZED;
2514     }
2515 
2516     return CP_ACCESS_OK;
2517 }
2518 
2519 static CPAccessResult gt_counter_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_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2529         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2530             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2531                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2532         }
2533 
2534         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2535         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2536             return CP_ACCESS_TRAP;
2537         }
2538 
2539         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2540         if (hcr & HCR_E2H) {
2541             if (timeridx == GTIMER_PHYS &&
2542                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2543                 return CP_ACCESS_TRAP_EL2;
2544             }
2545         } else {
2546             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2547             if (arm_feature(env, ARM_FEATURE_EL2) &&
2548                 timeridx == GTIMER_PHYS && !secure &&
2549                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2550                 return CP_ACCESS_TRAP_EL2;
2551             }
2552         }
2553         break;
2554 
2555     case 1:
2556         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2557         if (arm_feature(env, ARM_FEATURE_EL2) &&
2558             timeridx == GTIMER_PHYS && !secure &&
2559             (hcr & HCR_E2H
2560              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2561              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2562             return CP_ACCESS_TRAP_EL2;
2563         }
2564         break;
2565     }
2566     return CP_ACCESS_OK;
2567 }
2568 
2569 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2570                                       bool isread)
2571 {
2572     unsigned int cur_el = arm_current_el(env);
2573     bool secure = arm_is_secure(env);
2574     uint64_t hcr = arm_hcr_el2_eff(env);
2575 
2576     switch (cur_el) {
2577     case 0:
2578         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2579             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2580             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2581                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2582         }
2583 
2584         /*
2585          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2586          * EL0 if EL0[PV]TEN is zero.
2587          */
2588         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2589             return CP_ACCESS_TRAP;
2590         }
2591         /* fall through */
2592 
2593     case 1:
2594         if (arm_feature(env, ARM_FEATURE_EL2) &&
2595             timeridx == GTIMER_PHYS && !secure) {
2596             if (hcr & HCR_E2H) {
2597                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2598                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2599                     return CP_ACCESS_TRAP_EL2;
2600                 }
2601             } else {
2602                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2603                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2604                     return CP_ACCESS_TRAP_EL2;
2605                 }
2606             }
2607         }
2608         break;
2609     }
2610     return CP_ACCESS_OK;
2611 }
2612 
2613 static CPAccessResult gt_pct_access(CPUARMState *env,
2614                                     const ARMCPRegInfo *ri,
2615                                     bool isread)
2616 {
2617     return gt_counter_access(env, GTIMER_PHYS, isread);
2618 }
2619 
2620 static CPAccessResult gt_vct_access(CPUARMState *env,
2621                                     const ARMCPRegInfo *ri,
2622                                     bool isread)
2623 {
2624     return gt_counter_access(env, GTIMER_VIRT, isread);
2625 }
2626 
2627 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2628                                        bool isread)
2629 {
2630     return gt_timer_access(env, GTIMER_PHYS, isread);
2631 }
2632 
2633 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2634                                        bool isread)
2635 {
2636     return gt_timer_access(env, GTIMER_VIRT, isread);
2637 }
2638 
2639 static CPAccessResult gt_stimer_access(CPUARMState *env,
2640                                        const ARMCPRegInfo *ri,
2641                                        bool isread)
2642 {
2643     /* The AArch64 register view of the secure physical timer is
2644      * always accessible from EL3, and configurably accessible from
2645      * Secure EL1.
2646      */
2647     switch (arm_current_el(env)) {
2648     case 1:
2649         if (!arm_is_secure(env)) {
2650             return CP_ACCESS_TRAP;
2651         }
2652         if (!(env->cp15.scr_el3 & SCR_ST)) {
2653             return CP_ACCESS_TRAP_EL3;
2654         }
2655         return CP_ACCESS_OK;
2656     case 0:
2657     case 2:
2658         return CP_ACCESS_TRAP;
2659     case 3:
2660         return CP_ACCESS_OK;
2661     default:
2662         g_assert_not_reached();
2663     }
2664 }
2665 
2666 static uint64_t gt_get_countervalue(CPUARMState *env)
2667 {
2668     ARMCPU *cpu = env_archcpu(env);
2669 
2670     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2671 }
2672 
2673 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2674 {
2675     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2676 
2677     if (gt->ctl & 1) {
2678         /* Timer enabled: calculate and set current ISTATUS, irq, and
2679          * reset timer to when ISTATUS next has to change
2680          */
2681         uint64_t offset = timeridx == GTIMER_VIRT ?
2682                                       cpu->env.cp15.cntvoff_el2 : 0;
2683         uint64_t count = gt_get_countervalue(&cpu->env);
2684         /* Note that this must be unsigned 64 bit arithmetic: */
2685         int istatus = count - offset >= gt->cval;
2686         uint64_t nexttick;
2687         int irqstate;
2688 
2689         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2690 
2691         irqstate = (istatus && !(gt->ctl & 2));
2692         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2693 
2694         if (istatus) {
2695             /* Next transition is when count rolls back over to zero */
2696             nexttick = UINT64_MAX;
2697         } else {
2698             /* Next transition is when we hit cval */
2699             nexttick = gt->cval + offset;
2700         }
2701         /* Note that the desired next expiry time might be beyond the
2702          * signed-64-bit range of a QEMUTimer -- in this case we just
2703          * set the timer for as far in the future as possible. When the
2704          * timer expires we will reset the timer for any remaining period.
2705          */
2706         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2707             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2708         } else {
2709             timer_mod(cpu->gt_timer[timeridx], nexttick);
2710         }
2711         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2712     } else {
2713         /* Timer disabled: ISTATUS and timer output always clear */
2714         gt->ctl &= ~4;
2715         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2716         timer_del(cpu->gt_timer[timeridx]);
2717         trace_arm_gt_recalc_disabled(timeridx);
2718     }
2719 }
2720 
2721 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2722                            int timeridx)
2723 {
2724     ARMCPU *cpu = env_archcpu(env);
2725 
2726     timer_del(cpu->gt_timer[timeridx]);
2727 }
2728 
2729 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2730 {
2731     return gt_get_countervalue(env);
2732 }
2733 
2734 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2735 {
2736     uint64_t hcr;
2737 
2738     switch (arm_current_el(env)) {
2739     case 2:
2740         hcr = arm_hcr_el2_eff(env);
2741         if (hcr & HCR_E2H) {
2742             return 0;
2743         }
2744         break;
2745     case 0:
2746         hcr = arm_hcr_el2_eff(env);
2747         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2748             return 0;
2749         }
2750         break;
2751     }
2752 
2753     return env->cp15.cntvoff_el2;
2754 }
2755 
2756 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2757 {
2758     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2759 }
2760 
2761 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2762                           int timeridx,
2763                           uint64_t value)
2764 {
2765     trace_arm_gt_cval_write(timeridx, value);
2766     env->cp15.c14_timer[timeridx].cval = value;
2767     gt_recalc_timer(env_archcpu(env), timeridx);
2768 }
2769 
2770 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2771                              int timeridx)
2772 {
2773     uint64_t offset = 0;
2774 
2775     switch (timeridx) {
2776     case GTIMER_VIRT:
2777     case GTIMER_HYPVIRT:
2778         offset = gt_virt_cnt_offset(env);
2779         break;
2780     }
2781 
2782     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2783                       (gt_get_countervalue(env) - offset));
2784 }
2785 
2786 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2787                           int timeridx,
2788                           uint64_t value)
2789 {
2790     uint64_t offset = 0;
2791 
2792     switch (timeridx) {
2793     case GTIMER_VIRT:
2794     case GTIMER_HYPVIRT:
2795         offset = gt_virt_cnt_offset(env);
2796         break;
2797     }
2798 
2799     trace_arm_gt_tval_write(timeridx, value);
2800     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2801                                          sextract64(value, 0, 32);
2802     gt_recalc_timer(env_archcpu(env), timeridx);
2803 }
2804 
2805 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2806                          int timeridx,
2807                          uint64_t value)
2808 {
2809     ARMCPU *cpu = env_archcpu(env);
2810     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2811 
2812     trace_arm_gt_ctl_write(timeridx, value);
2813     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2814     if ((oldval ^ value) & 1) {
2815         /* Enable toggled */
2816         gt_recalc_timer(cpu, timeridx);
2817     } else if ((oldval ^ value) & 2) {
2818         /* IMASK toggled: don't need to recalculate,
2819          * just set the interrupt line based on ISTATUS
2820          */
2821         int irqstate = (oldval & 4) && !(value & 2);
2822 
2823         trace_arm_gt_imask_toggle(timeridx, irqstate);
2824         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2825     }
2826 }
2827 
2828 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2829 {
2830     gt_timer_reset(env, ri, GTIMER_PHYS);
2831 }
2832 
2833 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2834                                uint64_t value)
2835 {
2836     gt_cval_write(env, ri, GTIMER_PHYS, value);
2837 }
2838 
2839 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2840 {
2841     return gt_tval_read(env, ri, GTIMER_PHYS);
2842 }
2843 
2844 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2845                                uint64_t value)
2846 {
2847     gt_tval_write(env, ri, GTIMER_PHYS, value);
2848 }
2849 
2850 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2851                               uint64_t value)
2852 {
2853     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2854 }
2855 
2856 static int gt_phys_redir_timeridx(CPUARMState *env)
2857 {
2858     switch (arm_mmu_idx(env)) {
2859     case ARMMMUIdx_E20_0:
2860     case ARMMMUIdx_E20_2:
2861     case ARMMMUIdx_E20_2_PAN:
2862         return GTIMER_HYP;
2863     default:
2864         return GTIMER_PHYS;
2865     }
2866 }
2867 
2868 static int gt_virt_redir_timeridx(CPUARMState *env)
2869 {
2870     switch (arm_mmu_idx(env)) {
2871     case ARMMMUIdx_E20_0:
2872     case ARMMMUIdx_E20_2:
2873     case ARMMMUIdx_E20_2_PAN:
2874         return GTIMER_HYPVIRT;
2875     default:
2876         return GTIMER_VIRT;
2877     }
2878 }
2879 
2880 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2881                                         const ARMCPRegInfo *ri)
2882 {
2883     int timeridx = gt_phys_redir_timeridx(env);
2884     return env->cp15.c14_timer[timeridx].cval;
2885 }
2886 
2887 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2888                                      uint64_t value)
2889 {
2890     int timeridx = gt_phys_redir_timeridx(env);
2891     gt_cval_write(env, ri, timeridx, value);
2892 }
2893 
2894 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2895                                         const ARMCPRegInfo *ri)
2896 {
2897     int timeridx = gt_phys_redir_timeridx(env);
2898     return gt_tval_read(env, ri, timeridx);
2899 }
2900 
2901 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2902                                      uint64_t value)
2903 {
2904     int timeridx = gt_phys_redir_timeridx(env);
2905     gt_tval_write(env, ri, timeridx, value);
2906 }
2907 
2908 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2909                                        const ARMCPRegInfo *ri)
2910 {
2911     int timeridx = gt_phys_redir_timeridx(env);
2912     return env->cp15.c14_timer[timeridx].ctl;
2913 }
2914 
2915 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2916                                     uint64_t value)
2917 {
2918     int timeridx = gt_phys_redir_timeridx(env);
2919     gt_ctl_write(env, ri, timeridx, value);
2920 }
2921 
2922 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2923 {
2924     gt_timer_reset(env, ri, GTIMER_VIRT);
2925 }
2926 
2927 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2928                                uint64_t value)
2929 {
2930     gt_cval_write(env, ri, GTIMER_VIRT, value);
2931 }
2932 
2933 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2934 {
2935     return gt_tval_read(env, ri, GTIMER_VIRT);
2936 }
2937 
2938 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2939                                uint64_t value)
2940 {
2941     gt_tval_write(env, ri, GTIMER_VIRT, value);
2942 }
2943 
2944 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2945                               uint64_t value)
2946 {
2947     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2948 }
2949 
2950 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2951                               uint64_t value)
2952 {
2953     ARMCPU *cpu = env_archcpu(env);
2954 
2955     trace_arm_gt_cntvoff_write(value);
2956     raw_write(env, ri, value);
2957     gt_recalc_timer(cpu, GTIMER_VIRT);
2958 }
2959 
2960 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
2961                                         const ARMCPRegInfo *ri)
2962 {
2963     int timeridx = gt_virt_redir_timeridx(env);
2964     return env->cp15.c14_timer[timeridx].cval;
2965 }
2966 
2967 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2968                                      uint64_t value)
2969 {
2970     int timeridx = gt_virt_redir_timeridx(env);
2971     gt_cval_write(env, ri, timeridx, value);
2972 }
2973 
2974 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
2975                                         const ARMCPRegInfo *ri)
2976 {
2977     int timeridx = gt_virt_redir_timeridx(env);
2978     return gt_tval_read(env, ri, timeridx);
2979 }
2980 
2981 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2982                                      uint64_t value)
2983 {
2984     int timeridx = gt_virt_redir_timeridx(env);
2985     gt_tval_write(env, ri, timeridx, value);
2986 }
2987 
2988 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
2989                                        const ARMCPRegInfo *ri)
2990 {
2991     int timeridx = gt_virt_redir_timeridx(env);
2992     return env->cp15.c14_timer[timeridx].ctl;
2993 }
2994 
2995 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2996                                     uint64_t value)
2997 {
2998     int timeridx = gt_virt_redir_timeridx(env);
2999     gt_ctl_write(env, ri, timeridx, value);
3000 }
3001 
3002 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3003 {
3004     gt_timer_reset(env, ri, GTIMER_HYP);
3005 }
3006 
3007 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3008                               uint64_t value)
3009 {
3010     gt_cval_write(env, ri, GTIMER_HYP, value);
3011 }
3012 
3013 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3014 {
3015     return gt_tval_read(env, ri, GTIMER_HYP);
3016 }
3017 
3018 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3019                               uint64_t value)
3020 {
3021     gt_tval_write(env, ri, GTIMER_HYP, value);
3022 }
3023 
3024 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3025                               uint64_t value)
3026 {
3027     gt_ctl_write(env, ri, GTIMER_HYP, value);
3028 }
3029 
3030 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3031 {
3032     gt_timer_reset(env, ri, GTIMER_SEC);
3033 }
3034 
3035 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3036                               uint64_t value)
3037 {
3038     gt_cval_write(env, ri, GTIMER_SEC, value);
3039 }
3040 
3041 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3042 {
3043     return gt_tval_read(env, ri, GTIMER_SEC);
3044 }
3045 
3046 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3047                               uint64_t value)
3048 {
3049     gt_tval_write(env, ri, GTIMER_SEC, value);
3050 }
3051 
3052 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3053                               uint64_t value)
3054 {
3055     gt_ctl_write(env, ri, GTIMER_SEC, value);
3056 }
3057 
3058 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3059 {
3060     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
3061 }
3062 
3063 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3064                              uint64_t value)
3065 {
3066     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
3067 }
3068 
3069 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3070 {
3071     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
3072 }
3073 
3074 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3075                              uint64_t value)
3076 {
3077     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
3078 }
3079 
3080 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3081                             uint64_t value)
3082 {
3083     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
3084 }
3085 
3086 void arm_gt_ptimer_cb(void *opaque)
3087 {
3088     ARMCPU *cpu = opaque;
3089 
3090     gt_recalc_timer(cpu, GTIMER_PHYS);
3091 }
3092 
3093 void arm_gt_vtimer_cb(void *opaque)
3094 {
3095     ARMCPU *cpu = opaque;
3096 
3097     gt_recalc_timer(cpu, GTIMER_VIRT);
3098 }
3099 
3100 void arm_gt_htimer_cb(void *opaque)
3101 {
3102     ARMCPU *cpu = opaque;
3103 
3104     gt_recalc_timer(cpu, GTIMER_HYP);
3105 }
3106 
3107 void arm_gt_stimer_cb(void *opaque)
3108 {
3109     ARMCPU *cpu = opaque;
3110 
3111     gt_recalc_timer(cpu, GTIMER_SEC);
3112 }
3113 
3114 void arm_gt_hvtimer_cb(void *opaque)
3115 {
3116     ARMCPU *cpu = opaque;
3117 
3118     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
3119 }
3120 
3121 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
3122 {
3123     ARMCPU *cpu = env_archcpu(env);
3124 
3125     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
3126 }
3127 
3128 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3129     /* Note that CNTFRQ is purely reads-as-written for the benefit
3130      * of software; writing it doesn't actually change the timer frequency.
3131      * Our reset value matches the fixed frequency we implement the timer at.
3132      */
3133     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
3134       .type = ARM_CP_ALIAS,
3135       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3136       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
3137     },
3138     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3139       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3140       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3141       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3142       .resetfn = arm_gt_cntfrq_reset,
3143     },
3144     /* overall control: mostly access permissions */
3145     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
3146       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
3147       .access = PL1_RW,
3148       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
3149       .resetvalue = 0,
3150     },
3151     /* per-timer control */
3152     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3153       .secure = ARM_CP_SECSTATE_NS,
3154       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3155       .accessfn = gt_ptimer_access,
3156       .fieldoffset = offsetoflow32(CPUARMState,
3157                                    cp15.c14_timer[GTIMER_PHYS].ctl),
3158       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3159       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3160     },
3161     { .name = "CNTP_CTL_S",
3162       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3163       .secure = ARM_CP_SECSTATE_S,
3164       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3165       .accessfn = gt_ptimer_access,
3166       .fieldoffset = offsetoflow32(CPUARMState,
3167                                    cp15.c14_timer[GTIMER_SEC].ctl),
3168       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3169     },
3170     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
3171       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
3172       .type = ARM_CP_IO, .access = PL0_RW,
3173       .accessfn = gt_ptimer_access,
3174       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
3175       .resetvalue = 0,
3176       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3177       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3178     },
3179     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
3180       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3181       .accessfn = gt_vtimer_access,
3182       .fieldoffset = offsetoflow32(CPUARMState,
3183                                    cp15.c14_timer[GTIMER_VIRT].ctl),
3184       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3185       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3186     },
3187     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
3188       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
3189       .type = ARM_CP_IO, .access = PL0_RW,
3190       .accessfn = gt_vtimer_access,
3191       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
3192       .resetvalue = 0,
3193       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3194       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3195     },
3196     /* TimerValue views: a 32 bit downcounting view of the underlying state */
3197     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3198       .secure = ARM_CP_SECSTATE_NS,
3199       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3200       .accessfn = gt_ptimer_access,
3201       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3202     },
3203     { .name = "CNTP_TVAL_S",
3204       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3205       .secure = ARM_CP_SECSTATE_S,
3206       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3207       .accessfn = gt_ptimer_access,
3208       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
3209     },
3210     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3211       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
3212       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3213       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
3214       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3215     },
3216     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
3217       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3218       .accessfn = gt_vtimer_access,
3219       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3220     },
3221     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3222       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
3223       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3224       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
3225       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3226     },
3227     /* The counter itself */
3228     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
3229       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3230       .accessfn = gt_pct_access,
3231       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
3232     },
3233     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
3234       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
3235       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3236       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
3237     },
3238     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3239       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3240       .accessfn = gt_vct_access,
3241       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3242     },
3243     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3244       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3245       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3246       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3247     },
3248     /* Comparison value, indicating when the timer goes off */
3249     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3250       .secure = ARM_CP_SECSTATE_NS,
3251       .access = PL0_RW,
3252       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3253       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3254       .accessfn = gt_ptimer_access,
3255       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3256       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3257     },
3258     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3259       .secure = ARM_CP_SECSTATE_S,
3260       .access = PL0_RW,
3261       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3262       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3263       .accessfn = gt_ptimer_access,
3264       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3265     },
3266     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3267       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3268       .access = PL0_RW,
3269       .type = ARM_CP_IO,
3270       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3271       .resetvalue = 0, .accessfn = gt_ptimer_access,
3272       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3273       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3274     },
3275     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3276       .access = PL0_RW,
3277       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3278       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3279       .accessfn = gt_vtimer_access,
3280       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3281       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3282     },
3283     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3284       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3285       .access = PL0_RW,
3286       .type = ARM_CP_IO,
3287       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3288       .resetvalue = 0, .accessfn = gt_vtimer_access,
3289       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3290       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3291     },
3292     /* Secure timer -- this is actually restricted to only EL3
3293      * and configurably Secure-EL1 via the accessfn.
3294      */
3295     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3296       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3297       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3298       .accessfn = gt_stimer_access,
3299       .readfn = gt_sec_tval_read,
3300       .writefn = gt_sec_tval_write,
3301       .resetfn = gt_sec_timer_reset,
3302     },
3303     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3304       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3305       .type = ARM_CP_IO, .access = PL1_RW,
3306       .accessfn = gt_stimer_access,
3307       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3308       .resetvalue = 0,
3309       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3310     },
3311     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3312       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3313       .type = ARM_CP_IO, .access = PL1_RW,
3314       .accessfn = gt_stimer_access,
3315       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3316       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3317     },
3318     REGINFO_SENTINEL
3319 };
3320 
3321 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3322                                  bool isread)
3323 {
3324     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3325         return CP_ACCESS_TRAP;
3326     }
3327     return CP_ACCESS_OK;
3328 }
3329 
3330 #else
3331 
3332 /* In user-mode most of the generic timer registers are inaccessible
3333  * however modern kernels (4.12+) allow access to cntvct_el0
3334  */
3335 
3336 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3337 {
3338     ARMCPU *cpu = env_archcpu(env);
3339 
3340     /* Currently we have no support for QEMUTimer in linux-user so we
3341      * can't call gt_get_countervalue(env), instead we directly
3342      * call the lower level functions.
3343      */
3344     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3345 }
3346 
3347 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3348     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3349       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3350       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3351       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3352       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3353     },
3354     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3355       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3356       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3357       .readfn = gt_virt_cnt_read,
3358     },
3359     REGINFO_SENTINEL
3360 };
3361 
3362 #endif
3363 
3364 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3365 {
3366     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3367         raw_write(env, ri, value);
3368     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3369         raw_write(env, ri, value & 0xfffff6ff);
3370     } else {
3371         raw_write(env, ri, value & 0xfffff1ff);
3372     }
3373 }
3374 
3375 #ifndef CONFIG_USER_ONLY
3376 /* get_phys_addr() isn't present for user-mode-only targets */
3377 
3378 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3379                                  bool isread)
3380 {
3381     if (ri->opc2 & 4) {
3382         /* The ATS12NSO* operations must trap to EL3 if executed in
3383          * Secure EL1 (which can only happen if EL3 is AArch64).
3384          * They are simply UNDEF if executed from NS EL1.
3385          * They function normally from EL2 or EL3.
3386          */
3387         if (arm_current_el(env) == 1) {
3388             if (arm_is_secure_below_el3(env)) {
3389                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3390             }
3391             return CP_ACCESS_TRAP_UNCATEGORIZED;
3392         }
3393     }
3394     return CP_ACCESS_OK;
3395 }
3396 
3397 #ifdef CONFIG_TCG
3398 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3399                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3400 {
3401     hwaddr phys_addr;
3402     target_ulong page_size;
3403     int prot;
3404     bool ret;
3405     uint64_t par64;
3406     bool format64 = false;
3407     MemTxAttrs attrs = {};
3408     ARMMMUFaultInfo fi = {};
3409     ARMCacheAttrs cacheattrs = {};
3410 
3411     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3412                         &prot, &page_size, &fi, &cacheattrs);
3413 
3414     if (ret) {
3415         /*
3416          * Some kinds of translation fault must cause exceptions rather
3417          * than being reported in the PAR.
3418          */
3419         int current_el = arm_current_el(env);
3420         int target_el;
3421         uint32_t syn, fsr, fsc;
3422         bool take_exc = false;
3423 
3424         if (fi.s1ptw && current_el == 1 && !arm_is_secure(env)
3425             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3426             /*
3427              * Synchronous stage 2 fault on an access made as part of the
3428              * translation table walk for AT S1E0* or AT S1E1* insn
3429              * executed from NS EL1. If this is a synchronous external abort
3430              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3431              * to EL3. Otherwise the fault is taken as an exception to EL2,
3432              * and HPFAR_EL2 holds the faulting IPA.
3433              */
3434             if (fi.type == ARMFault_SyncExternalOnWalk &&
3435                 (env->cp15.scr_el3 & SCR_EA)) {
3436                 target_el = 3;
3437             } else {
3438                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3439                 target_el = 2;
3440             }
3441             take_exc = true;
3442         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3443             /*
3444              * Synchronous external aborts during a translation table walk
3445              * are taken as Data Abort exceptions.
3446              */
3447             if (fi.stage2) {
3448                 if (current_el == 3) {
3449                     target_el = 3;
3450                 } else {
3451                     target_el = 2;
3452                 }
3453             } else {
3454                 target_el = exception_target_el(env);
3455             }
3456             take_exc = true;
3457         }
3458 
3459         if (take_exc) {
3460             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3461             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3462                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3463                 fsr = arm_fi_to_lfsc(&fi);
3464                 fsc = extract32(fsr, 0, 6);
3465             } else {
3466                 fsr = arm_fi_to_sfsc(&fi);
3467                 fsc = 0x3f;
3468             }
3469             /*
3470              * Report exception with ESR indicating a fault due to a
3471              * translation table walk for a cache maintenance instruction.
3472              */
3473             syn = syn_data_abort_no_iss(current_el == target_el, 0,
3474                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3475             env->exception.vaddress = value;
3476             env->exception.fsr = fsr;
3477             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3478         }
3479     }
3480 
3481     if (is_a64(env)) {
3482         format64 = true;
3483     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3484         /*
3485          * ATS1Cxx:
3486          * * TTBCR.EAE determines whether the result is returned using the
3487          *   32-bit or the 64-bit PAR format
3488          * * Instructions executed in Hyp mode always use the 64bit format
3489          *
3490          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3491          * * The Non-secure TTBCR.EAE bit is set to 1
3492          * * The implementation includes EL2, and the value of HCR.VM is 1
3493          *
3494          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3495          *
3496          * ATS1Hx always uses the 64bit format.
3497          */
3498         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3499 
3500         if (arm_feature(env, ARM_FEATURE_EL2)) {
3501             if (mmu_idx == ARMMMUIdx_E10_0 ||
3502                 mmu_idx == ARMMMUIdx_E10_1 ||
3503                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3504                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3505             } else {
3506                 format64 |= arm_current_el(env) == 2;
3507             }
3508         }
3509     }
3510 
3511     if (format64) {
3512         /* Create a 64-bit PAR */
3513         par64 = (1 << 11); /* LPAE bit always set */
3514         if (!ret) {
3515             par64 |= phys_addr & ~0xfffULL;
3516             if (!attrs.secure) {
3517                 par64 |= (1 << 9); /* NS */
3518             }
3519             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3520             par64 |= cacheattrs.shareability << 7; /* SH */
3521         } else {
3522             uint32_t fsr = arm_fi_to_lfsc(&fi);
3523 
3524             par64 |= 1; /* F */
3525             par64 |= (fsr & 0x3f) << 1; /* FS */
3526             if (fi.stage2) {
3527                 par64 |= (1 << 9); /* S */
3528             }
3529             if (fi.s1ptw) {
3530                 par64 |= (1 << 8); /* PTW */
3531             }
3532         }
3533     } else {
3534         /* fsr is a DFSR/IFSR value for the short descriptor
3535          * translation table format (with WnR always clear).
3536          * Convert it to a 32-bit PAR.
3537          */
3538         if (!ret) {
3539             /* We do not set any attribute bits in the PAR */
3540             if (page_size == (1 << 24)
3541                 && arm_feature(env, ARM_FEATURE_V7)) {
3542                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3543             } else {
3544                 par64 = phys_addr & 0xfffff000;
3545             }
3546             if (!attrs.secure) {
3547                 par64 |= (1 << 9); /* NS */
3548             }
3549         } else {
3550             uint32_t fsr = arm_fi_to_sfsc(&fi);
3551 
3552             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3553                     ((fsr & 0xf) << 1) | 1;
3554         }
3555     }
3556     return par64;
3557 }
3558 #endif /* CONFIG_TCG */
3559 
3560 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3561 {
3562 #ifdef CONFIG_TCG
3563     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3564     uint64_t par64;
3565     ARMMMUIdx mmu_idx;
3566     int el = arm_current_el(env);
3567     bool secure = arm_is_secure_below_el3(env);
3568 
3569     switch (ri->opc2 & 6) {
3570     case 0:
3571         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3572         switch (el) {
3573         case 3:
3574             mmu_idx = ARMMMUIdx_SE3;
3575             break;
3576         case 2:
3577             g_assert(!secure);  /* TODO: ARMv8.4-SecEL2 */
3578             /* fall through */
3579         case 1:
3580             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3581                 mmu_idx = (secure ? ARMMMUIdx_SE10_1_PAN
3582                            : ARMMMUIdx_Stage1_E1_PAN);
3583             } else {
3584                 mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_Stage1_E1;
3585             }
3586             break;
3587         default:
3588             g_assert_not_reached();
3589         }
3590         break;
3591     case 2:
3592         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3593         switch (el) {
3594         case 3:
3595             mmu_idx = ARMMMUIdx_SE10_0;
3596             break;
3597         case 2:
3598             mmu_idx = ARMMMUIdx_Stage1_E0;
3599             break;
3600         case 1:
3601             mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_Stage1_E0;
3602             break;
3603         default:
3604             g_assert_not_reached();
3605         }
3606         break;
3607     case 4:
3608         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3609         mmu_idx = ARMMMUIdx_E10_1;
3610         break;
3611     case 6:
3612         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3613         mmu_idx = ARMMMUIdx_E10_0;
3614         break;
3615     default:
3616         g_assert_not_reached();
3617     }
3618 
3619     par64 = do_ats_write(env, value, access_type, mmu_idx);
3620 
3621     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3622 #else
3623     /* Handled by hardware accelerator. */
3624     g_assert_not_reached();
3625 #endif /* CONFIG_TCG */
3626 }
3627 
3628 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3629                         uint64_t value)
3630 {
3631 #ifdef CONFIG_TCG
3632     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3633     uint64_t par64;
3634 
3635     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3636 
3637     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3638 #else
3639     /* Handled by hardware accelerator. */
3640     g_assert_not_reached();
3641 #endif /* CONFIG_TCG */
3642 }
3643 
3644 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3645                                      bool isread)
3646 {
3647     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
3648         return CP_ACCESS_TRAP;
3649     }
3650     return CP_ACCESS_OK;
3651 }
3652 
3653 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3654                         uint64_t value)
3655 {
3656 #ifdef CONFIG_TCG
3657     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3658     ARMMMUIdx mmu_idx;
3659     int secure = arm_is_secure_below_el3(env);
3660 
3661     switch (ri->opc2 & 6) {
3662     case 0:
3663         switch (ri->opc1) {
3664         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3665             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3666                 mmu_idx = (secure ? ARMMMUIdx_SE10_1_PAN
3667                            : ARMMMUIdx_Stage1_E1_PAN);
3668             } else {
3669                 mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_Stage1_E1;
3670             }
3671             break;
3672         case 4: /* AT S1E2R, AT S1E2W */
3673             mmu_idx = ARMMMUIdx_E2;
3674             break;
3675         case 6: /* AT S1E3R, AT S1E3W */
3676             mmu_idx = ARMMMUIdx_SE3;
3677             break;
3678         default:
3679             g_assert_not_reached();
3680         }
3681         break;
3682     case 2: /* AT S1E0R, AT S1E0W */
3683         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_Stage1_E0;
3684         break;
3685     case 4: /* AT S12E1R, AT S12E1W */
3686         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3687         break;
3688     case 6: /* AT S12E0R, AT S12E0W */
3689         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3690         break;
3691     default:
3692         g_assert_not_reached();
3693     }
3694 
3695     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3696 #else
3697     /* Handled by hardware accelerator. */
3698     g_assert_not_reached();
3699 #endif /* CONFIG_TCG */
3700 }
3701 #endif
3702 
3703 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3704     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3705       .access = PL1_RW, .resetvalue = 0,
3706       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3707                              offsetoflow32(CPUARMState, cp15.par_ns) },
3708       .writefn = par_write },
3709 #ifndef CONFIG_USER_ONLY
3710     /* This underdecoding is safe because the reginfo is NO_RAW. */
3711     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3712       .access = PL1_W, .accessfn = ats_access,
3713       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3714 #endif
3715     REGINFO_SENTINEL
3716 };
3717 
3718 /* Return basic MPU access permission bits.  */
3719 static uint32_t simple_mpu_ap_bits(uint32_t val)
3720 {
3721     uint32_t ret;
3722     uint32_t mask;
3723     int i;
3724     ret = 0;
3725     mask = 3;
3726     for (i = 0; i < 16; i += 2) {
3727         ret |= (val >> i) & mask;
3728         mask <<= 2;
3729     }
3730     return ret;
3731 }
3732 
3733 /* Pad basic MPU access permission bits to extended format.  */
3734 static uint32_t extended_mpu_ap_bits(uint32_t val)
3735 {
3736     uint32_t ret;
3737     uint32_t mask;
3738     int i;
3739     ret = 0;
3740     mask = 3;
3741     for (i = 0; i < 16; i += 2) {
3742         ret |= (val & mask) << i;
3743         mask <<= 2;
3744     }
3745     return ret;
3746 }
3747 
3748 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3749                                  uint64_t value)
3750 {
3751     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3752 }
3753 
3754 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3755 {
3756     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3757 }
3758 
3759 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3760                                  uint64_t value)
3761 {
3762     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3763 }
3764 
3765 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3766 {
3767     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3768 }
3769 
3770 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3771 {
3772     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3773 
3774     if (!u32p) {
3775         return 0;
3776     }
3777 
3778     u32p += env->pmsav7.rnr[M_REG_NS];
3779     return *u32p;
3780 }
3781 
3782 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3783                          uint64_t value)
3784 {
3785     ARMCPU *cpu = env_archcpu(env);
3786     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3787 
3788     if (!u32p) {
3789         return;
3790     }
3791 
3792     u32p += env->pmsav7.rnr[M_REG_NS];
3793     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3794     *u32p = value;
3795 }
3796 
3797 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3798                               uint64_t value)
3799 {
3800     ARMCPU *cpu = env_archcpu(env);
3801     uint32_t nrgs = cpu->pmsav7_dregion;
3802 
3803     if (value >= nrgs) {
3804         qemu_log_mask(LOG_GUEST_ERROR,
3805                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3806                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3807         return;
3808     }
3809 
3810     raw_write(env, ri, value);
3811 }
3812 
3813 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3814     /* Reset for all these registers is handled in arm_cpu_reset(),
3815      * because the PMSAv7 is also used by M-profile CPUs, which do
3816      * not register cpregs but still need the state to be reset.
3817      */
3818     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3819       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3820       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3821       .readfn = pmsav7_read, .writefn = pmsav7_write,
3822       .resetfn = arm_cp_reset_ignore },
3823     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3824       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3825       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3826       .readfn = pmsav7_read, .writefn = pmsav7_write,
3827       .resetfn = arm_cp_reset_ignore },
3828     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3829       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3830       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3831       .readfn = pmsav7_read, .writefn = pmsav7_write,
3832       .resetfn = arm_cp_reset_ignore },
3833     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3834       .access = PL1_RW,
3835       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3836       .writefn = pmsav7_rgnr_write,
3837       .resetfn = arm_cp_reset_ignore },
3838     REGINFO_SENTINEL
3839 };
3840 
3841 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3842     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3843       .access = PL1_RW, .type = ARM_CP_ALIAS,
3844       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3845       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3846     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3847       .access = PL1_RW, .type = ARM_CP_ALIAS,
3848       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3849       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3850     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3851       .access = PL1_RW,
3852       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3853       .resetvalue = 0, },
3854     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3855       .access = PL1_RW,
3856       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3857       .resetvalue = 0, },
3858     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3859       .access = PL1_RW,
3860       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3861     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3862       .access = PL1_RW,
3863       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3864     /* Protection region base and size registers */
3865     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3866       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3867       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3868     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3869       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3870       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3871     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3872       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3873       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3874     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3875       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3876       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3877     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3878       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3879       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3880     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3881       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3882       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3883     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3884       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3885       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3886     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3887       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3888       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3889     REGINFO_SENTINEL
3890 };
3891 
3892 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3893                                  uint64_t value)
3894 {
3895     TCR *tcr = raw_ptr(env, ri);
3896     int maskshift = extract32(value, 0, 3);
3897 
3898     if (!arm_feature(env, ARM_FEATURE_V8)) {
3899         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3900             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3901              * using Long-desciptor translation table format */
3902             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3903         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3904             /* In an implementation that includes the Security Extensions
3905              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3906              * Short-descriptor translation table format.
3907              */
3908             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3909         } else {
3910             value &= TTBCR_N;
3911         }
3912     }
3913 
3914     /* Update the masks corresponding to the TCR bank being written
3915      * Note that we always calculate mask and base_mask, but
3916      * they are only used for short-descriptor tables (ie if EAE is 0);
3917      * for long-descriptor tables the TCR fields are used differently
3918      * and the mask and base_mask values are meaningless.
3919      */
3920     tcr->raw_tcr = value;
3921     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3922     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3923 }
3924 
3925 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3926                              uint64_t value)
3927 {
3928     ARMCPU *cpu = env_archcpu(env);
3929     TCR *tcr = raw_ptr(env, ri);
3930 
3931     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3932         /* With LPAE the TTBCR could result in a change of ASID
3933          * via the TTBCR.A1 bit, so do a TLB flush.
3934          */
3935         tlb_flush(CPU(cpu));
3936     }
3937     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3938     value = deposit64(tcr->raw_tcr, 0, 32, value);
3939     vmsa_ttbcr_raw_write(env, ri, value);
3940 }
3941 
3942 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3943 {
3944     TCR *tcr = raw_ptr(env, ri);
3945 
3946     /* Reset both the TCR as well as the masks corresponding to the bank of
3947      * the TCR being reset.
3948      */
3949     tcr->raw_tcr = 0;
3950     tcr->mask = 0;
3951     tcr->base_mask = 0xffffc000u;
3952 }
3953 
3954 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3955                                uint64_t value)
3956 {
3957     ARMCPU *cpu = env_archcpu(env);
3958     TCR *tcr = raw_ptr(env, ri);
3959 
3960     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3961     tlb_flush(CPU(cpu));
3962     tcr->raw_tcr = value;
3963 }
3964 
3965 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3966                             uint64_t value)
3967 {
3968     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3969     if (cpreg_field_is_64bit(ri) &&
3970         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3971         ARMCPU *cpu = env_archcpu(env);
3972         tlb_flush(CPU(cpu));
3973     }
3974     raw_write(env, ri, value);
3975 }
3976 
3977 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3978                                     uint64_t value)
3979 {
3980     /*
3981      * If we are running with E2&0 regime, then an ASID is active.
3982      * Flush if that might be changing.  Note we're not checking
3983      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
3984      * holds the active ASID, only checking the field that might.
3985      */
3986     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
3987         (arm_hcr_el2_eff(env) & HCR_E2H)) {
3988         tlb_flush_by_mmuidx(env_cpu(env),
3989                             ARMMMUIdxBit_E20_2 |
3990                             ARMMMUIdxBit_E20_2_PAN |
3991                             ARMMMUIdxBit_E20_0);
3992     }
3993     raw_write(env, ri, value);
3994 }
3995 
3996 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3997                         uint64_t value)
3998 {
3999     ARMCPU *cpu = env_archcpu(env);
4000     CPUState *cs = CPU(cpu);
4001 
4002     /*
4003      * A change in VMID to the stage2 page table (Stage2) invalidates
4004      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
4005      */
4006     if (raw_read(env, ri) != value) {
4007         tlb_flush_by_mmuidx(cs,
4008                             ARMMMUIdxBit_E10_1 |
4009                             ARMMMUIdxBit_E10_1_PAN |
4010                             ARMMMUIdxBit_E10_0);
4011         raw_write(env, ri, value);
4012     }
4013 }
4014 
4015 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
4016     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
4017       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
4018       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
4019                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
4020     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
4021       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4022       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
4023                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
4024     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
4025       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4026       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
4027                              offsetof(CPUARMState, cp15.dfar_ns) } },
4028     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
4029       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
4030       .access = PL1_RW, .accessfn = access_tvm_trvm,
4031       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
4032       .resetvalue = 0, },
4033     REGINFO_SENTINEL
4034 };
4035 
4036 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
4037     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
4038       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
4039       .access = PL1_RW, .accessfn = access_tvm_trvm,
4040       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
4041     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
4042       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
4043       .access = PL1_RW, .accessfn = access_tvm_trvm,
4044       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4045       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4046                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
4047     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
4048       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
4049       .access = PL1_RW, .accessfn = access_tvm_trvm,
4050       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4051       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4052                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
4053     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
4054       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4055       .access = PL1_RW, .accessfn = access_tvm_trvm,
4056       .writefn = vmsa_tcr_el12_write,
4057       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
4058       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
4059     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4060       .access = PL1_RW, .accessfn = access_tvm_trvm,
4061       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
4062       .raw_writefn = vmsa_ttbcr_raw_write,
4063       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
4064                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
4065     REGINFO_SENTINEL
4066 };
4067 
4068 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
4069  * qemu tlbs nor adjusting cached masks.
4070  */
4071 static const ARMCPRegInfo ttbcr2_reginfo = {
4072     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
4073     .access = PL1_RW, .accessfn = access_tvm_trvm,
4074     .type = ARM_CP_ALIAS,
4075     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
4076                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
4077 };
4078 
4079 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
4080                                 uint64_t value)
4081 {
4082     env->cp15.c15_ticonfig = value & 0xe7;
4083     /* The OS_TYPE bit in this register changes the reported CPUID! */
4084     env->cp15.c0_cpuid = (value & (1 << 5)) ?
4085         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
4086 }
4087 
4088 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
4089                                 uint64_t value)
4090 {
4091     env->cp15.c15_threadid = value & 0xffff;
4092 }
4093 
4094 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
4095                            uint64_t value)
4096 {
4097     /* Wait-for-interrupt (deprecated) */
4098     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
4099 }
4100 
4101 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
4102                                   uint64_t value)
4103 {
4104     /* On OMAP there are registers indicating the max/min index of dcache lines
4105      * containing a dirty line; cache flush operations have to reset these.
4106      */
4107     env->cp15.c15_i_max = 0x000;
4108     env->cp15.c15_i_min = 0xff0;
4109 }
4110 
4111 static const ARMCPRegInfo omap_cp_reginfo[] = {
4112     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
4113       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
4114       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
4115       .resetvalue = 0, },
4116     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
4117       .access = PL1_RW, .type = ARM_CP_NOP },
4118     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
4119       .access = PL1_RW,
4120       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
4121       .writefn = omap_ticonfig_write },
4122     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
4123       .access = PL1_RW,
4124       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
4125     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
4126       .access = PL1_RW, .resetvalue = 0xff0,
4127       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
4128     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
4129       .access = PL1_RW,
4130       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
4131       .writefn = omap_threadid_write },
4132     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
4133       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4134       .type = ARM_CP_NO_RAW,
4135       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
4136     /* TODO: Peripheral port remap register:
4137      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
4138      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
4139      * when MMU is off.
4140      */
4141     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
4142       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
4143       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
4144       .writefn = omap_cachemaint_write },
4145     { .name = "C9", .cp = 15, .crn = 9,
4146       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
4147       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
4148     REGINFO_SENTINEL
4149 };
4150 
4151 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4152                               uint64_t value)
4153 {
4154     env->cp15.c15_cpar = value & 0x3fff;
4155 }
4156 
4157 static const ARMCPRegInfo xscale_cp_reginfo[] = {
4158     { .name = "XSCALE_CPAR",
4159       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4160       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
4161       .writefn = xscale_cpar_write, },
4162     { .name = "XSCALE_AUXCR",
4163       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
4164       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
4165       .resetvalue = 0, },
4166     /* XScale specific cache-lockdown: since we have no cache we NOP these
4167      * and hope the guest does not really rely on cache behaviour.
4168      */
4169     { .name = "XSCALE_LOCK_ICACHE_LINE",
4170       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
4171       .access = PL1_W, .type = ARM_CP_NOP },
4172     { .name = "XSCALE_UNLOCK_ICACHE",
4173       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
4174       .access = PL1_W, .type = ARM_CP_NOP },
4175     { .name = "XSCALE_DCACHE_LOCK",
4176       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
4177       .access = PL1_RW, .type = ARM_CP_NOP },
4178     { .name = "XSCALE_UNLOCK_DCACHE",
4179       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
4180       .access = PL1_W, .type = ARM_CP_NOP },
4181     REGINFO_SENTINEL
4182 };
4183 
4184 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
4185     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
4186      * implementation of this implementation-defined space.
4187      * Ideally this should eventually disappear in favour of actually
4188      * implementing the correct behaviour for all cores.
4189      */
4190     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
4191       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4192       .access = PL1_RW,
4193       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
4194       .resetvalue = 0 },
4195     REGINFO_SENTINEL
4196 };
4197 
4198 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
4199     /* Cache status: RAZ because we have no cache so it's always clean */
4200     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
4201       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4202       .resetvalue = 0 },
4203     REGINFO_SENTINEL
4204 };
4205 
4206 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
4207     /* We never have a a block transfer operation in progress */
4208     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
4209       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4210       .resetvalue = 0 },
4211     /* The cache ops themselves: these all NOP for QEMU */
4212     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
4213       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4214     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
4215       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4216     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
4217       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4218     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4219       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4220     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4221       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4222     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4223       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4224     REGINFO_SENTINEL
4225 };
4226 
4227 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4228     /* The cache test-and-clean instructions always return (1 << 30)
4229      * to indicate that there are no dirty cache lines.
4230      */
4231     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4232       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4233       .resetvalue = (1 << 30) },
4234     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4235       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4236       .resetvalue = (1 << 30) },
4237     REGINFO_SENTINEL
4238 };
4239 
4240 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4241     /* Ignore ReadBuffer accesses */
4242     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4243       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4244       .access = PL1_RW, .resetvalue = 0,
4245       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4246     REGINFO_SENTINEL
4247 };
4248 
4249 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4250 {
4251     ARMCPU *cpu = env_archcpu(env);
4252     unsigned int cur_el = arm_current_el(env);
4253     bool secure = arm_is_secure(env);
4254 
4255     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
4256         return env->cp15.vpidr_el2;
4257     }
4258     return raw_read(env, ri);
4259 }
4260 
4261 static uint64_t mpidr_read_val(CPUARMState *env)
4262 {
4263     ARMCPU *cpu = env_archcpu(env);
4264     uint64_t mpidr = cpu->mp_affinity;
4265 
4266     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4267         mpidr |= (1U << 31);
4268         /* Cores which are uniprocessor (non-coherent)
4269          * but still implement the MP extensions set
4270          * bit 30. (For instance, Cortex-R5).
4271          */
4272         if (cpu->mp_is_up) {
4273             mpidr |= (1u << 30);
4274         }
4275     }
4276     return mpidr;
4277 }
4278 
4279 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4280 {
4281     unsigned int cur_el = arm_current_el(env);
4282     bool secure = arm_is_secure(env);
4283 
4284     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
4285         return env->cp15.vmpidr_el2;
4286     }
4287     return mpidr_read_val(env);
4288 }
4289 
4290 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4291     /* NOP AMAIR0/1 */
4292     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4293       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4294       .access = PL1_RW, .accessfn = access_tvm_trvm,
4295       .type = ARM_CP_CONST, .resetvalue = 0 },
4296     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4297     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4298       .access = PL1_RW, .accessfn = access_tvm_trvm,
4299       .type = ARM_CP_CONST, .resetvalue = 0 },
4300     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4301       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4302       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4303                              offsetof(CPUARMState, cp15.par_ns)} },
4304     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4305       .access = PL1_RW, .accessfn = access_tvm_trvm,
4306       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4307       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4308                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4309       .writefn = vmsa_ttbr_write, },
4310     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4311       .access = PL1_RW, .accessfn = access_tvm_trvm,
4312       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4313       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4314                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4315       .writefn = vmsa_ttbr_write, },
4316     REGINFO_SENTINEL
4317 };
4318 
4319 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4320 {
4321     return vfp_get_fpcr(env);
4322 }
4323 
4324 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4325                             uint64_t value)
4326 {
4327     vfp_set_fpcr(env, value);
4328 }
4329 
4330 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4331 {
4332     return vfp_get_fpsr(env);
4333 }
4334 
4335 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4336                             uint64_t value)
4337 {
4338     vfp_set_fpsr(env, value);
4339 }
4340 
4341 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4342                                        bool isread)
4343 {
4344     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4345         return CP_ACCESS_TRAP;
4346     }
4347     return CP_ACCESS_OK;
4348 }
4349 
4350 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4351                             uint64_t value)
4352 {
4353     env->daif = value & PSTATE_DAIF;
4354 }
4355 
4356 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4357 {
4358     return env->pstate & PSTATE_PAN;
4359 }
4360 
4361 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4362                            uint64_t value)
4363 {
4364     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4365 }
4366 
4367 static const ARMCPRegInfo pan_reginfo = {
4368     .name = "PAN", .state = ARM_CP_STATE_AA64,
4369     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4370     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4371     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4372 };
4373 
4374 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4375 {
4376     return env->pstate & PSTATE_UAO;
4377 }
4378 
4379 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4380                            uint64_t value)
4381 {
4382     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4383 }
4384 
4385 static const ARMCPRegInfo uao_reginfo = {
4386     .name = "UAO", .state = ARM_CP_STATE_AA64,
4387     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4388     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4389     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4390 };
4391 
4392 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4393                                               const ARMCPRegInfo *ri,
4394                                               bool isread)
4395 {
4396     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4397     switch (arm_current_el(env)) {
4398     case 0:
4399         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4400         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4401             return CP_ACCESS_TRAP;
4402         }
4403         /* fall through */
4404     case 1:
4405         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4406         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4407             return CP_ACCESS_TRAP_EL2;
4408         }
4409         break;
4410     }
4411     return CP_ACCESS_OK;
4412 }
4413 
4414 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4415                                               const ARMCPRegInfo *ri,
4416                                               bool isread)
4417 {
4418     /* Cache invalidate/clean to Point of Unification... */
4419     switch (arm_current_el(env)) {
4420     case 0:
4421         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4422         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4423             return CP_ACCESS_TRAP;
4424         }
4425         /* fall through */
4426     case 1:
4427         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4428         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4429             return CP_ACCESS_TRAP_EL2;
4430         }
4431         break;
4432     }
4433     return CP_ACCESS_OK;
4434 }
4435 
4436 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4437  * Page D4-1736 (DDI0487A.b)
4438  */
4439 
4440 static int vae1_tlbmask(CPUARMState *env)
4441 {
4442     /* Since we exclude secure first, we may read HCR_EL2 directly. */
4443     if (arm_is_secure_below_el3(env)) {
4444         return ARMMMUIdxBit_SE10_1 |
4445                ARMMMUIdxBit_SE10_1_PAN |
4446                ARMMMUIdxBit_SE10_0;
4447     } else if ((env->cp15.hcr_el2 & (HCR_E2H | HCR_TGE))
4448                == (HCR_E2H | HCR_TGE)) {
4449         return ARMMMUIdxBit_E20_2 |
4450                ARMMMUIdxBit_E20_2_PAN |
4451                ARMMMUIdxBit_E20_0;
4452     } else {
4453         return ARMMMUIdxBit_E10_1 |
4454                ARMMMUIdxBit_E10_1_PAN |
4455                ARMMMUIdxBit_E10_0;
4456     }
4457 }
4458 
4459 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4460                                       uint64_t value)
4461 {
4462     CPUState *cs = env_cpu(env);
4463     int mask = vae1_tlbmask(env);
4464 
4465     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4466 }
4467 
4468 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4469                                     uint64_t value)
4470 {
4471     CPUState *cs = env_cpu(env);
4472     int mask = vae1_tlbmask(env);
4473 
4474     if (tlb_force_broadcast(env)) {
4475         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4476     } else {
4477         tlb_flush_by_mmuidx(cs, mask);
4478     }
4479 }
4480 
4481 static int alle1_tlbmask(CPUARMState *env)
4482 {
4483     /*
4484      * Note that the 'ALL' scope must invalidate both stage 1 and
4485      * stage 2 translations, whereas most other scopes only invalidate
4486      * stage 1 translations.
4487      */
4488     if (arm_is_secure_below_el3(env)) {
4489         return ARMMMUIdxBit_SE10_1 |
4490                ARMMMUIdxBit_SE10_1_PAN |
4491                ARMMMUIdxBit_SE10_0;
4492     } else {
4493         return ARMMMUIdxBit_E10_1 |
4494                ARMMMUIdxBit_E10_1_PAN |
4495                ARMMMUIdxBit_E10_0;
4496     }
4497 }
4498 
4499 static int e2_tlbmask(CPUARMState *env)
4500 {
4501     /* TODO: ARMv8.4-SecEL2 */
4502     return ARMMMUIdxBit_E20_0 |
4503            ARMMMUIdxBit_E20_2 |
4504            ARMMMUIdxBit_E20_2_PAN |
4505            ARMMMUIdxBit_E2;
4506 }
4507 
4508 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4509                                   uint64_t value)
4510 {
4511     CPUState *cs = env_cpu(env);
4512     int mask = alle1_tlbmask(env);
4513 
4514     tlb_flush_by_mmuidx(cs, mask);
4515 }
4516 
4517 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4518                                   uint64_t value)
4519 {
4520     CPUState *cs = env_cpu(env);
4521     int mask = e2_tlbmask(env);
4522 
4523     tlb_flush_by_mmuidx(cs, mask);
4524 }
4525 
4526 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4527                                   uint64_t value)
4528 {
4529     ARMCPU *cpu = env_archcpu(env);
4530     CPUState *cs = CPU(cpu);
4531 
4532     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4533 }
4534 
4535 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4536                                     uint64_t value)
4537 {
4538     CPUState *cs = env_cpu(env);
4539     int mask = alle1_tlbmask(env);
4540 
4541     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4542 }
4543 
4544 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4545                                     uint64_t value)
4546 {
4547     CPUState *cs = env_cpu(env);
4548     int mask = e2_tlbmask(env);
4549 
4550     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4551 }
4552 
4553 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4554                                     uint64_t value)
4555 {
4556     CPUState *cs = env_cpu(env);
4557 
4558     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4559 }
4560 
4561 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4562                                  uint64_t value)
4563 {
4564     /* Invalidate by VA, EL2
4565      * Currently handles both VAE2 and VALE2, since we don't support
4566      * flush-last-level-only.
4567      */
4568     CPUState *cs = env_cpu(env);
4569     int mask = e2_tlbmask(env);
4570     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4571 
4572     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4573 }
4574 
4575 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4576                                  uint64_t value)
4577 {
4578     /* Invalidate by VA, EL3
4579      * Currently handles both VAE3 and VALE3, since we don't support
4580      * flush-last-level-only.
4581      */
4582     ARMCPU *cpu = env_archcpu(env);
4583     CPUState *cs = CPU(cpu);
4584     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4585 
4586     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4587 }
4588 
4589 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4590                                    uint64_t value)
4591 {
4592     CPUState *cs = env_cpu(env);
4593     int mask = vae1_tlbmask(env);
4594     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4595 
4596     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr, mask);
4597 }
4598 
4599 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4600                                  uint64_t value)
4601 {
4602     /* Invalidate by VA, EL1&0 (AArch64 version).
4603      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4604      * since we don't support flush-for-specific-ASID-only or
4605      * flush-last-level-only.
4606      */
4607     CPUState *cs = env_cpu(env);
4608     int mask = vae1_tlbmask(env);
4609     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4610 
4611     if (tlb_force_broadcast(env)) {
4612         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr, mask);
4613     } else {
4614         tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4615     }
4616 }
4617 
4618 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4619                                    uint64_t value)
4620 {
4621     CPUState *cs = env_cpu(env);
4622     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4623 
4624     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4625                                              ARMMMUIdxBit_E2);
4626 }
4627 
4628 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4629                                    uint64_t value)
4630 {
4631     CPUState *cs = env_cpu(env);
4632     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4633 
4634     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4635                                              ARMMMUIdxBit_SE3);
4636 }
4637 
4638 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4639                                       bool isread)
4640 {
4641     int cur_el = arm_current_el(env);
4642 
4643     if (cur_el < 2) {
4644         uint64_t hcr = arm_hcr_el2_eff(env);
4645 
4646         if (cur_el == 0) {
4647             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4648                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4649                     return CP_ACCESS_TRAP_EL2;
4650                 }
4651             } else {
4652                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4653                     return CP_ACCESS_TRAP;
4654                 }
4655                 if (hcr & HCR_TDZ) {
4656                     return CP_ACCESS_TRAP_EL2;
4657                 }
4658             }
4659         } else if (hcr & HCR_TDZ) {
4660             return CP_ACCESS_TRAP_EL2;
4661         }
4662     }
4663     return CP_ACCESS_OK;
4664 }
4665 
4666 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4667 {
4668     ARMCPU *cpu = env_archcpu(env);
4669     int dzp_bit = 1 << 4;
4670 
4671     /* DZP indicates whether DC ZVA access is allowed */
4672     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4673         dzp_bit = 0;
4674     }
4675     return cpu->dcz_blocksize | dzp_bit;
4676 }
4677 
4678 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4679                                     bool isread)
4680 {
4681     if (!(env->pstate & PSTATE_SP)) {
4682         /* Access to SP_EL0 is undefined if it's being used as
4683          * the stack pointer.
4684          */
4685         return CP_ACCESS_TRAP_UNCATEGORIZED;
4686     }
4687     return CP_ACCESS_OK;
4688 }
4689 
4690 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4691 {
4692     return env->pstate & PSTATE_SP;
4693 }
4694 
4695 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4696 {
4697     update_spsel(env, val);
4698 }
4699 
4700 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4701                         uint64_t value)
4702 {
4703     ARMCPU *cpu = env_archcpu(env);
4704 
4705     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4706         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4707         value &= ~SCTLR_M;
4708     }
4709 
4710     /* ??? Lots of these bits are not implemented.  */
4711 
4712     if (ri->state == ARM_CP_STATE_AA64 && !cpu_isar_feature(aa64_mte, cpu)) {
4713         if (ri->opc1 == 6) { /* SCTLR_EL3 */
4714             value &= ~(SCTLR_ITFSB | SCTLR_TCF | SCTLR_ATA);
4715         } else {
4716             value &= ~(SCTLR_ITFSB | SCTLR_TCF0 | SCTLR_TCF |
4717                        SCTLR_ATA0 | SCTLR_ATA);
4718         }
4719     }
4720 
4721     if (raw_read(env, ri) == value) {
4722         /* Skip the TLB flush if nothing actually changed; Linux likes
4723          * to do a lot of pointless SCTLR writes.
4724          */
4725         return;
4726     }
4727 
4728     raw_write(env, ri, value);
4729 
4730     /* This may enable/disable the MMU, so do a TLB flush.  */
4731     tlb_flush(CPU(cpu));
4732 
4733     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4734         /*
4735          * Normally we would always end the TB on an SCTLR write; see the
4736          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4737          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4738          * of hflags from the translator, so do it here.
4739          */
4740         arm_rebuild_hflags(env);
4741     }
4742 }
4743 
4744 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4745                                      bool isread)
4746 {
4747     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4748         return CP_ACCESS_TRAP_FP_EL2;
4749     }
4750     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4751         return CP_ACCESS_TRAP_FP_EL3;
4752     }
4753     return CP_ACCESS_OK;
4754 }
4755 
4756 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4757                        uint64_t value)
4758 {
4759     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4760 }
4761 
4762 static const ARMCPRegInfo v8_cp_reginfo[] = {
4763     /* Minimal set of EL0-visible registers. This will need to be expanded
4764      * significantly for system emulation of AArch64 CPUs.
4765      */
4766     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4767       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4768       .access = PL0_RW, .type = ARM_CP_NZCV },
4769     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4770       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4771       .type = ARM_CP_NO_RAW,
4772       .access = PL0_RW, .accessfn = aa64_daif_access,
4773       .fieldoffset = offsetof(CPUARMState, daif),
4774       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4775     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4776       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4777       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4778       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4779     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4780       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4781       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4782       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4783     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4784       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4785       .access = PL0_R, .type = ARM_CP_NO_RAW,
4786       .readfn = aa64_dczid_read },
4787     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4788       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4789       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4790 #ifndef CONFIG_USER_ONLY
4791       /* Avoid overhead of an access check that always passes in user-mode */
4792       .accessfn = aa64_zva_access,
4793 #endif
4794     },
4795     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4796       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4797       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4798     /* Cache ops: all NOPs since we don't emulate caches */
4799     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4800       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4801       .access = PL1_W, .type = ARM_CP_NOP,
4802       .accessfn = aa64_cacheop_pou_access },
4803     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4804       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4805       .access = PL1_W, .type = ARM_CP_NOP,
4806       .accessfn = aa64_cacheop_pou_access },
4807     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4808       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4809       .access = PL0_W, .type = ARM_CP_NOP,
4810       .accessfn = aa64_cacheop_pou_access },
4811     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4812       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4813       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4814       .type = ARM_CP_NOP },
4815     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4816       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4817       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4818     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4819       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4820       .access = PL0_W, .type = ARM_CP_NOP,
4821       .accessfn = aa64_cacheop_poc_access },
4822     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4823       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4824       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4825     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4826       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4827       .access = PL0_W, .type = ARM_CP_NOP,
4828       .accessfn = aa64_cacheop_pou_access },
4829     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4830       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4831       .access = PL0_W, .type = ARM_CP_NOP,
4832       .accessfn = aa64_cacheop_poc_access },
4833     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4834       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4835       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4836     /* TLBI operations */
4837     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4838       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4839       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4840       .writefn = tlbi_aa64_vmalle1is_write },
4841     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4842       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4843       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4844       .writefn = tlbi_aa64_vae1is_write },
4845     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4846       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4847       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4848       .writefn = tlbi_aa64_vmalle1is_write },
4849     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4850       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4851       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4852       .writefn = tlbi_aa64_vae1is_write },
4853     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4854       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4855       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4856       .writefn = tlbi_aa64_vae1is_write },
4857     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4858       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4859       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4860       .writefn = tlbi_aa64_vae1is_write },
4861     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4862       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4863       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4864       .writefn = tlbi_aa64_vmalle1_write },
4865     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4866       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4867       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4868       .writefn = tlbi_aa64_vae1_write },
4869     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4870       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4871       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4872       .writefn = tlbi_aa64_vmalle1_write },
4873     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4874       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4875       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4876       .writefn = tlbi_aa64_vae1_write },
4877     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4878       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4879       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4880       .writefn = tlbi_aa64_vae1_write },
4881     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4882       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4883       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4884       .writefn = tlbi_aa64_vae1_write },
4885     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4886       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4887       .access = PL2_W, .type = ARM_CP_NOP },
4888     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4889       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4890       .access = PL2_W, .type = ARM_CP_NOP },
4891     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4892       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4893       .access = PL2_W, .type = ARM_CP_NO_RAW,
4894       .writefn = tlbi_aa64_alle1is_write },
4895     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4896       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4897       .access = PL2_W, .type = ARM_CP_NO_RAW,
4898       .writefn = tlbi_aa64_alle1is_write },
4899     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4900       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4901       .access = PL2_W, .type = ARM_CP_NOP },
4902     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4903       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4904       .access = PL2_W, .type = ARM_CP_NOP },
4905     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4906       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4907       .access = PL2_W, .type = ARM_CP_NO_RAW,
4908       .writefn = tlbi_aa64_alle1_write },
4909     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4910       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4911       .access = PL2_W, .type = ARM_CP_NO_RAW,
4912       .writefn = tlbi_aa64_alle1is_write },
4913 #ifndef CONFIG_USER_ONLY
4914     /* 64 bit address translation operations */
4915     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4916       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4917       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4918       .writefn = ats_write64 },
4919     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4920       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4921       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4922       .writefn = ats_write64 },
4923     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4924       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4925       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4926       .writefn = ats_write64 },
4927     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4928       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4929       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4930       .writefn = ats_write64 },
4931     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4932       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4933       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4934       .writefn = ats_write64 },
4935     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4936       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4937       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4938       .writefn = ats_write64 },
4939     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4940       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4941       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4942       .writefn = ats_write64 },
4943     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4944       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4945       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4946       .writefn = ats_write64 },
4947     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4948     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4949       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4950       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4951       .writefn = ats_write64 },
4952     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4953       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4954       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4955       .writefn = ats_write64 },
4956     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4957       .type = ARM_CP_ALIAS,
4958       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4959       .access = PL1_RW, .resetvalue = 0,
4960       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4961       .writefn = par_write },
4962 #endif
4963     /* TLB invalidate last level of translation table walk */
4964     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4965       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4966       .writefn = tlbimva_is_write },
4967     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4968       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4969       .writefn = tlbimvaa_is_write },
4970     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4971       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4972       .writefn = tlbimva_write },
4973     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4974       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4975       .writefn = tlbimvaa_write },
4976     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4977       .type = ARM_CP_NO_RAW, .access = PL2_W,
4978       .writefn = tlbimva_hyp_write },
4979     { .name = "TLBIMVALHIS",
4980       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4981       .type = ARM_CP_NO_RAW, .access = PL2_W,
4982       .writefn = tlbimva_hyp_is_write },
4983     { .name = "TLBIIPAS2",
4984       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4985       .type = ARM_CP_NOP, .access = PL2_W },
4986     { .name = "TLBIIPAS2IS",
4987       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4988       .type = ARM_CP_NOP, .access = PL2_W },
4989     { .name = "TLBIIPAS2L",
4990       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4991       .type = ARM_CP_NOP, .access = PL2_W },
4992     { .name = "TLBIIPAS2LIS",
4993       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4994       .type = ARM_CP_NOP, .access = PL2_W },
4995     /* 32 bit cache operations */
4996     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4997       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
4998     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
4999       .type = ARM_CP_NOP, .access = PL1_W },
5000     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5001       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5002     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5003       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5004     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5005       .type = ARM_CP_NOP, .access = PL1_W },
5006     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5007       .type = ARM_CP_NOP, .access = PL1_W },
5008     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5009       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5010     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5011       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5012     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5013       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5014     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5015       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5016     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5017       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5018     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5019       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5020     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5021       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5022     /* MMU Domain access control / MPU write buffer control */
5023     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5024       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5025       .writefn = dacr_write, .raw_writefn = raw_write,
5026       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5027                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5028     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5029       .type = ARM_CP_ALIAS,
5030       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5031       .access = PL1_RW,
5032       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5033     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5034       .type = ARM_CP_ALIAS,
5035       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5036       .access = PL1_RW,
5037       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5038     /* We rely on the access checks not allowing the guest to write to the
5039      * state field when SPSel indicates that it's being used as the stack
5040      * pointer.
5041      */
5042     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5043       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5044       .access = PL1_RW, .accessfn = sp_el0_access,
5045       .type = ARM_CP_ALIAS,
5046       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5047     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5048       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5049       .access = PL2_RW, .type = ARM_CP_ALIAS,
5050       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5051     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5052       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5053       .type = ARM_CP_NO_RAW,
5054       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5055     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5056       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5057       .type = ARM_CP_ALIAS,
5058       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
5059       .access = PL2_RW, .accessfn = fpexc32_access },
5060     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5061       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5062       .access = PL2_RW, .resetvalue = 0,
5063       .writefn = dacr_write, .raw_writefn = raw_write,
5064       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5065     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5066       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5067       .access = PL2_RW, .resetvalue = 0,
5068       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5069     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5070       .type = ARM_CP_ALIAS,
5071       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5072       .access = PL2_RW,
5073       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5074     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5075       .type = ARM_CP_ALIAS,
5076       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5077       .access = PL2_RW,
5078       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5079     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5080       .type = ARM_CP_ALIAS,
5081       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5082       .access = PL2_RW,
5083       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5084     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5085       .type = ARM_CP_ALIAS,
5086       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5087       .access = PL2_RW,
5088       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5089     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5090       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5091       .resetvalue = 0,
5092       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5093     { .name = "SDCR", .type = ARM_CP_ALIAS,
5094       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5095       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5096       .writefn = sdcr_write,
5097       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5098     REGINFO_SENTINEL
5099 };
5100 
5101 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
5102 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
5103     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5104       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5105       .access = PL2_RW,
5106       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
5107     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
5108       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5109       .access = PL2_RW,
5110       .type = ARM_CP_CONST, .resetvalue = 0 },
5111     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5112       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5113       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5114     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5115       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5116       .access = PL2_RW,
5117       .type = ARM_CP_CONST, .resetvalue = 0 },
5118     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5119       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5120       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5121     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5122       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5123       .access = PL2_RW, .type = ARM_CP_CONST,
5124       .resetvalue = 0 },
5125     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5126       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5127       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5128     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5129       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5130       .access = PL2_RW, .type = ARM_CP_CONST,
5131       .resetvalue = 0 },
5132     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5133       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5134       .access = PL2_RW, .type = ARM_CP_CONST,
5135       .resetvalue = 0 },
5136     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5137       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5138       .access = PL2_RW, .type = ARM_CP_CONST,
5139       .resetvalue = 0 },
5140     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5141       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5142       .access = PL2_RW, .type = ARM_CP_CONST,
5143       .resetvalue = 0 },
5144     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5145       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5146       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5147     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
5148       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5149       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5150       .type = ARM_CP_CONST, .resetvalue = 0 },
5151     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5152       .cp = 15, .opc1 = 6, .crm = 2,
5153       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5154       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
5155     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5156       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5157       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5158     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5159       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5160       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5161     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5162       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5163       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5164     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5165       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5166       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5167     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5168       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5169       .resetvalue = 0 },
5170     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5171       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5172       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5173     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5174       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5175       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5176     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5177       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5178       .resetvalue = 0 },
5179     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5180       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5181       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5182     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5183       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5184       .resetvalue = 0 },
5185     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5186       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5187       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5188     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5189       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5190       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5191     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5192       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5193       .access = PL2_RW, .accessfn = access_tda,
5194       .type = ARM_CP_CONST, .resetvalue = 0 },
5195     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
5196       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5197       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5198       .type = ARM_CP_CONST, .resetvalue = 0 },
5199     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5200       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5201       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5202     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5203       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5204       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5205     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5206       .type = ARM_CP_CONST,
5207       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5208       .access = PL2_RW, .resetvalue = 0 },
5209     REGINFO_SENTINEL
5210 };
5211 
5212 /* Ditto, but for registers which exist in ARMv8 but not v7 */
5213 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
5214     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5215       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5216       .access = PL2_RW,
5217       .type = ARM_CP_CONST, .resetvalue = 0 },
5218     REGINFO_SENTINEL
5219 };
5220 
5221 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5222 {
5223     ARMCPU *cpu = env_archcpu(env);
5224 
5225     if (arm_feature(env, ARM_FEATURE_V8)) {
5226         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5227     } else {
5228         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5229     }
5230 
5231     if (arm_feature(env, ARM_FEATURE_EL3)) {
5232         valid_mask &= ~HCR_HCD;
5233     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5234         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5235          * However, if we're using the SMC PSCI conduit then QEMU is
5236          * effectively acting like EL3 firmware and so the guest at
5237          * EL2 should retain the ability to prevent EL1 from being
5238          * able to make SMC calls into the ersatz firmware, so in
5239          * that case HCR.TSC should be read/write.
5240          */
5241         valid_mask &= ~HCR_TSC;
5242     }
5243 
5244     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5245         if (cpu_isar_feature(aa64_vh, cpu)) {
5246             valid_mask |= HCR_E2H;
5247         }
5248         if (cpu_isar_feature(aa64_lor, cpu)) {
5249             valid_mask |= HCR_TLOR;
5250         }
5251         if (cpu_isar_feature(aa64_pauth, cpu)) {
5252             valid_mask |= HCR_API | HCR_APK;
5253         }
5254         if (cpu_isar_feature(aa64_mte, cpu)) {
5255             valid_mask |= HCR_ATA | HCR_DCT | HCR_TID5;
5256         }
5257     }
5258 
5259     /* Clear RES0 bits.  */
5260     value &= valid_mask;
5261 
5262     /*
5263      * These bits change the MMU setup:
5264      * HCR_VM enables stage 2 translation
5265      * HCR_PTW forbids certain page-table setups
5266      * HCR_DC disables stage1 and enables stage2 translation
5267      * HCR_DCT enables tagging on (disabled) stage1 translation
5268      */
5269     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC | HCR_DCT)) {
5270         tlb_flush(CPU(cpu));
5271     }
5272     env->cp15.hcr_el2 = value;
5273 
5274     /*
5275      * Updates to VI and VF require us to update the status of
5276      * virtual interrupts, which are the logical OR of these bits
5277      * and the state of the input lines from the GIC. (This requires
5278      * that we have the iothread lock, which is done by marking the
5279      * reginfo structs as ARM_CP_IO.)
5280      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5281      * possible for it to be taken immediately, because VIRQ and
5282      * VFIQ are masked unless running at EL0 or EL1, and HCR
5283      * can only be written at EL2.
5284      */
5285     g_assert(qemu_mutex_iothread_locked());
5286     arm_cpu_update_virq(cpu);
5287     arm_cpu_update_vfiq(cpu);
5288 }
5289 
5290 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5291 {
5292     do_hcr_write(env, value, 0);
5293 }
5294 
5295 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5296                           uint64_t value)
5297 {
5298     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5299     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5300     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5301 }
5302 
5303 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5304                          uint64_t value)
5305 {
5306     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5307     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5308     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5309 }
5310 
5311 /*
5312  * Return the effective value of HCR_EL2.
5313  * Bits that are not included here:
5314  * RW       (read from SCR_EL3.RW as needed)
5315  */
5316 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5317 {
5318     uint64_t ret = env->cp15.hcr_el2;
5319 
5320     if (arm_is_secure_below_el3(env)) {
5321         /*
5322          * "This register has no effect if EL2 is not enabled in the
5323          * current Security state".  This is ARMv8.4-SecEL2 speak for
5324          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5325          *
5326          * Prior to that, the language was "In an implementation that
5327          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5328          * as if this field is 0 for all purposes other than a direct
5329          * read or write access of HCR_EL2".  With lots of enumeration
5330          * on a per-field basis.  In current QEMU, this is condition
5331          * is arm_is_secure_below_el3.
5332          *
5333          * Since the v8.4 language applies to the entire register, and
5334          * appears to be backward compatible, use that.
5335          */
5336         return 0;
5337     }
5338 
5339     /*
5340      * For a cpu that supports both aarch64 and aarch32, we can set bits
5341      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5342      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5343      */
5344     if (!arm_el_is_aa64(env, 2)) {
5345         uint64_t aa32_valid;
5346 
5347         /*
5348          * These bits are up-to-date as of ARMv8.6.
5349          * For HCR, it's easiest to list just the 2 bits that are invalid.
5350          * For HCR2, list those that are valid.
5351          */
5352         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5353         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5354                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5355         ret &= aa32_valid;
5356     }
5357 
5358     if (ret & HCR_TGE) {
5359         /* These bits are up-to-date as of ARMv8.6.  */
5360         if (ret & HCR_E2H) {
5361             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5362                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5363                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5364                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5365                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5366                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5367         } else {
5368             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5369         }
5370         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5371                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5372                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5373                  HCR_TLOR);
5374     }
5375 
5376     return ret;
5377 }
5378 
5379 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5380                            uint64_t value)
5381 {
5382     /*
5383      * For A-profile AArch32 EL3, if NSACR.CP10
5384      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5385      */
5386     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5387         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5388         value &= ~(0x3 << 10);
5389         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5390     }
5391     env->cp15.cptr_el[2] = value;
5392 }
5393 
5394 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5395 {
5396     /*
5397      * For A-profile AArch32 EL3, if NSACR.CP10
5398      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5399      */
5400     uint64_t value = env->cp15.cptr_el[2];
5401 
5402     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5403         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5404         value |= 0x3 << 10;
5405     }
5406     return value;
5407 }
5408 
5409 static const ARMCPRegInfo el2_cp_reginfo[] = {
5410     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5411       .type = ARM_CP_IO,
5412       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5413       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5414       .writefn = hcr_write },
5415     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5416       .type = ARM_CP_ALIAS | ARM_CP_IO,
5417       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5418       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5419       .writefn = hcr_writelow },
5420     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5421       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5422       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5423     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5424       .type = ARM_CP_ALIAS,
5425       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5426       .access = PL2_RW,
5427       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5428     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5429       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5430       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5431     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5432       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5433       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5434     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5435       .type = ARM_CP_ALIAS,
5436       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5437       .access = PL2_RW,
5438       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5439     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5440       .type = ARM_CP_ALIAS,
5441       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5442       .access = PL2_RW,
5443       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5444     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5445       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5446       .access = PL2_RW, .writefn = vbar_write,
5447       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5448       .resetvalue = 0 },
5449     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5450       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5451       .access = PL3_RW, .type = ARM_CP_ALIAS,
5452       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5453     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5454       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5455       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5456       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5457       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5458     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5459       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5460       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5461       .resetvalue = 0 },
5462     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5463       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5464       .access = PL2_RW, .type = ARM_CP_ALIAS,
5465       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5466     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5467       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5468       .access = PL2_RW, .type = ARM_CP_CONST,
5469       .resetvalue = 0 },
5470     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5471     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5472       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5473       .access = PL2_RW, .type = ARM_CP_CONST,
5474       .resetvalue = 0 },
5475     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5476       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5477       .access = PL2_RW, .type = ARM_CP_CONST,
5478       .resetvalue = 0 },
5479     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5480       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5481       .access = PL2_RW, .type = ARM_CP_CONST,
5482       .resetvalue = 0 },
5483     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5484       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5485       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5486       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5487       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5488     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5489       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5490       .type = ARM_CP_ALIAS,
5491       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5492       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5493     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5494       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5495       .access = PL2_RW,
5496       /* no .writefn needed as this can't cause an ASID change;
5497        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5498        */
5499       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5500     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5501       .cp = 15, .opc1 = 6, .crm = 2,
5502       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5503       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5504       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5505       .writefn = vttbr_write },
5506     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5507       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5508       .access = PL2_RW, .writefn = vttbr_write,
5509       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5510     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5511       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5512       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5513       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5514     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5515       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5516       .access = PL2_RW, .resetvalue = 0,
5517       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5518     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5519       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5520       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5521       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5522     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5523       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5524       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5525     { .name = "TLBIALLNSNH",
5526       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5527       .type = ARM_CP_NO_RAW, .access = PL2_W,
5528       .writefn = tlbiall_nsnh_write },
5529     { .name = "TLBIALLNSNHIS",
5530       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5531       .type = ARM_CP_NO_RAW, .access = PL2_W,
5532       .writefn = tlbiall_nsnh_is_write },
5533     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5534       .type = ARM_CP_NO_RAW, .access = PL2_W,
5535       .writefn = tlbiall_hyp_write },
5536     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5537       .type = ARM_CP_NO_RAW, .access = PL2_W,
5538       .writefn = tlbiall_hyp_is_write },
5539     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5540       .type = ARM_CP_NO_RAW, .access = PL2_W,
5541       .writefn = tlbimva_hyp_write },
5542     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5543       .type = ARM_CP_NO_RAW, .access = PL2_W,
5544       .writefn = tlbimva_hyp_is_write },
5545     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5546       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5547       .type = ARM_CP_NO_RAW, .access = PL2_W,
5548       .writefn = tlbi_aa64_alle2_write },
5549     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5550       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5551       .type = ARM_CP_NO_RAW, .access = PL2_W,
5552       .writefn = tlbi_aa64_vae2_write },
5553     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5554       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5555       .access = PL2_W, .type = ARM_CP_NO_RAW,
5556       .writefn = tlbi_aa64_vae2_write },
5557     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5558       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5559       .access = PL2_W, .type = ARM_CP_NO_RAW,
5560       .writefn = tlbi_aa64_alle2is_write },
5561     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5562       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5563       .type = ARM_CP_NO_RAW, .access = PL2_W,
5564       .writefn = tlbi_aa64_vae2is_write },
5565     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5566       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5567       .access = PL2_W, .type = ARM_CP_NO_RAW,
5568       .writefn = tlbi_aa64_vae2is_write },
5569 #ifndef CONFIG_USER_ONLY
5570     /* Unlike the other EL2-related AT operations, these must
5571      * UNDEF from EL3 if EL2 is not implemented, which is why we
5572      * define them here rather than with the rest of the AT ops.
5573      */
5574     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5575       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5576       .access = PL2_W, .accessfn = at_s1e2_access,
5577       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5578     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5579       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5580       .access = PL2_W, .accessfn = at_s1e2_access,
5581       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5582     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5583      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5584      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5585      * to behave as if SCR.NS was 1.
5586      */
5587     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5588       .access = PL2_W,
5589       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5590     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5591       .access = PL2_W,
5592       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5593     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5594       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5595       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5596        * reset values as IMPDEF. We choose to reset to 3 to comply with
5597        * both ARMv7 and ARMv8.
5598        */
5599       .access = PL2_RW, .resetvalue = 3,
5600       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5601     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5602       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5603       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5604       .writefn = gt_cntvoff_write,
5605       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5606     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5607       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5608       .writefn = gt_cntvoff_write,
5609       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5610     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5611       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5612       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5613       .type = ARM_CP_IO, .access = PL2_RW,
5614       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5615     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5616       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5617       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5618       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5619     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5620       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5621       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5622       .resetfn = gt_hyp_timer_reset,
5623       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5624     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5625       .type = ARM_CP_IO,
5626       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5627       .access = PL2_RW,
5628       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5629       .resetvalue = 0,
5630       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5631 #endif
5632     /* The only field of MDCR_EL2 that has a defined architectural reset value
5633      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
5634      * don't implement any PMU event counters, so using zero as a reset
5635      * value for MDCR_EL2 is okay
5636      */
5637     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5638       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5639       .access = PL2_RW, .resetvalue = 0,
5640       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5641     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5642       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5643       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5644       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5645     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5646       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5647       .access = PL2_RW,
5648       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5649     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5650       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5651       .access = PL2_RW,
5652       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5653     REGINFO_SENTINEL
5654 };
5655 
5656 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5657     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5658       .type = ARM_CP_ALIAS | ARM_CP_IO,
5659       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5660       .access = PL2_RW,
5661       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5662       .writefn = hcr_writehigh },
5663     REGINFO_SENTINEL
5664 };
5665 
5666 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5667                                    bool isread)
5668 {
5669     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5670      * At Secure EL1 it traps to EL3.
5671      */
5672     if (arm_current_el(env) == 3) {
5673         return CP_ACCESS_OK;
5674     }
5675     if (arm_is_secure_below_el3(env)) {
5676         return CP_ACCESS_TRAP_EL3;
5677     }
5678     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5679     if (isread) {
5680         return CP_ACCESS_OK;
5681     }
5682     return CP_ACCESS_TRAP_UNCATEGORIZED;
5683 }
5684 
5685 static const ARMCPRegInfo el3_cp_reginfo[] = {
5686     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5687       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5688       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5689       .resetvalue = 0, .writefn = scr_write },
5690     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5691       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5692       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5693       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5694       .writefn = scr_write },
5695     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5696       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5697       .access = PL3_RW, .resetvalue = 0,
5698       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5699     { .name = "SDER",
5700       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5701       .access = PL3_RW, .resetvalue = 0,
5702       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5703     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5704       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5705       .writefn = vbar_write, .resetvalue = 0,
5706       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5707     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5708       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5709       .access = PL3_RW, .resetvalue = 0,
5710       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5711     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5712       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5713       .access = PL3_RW,
5714       /* no .writefn needed as this can't cause an ASID change;
5715        * we must provide a .raw_writefn and .resetfn because we handle
5716        * reset and migration for the AArch32 TTBCR(S), which might be
5717        * using mask and base_mask.
5718        */
5719       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5720       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5721     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5722       .type = ARM_CP_ALIAS,
5723       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5724       .access = PL3_RW,
5725       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5726     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5727       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5728       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5729     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5730       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5731       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5732     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5733       .type = ARM_CP_ALIAS,
5734       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5735       .access = PL3_RW,
5736       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5737     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5738       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5739       .access = PL3_RW, .writefn = vbar_write,
5740       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5741       .resetvalue = 0 },
5742     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5743       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5744       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5745       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5746     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5747       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5748       .access = PL3_RW, .resetvalue = 0,
5749       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5750     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5751       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5752       .access = PL3_RW, .type = ARM_CP_CONST,
5753       .resetvalue = 0 },
5754     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5755       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5756       .access = PL3_RW, .type = ARM_CP_CONST,
5757       .resetvalue = 0 },
5758     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5759       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5760       .access = PL3_RW, .type = ARM_CP_CONST,
5761       .resetvalue = 0 },
5762     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5763       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5764       .access = PL3_W, .type = ARM_CP_NO_RAW,
5765       .writefn = tlbi_aa64_alle3is_write },
5766     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5767       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5768       .access = PL3_W, .type = ARM_CP_NO_RAW,
5769       .writefn = tlbi_aa64_vae3is_write },
5770     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5771       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5772       .access = PL3_W, .type = ARM_CP_NO_RAW,
5773       .writefn = tlbi_aa64_vae3is_write },
5774     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5775       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5776       .access = PL3_W, .type = ARM_CP_NO_RAW,
5777       .writefn = tlbi_aa64_alle3_write },
5778     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5779       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5780       .access = PL3_W, .type = ARM_CP_NO_RAW,
5781       .writefn = tlbi_aa64_vae3_write },
5782     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5783       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5784       .access = PL3_W, .type = ARM_CP_NO_RAW,
5785       .writefn = tlbi_aa64_vae3_write },
5786     REGINFO_SENTINEL
5787 };
5788 
5789 #ifndef CONFIG_USER_ONLY
5790 /* Test if system register redirection is to occur in the current state.  */
5791 static bool redirect_for_e2h(CPUARMState *env)
5792 {
5793     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5794 }
5795 
5796 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5797 {
5798     CPReadFn *readfn;
5799 
5800     if (redirect_for_e2h(env)) {
5801         /* Switch to the saved EL2 version of the register.  */
5802         ri = ri->opaque;
5803         readfn = ri->readfn;
5804     } else {
5805         readfn = ri->orig_readfn;
5806     }
5807     if (readfn == NULL) {
5808         readfn = raw_read;
5809     }
5810     return readfn(env, ri);
5811 }
5812 
5813 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5814                           uint64_t value)
5815 {
5816     CPWriteFn *writefn;
5817 
5818     if (redirect_for_e2h(env)) {
5819         /* Switch to the saved EL2 version of the register.  */
5820         ri = ri->opaque;
5821         writefn = ri->writefn;
5822     } else {
5823         writefn = ri->orig_writefn;
5824     }
5825     if (writefn == NULL) {
5826         writefn = raw_write;
5827     }
5828     writefn(env, ri, value);
5829 }
5830 
5831 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5832 {
5833     struct E2HAlias {
5834         uint32_t src_key, dst_key, new_key;
5835         const char *src_name, *dst_name, *new_name;
5836         bool (*feature)(const ARMISARegisters *id);
5837     };
5838 
5839 #define K(op0, op1, crn, crm, op2) \
5840     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5841 
5842     static const struct E2HAlias aliases[] = {
5843         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5844           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5845         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5846           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5847         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5848           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5849         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5850           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5851         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5852           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5853         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5854           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5855         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5856           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5857         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5858           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5859         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5860           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5861         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5862           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5863         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5864           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5865         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5866           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5867         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5868           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5869         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5870           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5871         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
5872           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
5873         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
5874           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
5875 
5876         /*
5877          * Note that redirection of ZCR is mentioned in the description
5878          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
5879          * not in the summary table.
5880          */
5881         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
5882           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
5883 
5884         { K(3, 0,  5, 6, 0), K(3, 4,  5, 6, 0), K(3, 5, 5, 6, 0),
5885           "TFSR_EL1", "TFSR_EL2", "TFSR_EL12", isar_feature_aa64_mte },
5886 
5887         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
5888         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
5889     };
5890 #undef K
5891 
5892     size_t i;
5893 
5894     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
5895         const struct E2HAlias *a = &aliases[i];
5896         ARMCPRegInfo *src_reg, *dst_reg;
5897 
5898         if (a->feature && !a->feature(&cpu->isar)) {
5899             continue;
5900         }
5901 
5902         src_reg = g_hash_table_lookup(cpu->cp_regs, &a->src_key);
5903         dst_reg = g_hash_table_lookup(cpu->cp_regs, &a->dst_key);
5904         g_assert(src_reg != NULL);
5905         g_assert(dst_reg != NULL);
5906 
5907         /* Cross-compare names to detect typos in the keys.  */
5908         g_assert(strcmp(src_reg->name, a->src_name) == 0);
5909         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
5910 
5911         /* None of the core system registers use opaque; we will.  */
5912         g_assert(src_reg->opaque == NULL);
5913 
5914         /* Create alias before redirection so we dup the right data. */
5915         if (a->new_key) {
5916             ARMCPRegInfo *new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
5917             uint32_t *new_key = g_memdup(&a->new_key, sizeof(uint32_t));
5918             bool ok;
5919 
5920             new_reg->name = a->new_name;
5921             new_reg->type |= ARM_CP_ALIAS;
5922             /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
5923             new_reg->access &= PL2_RW | PL3_RW;
5924 
5925             ok = g_hash_table_insert(cpu->cp_regs, new_key, new_reg);
5926             g_assert(ok);
5927         }
5928 
5929         src_reg->opaque = dst_reg;
5930         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
5931         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
5932         if (!src_reg->raw_readfn) {
5933             src_reg->raw_readfn = raw_read;
5934         }
5935         if (!src_reg->raw_writefn) {
5936             src_reg->raw_writefn = raw_write;
5937         }
5938         src_reg->readfn = el2_e2h_read;
5939         src_reg->writefn = el2_e2h_write;
5940     }
5941 }
5942 #endif
5943 
5944 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5945                                      bool isread)
5946 {
5947     int cur_el = arm_current_el(env);
5948 
5949     if (cur_el < 2) {
5950         uint64_t hcr = arm_hcr_el2_eff(env);
5951 
5952         if (cur_el == 0) {
5953             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
5954                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
5955                     return CP_ACCESS_TRAP_EL2;
5956                 }
5957             } else {
5958                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5959                     return CP_ACCESS_TRAP;
5960                 }
5961                 if (hcr & HCR_TID2) {
5962                     return CP_ACCESS_TRAP_EL2;
5963                 }
5964             }
5965         } else if (hcr & HCR_TID2) {
5966             return CP_ACCESS_TRAP_EL2;
5967         }
5968     }
5969 
5970     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
5971         return CP_ACCESS_TRAP_EL2;
5972     }
5973 
5974     return CP_ACCESS_OK;
5975 }
5976 
5977 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5978                         uint64_t value)
5979 {
5980     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5981      * read via a bit in OSLSR_EL1.
5982      */
5983     int oslock;
5984 
5985     if (ri->state == ARM_CP_STATE_AA32) {
5986         oslock = (value == 0xC5ACCE55);
5987     } else {
5988         oslock = value & 1;
5989     }
5990 
5991     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5992 }
5993 
5994 static const ARMCPRegInfo debug_cp_reginfo[] = {
5995     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5996      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5997      * unlike DBGDRAR it is never accessible from EL0.
5998      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5999      * accessor.
6000      */
6001     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
6002       .access = PL0_R, .accessfn = access_tdra,
6003       .type = ARM_CP_CONST, .resetvalue = 0 },
6004     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
6005       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6006       .access = PL1_R, .accessfn = access_tdra,
6007       .type = ARM_CP_CONST, .resetvalue = 0 },
6008     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
6009       .access = PL0_R, .accessfn = access_tdra,
6010       .type = ARM_CP_CONST, .resetvalue = 0 },
6011     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
6012     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
6013       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
6014       .access = PL1_RW, .accessfn = access_tda,
6015       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
6016       .resetvalue = 0 },
6017     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
6018      * We don't implement the configurable EL0 access.
6019      */
6020     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
6021       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6022       .type = ARM_CP_ALIAS,
6023       .access = PL1_R, .accessfn = access_tda,
6024       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
6025     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
6026       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
6027       .access = PL1_W, .type = ARM_CP_NO_RAW,
6028       .accessfn = access_tdosa,
6029       .writefn = oslar_write },
6030     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
6031       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
6032       .access = PL1_R, .resetvalue = 10,
6033       .accessfn = access_tdosa,
6034       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
6035     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
6036     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
6037       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
6038       .access = PL1_RW, .accessfn = access_tdosa,
6039       .type = ARM_CP_NOP },
6040     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
6041      * implement vector catch debug events yet.
6042      */
6043     { .name = "DBGVCR",
6044       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6045       .access = PL1_RW, .accessfn = access_tda,
6046       .type = ARM_CP_NOP },
6047     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
6048      * to save and restore a 32-bit guest's DBGVCR)
6049      */
6050     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
6051       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
6052       .access = PL2_RW, .accessfn = access_tda,
6053       .type = ARM_CP_NOP },
6054     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6055      * Channel but Linux may try to access this register. The 32-bit
6056      * alias is DBGDCCINT.
6057      */
6058     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6059       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6060       .access = PL1_RW, .accessfn = access_tda,
6061       .type = ARM_CP_NOP },
6062     REGINFO_SENTINEL
6063 };
6064 
6065 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6066     /* 64 bit access versions of the (dummy) debug registers */
6067     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6068       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6069     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6070       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6071     REGINFO_SENTINEL
6072 };
6073 
6074 /* Return the exception level to which exceptions should be taken
6075  * via SVEAccessTrap.  If an exception should be routed through
6076  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6077  * take care of raising that exception.
6078  * C.f. the ARM pseudocode function CheckSVEEnabled.
6079  */
6080 int sve_exception_el(CPUARMState *env, int el)
6081 {
6082 #ifndef CONFIG_USER_ONLY
6083     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6084 
6085     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6086         bool disabled = false;
6087 
6088         /* The CPACR.ZEN controls traps to EL1:
6089          * 0, 2 : trap EL0 and EL1 accesses
6090          * 1    : trap only EL0 accesses
6091          * 3    : trap no accesses
6092          */
6093         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
6094             disabled = true;
6095         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
6096             disabled = el == 0;
6097         }
6098         if (disabled) {
6099             /* route_to_el2 */
6100             return hcr_el2 & HCR_TGE ? 2 : 1;
6101         }
6102 
6103         /* Check CPACR.FPEN.  */
6104         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
6105             disabled = true;
6106         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
6107             disabled = el == 0;
6108         }
6109         if (disabled) {
6110             return 0;
6111         }
6112     }
6113 
6114     /* CPTR_EL2.  Since TZ and TFP are positive,
6115      * they will be zero when EL2 is not present.
6116      */
6117     if (el <= 2 && !arm_is_secure_below_el3(env)) {
6118         if (env->cp15.cptr_el[2] & CPTR_TZ) {
6119             return 2;
6120         }
6121         if (env->cp15.cptr_el[2] & CPTR_TFP) {
6122             return 0;
6123         }
6124     }
6125 
6126     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6127     if (arm_feature(env, ARM_FEATURE_EL3)
6128         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6129         return 3;
6130     }
6131 #endif
6132     return 0;
6133 }
6134 
6135 static uint32_t sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6136 {
6137     uint32_t end_len;
6138 
6139     end_len = start_len &= 0xf;
6140     if (!test_bit(start_len, cpu->sve_vq_map)) {
6141         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6142         assert(end_len < start_len);
6143     }
6144     return end_len;
6145 }
6146 
6147 /*
6148  * Given that SVE is enabled, return the vector length for EL.
6149  */
6150 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6151 {
6152     ARMCPU *cpu = env_archcpu(env);
6153     uint32_t zcr_len = cpu->sve_max_vq - 1;
6154 
6155     if (el <= 1) {
6156         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6157     }
6158     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6159         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6160     }
6161     if (arm_feature(env, ARM_FEATURE_EL3)) {
6162         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6163     }
6164 
6165     return sve_zcr_get_valid_len(cpu, zcr_len);
6166 }
6167 
6168 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6169                       uint64_t value)
6170 {
6171     int cur_el = arm_current_el(env);
6172     int old_len = sve_zcr_len_for_el(env, cur_el);
6173     int new_len;
6174 
6175     /* Bits other than [3:0] are RAZ/WI.  */
6176     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6177     raw_write(env, ri, value & 0xf);
6178 
6179     /*
6180      * Because we arrived here, we know both FP and SVE are enabled;
6181      * otherwise we would have trapped access to the ZCR_ELn register.
6182      */
6183     new_len = sve_zcr_len_for_el(env, cur_el);
6184     if (new_len < old_len) {
6185         aarch64_sve_narrow_vq(env, new_len + 1);
6186     }
6187 }
6188 
6189 static const ARMCPRegInfo zcr_el1_reginfo = {
6190     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6191     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6192     .access = PL1_RW, .type = ARM_CP_SVE,
6193     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6194     .writefn = zcr_write, .raw_writefn = raw_write
6195 };
6196 
6197 static const ARMCPRegInfo zcr_el2_reginfo = {
6198     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6199     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6200     .access = PL2_RW, .type = ARM_CP_SVE,
6201     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6202     .writefn = zcr_write, .raw_writefn = raw_write
6203 };
6204 
6205 static const ARMCPRegInfo zcr_no_el2_reginfo = {
6206     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6207     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6208     .access = PL2_RW, .type = ARM_CP_SVE,
6209     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
6210 };
6211 
6212 static const ARMCPRegInfo zcr_el3_reginfo = {
6213     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6214     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6215     .access = PL3_RW, .type = ARM_CP_SVE,
6216     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6217     .writefn = zcr_write, .raw_writefn = raw_write
6218 };
6219 
6220 void hw_watchpoint_update(ARMCPU *cpu, int n)
6221 {
6222     CPUARMState *env = &cpu->env;
6223     vaddr len = 0;
6224     vaddr wvr = env->cp15.dbgwvr[n];
6225     uint64_t wcr = env->cp15.dbgwcr[n];
6226     int mask;
6227     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6228 
6229     if (env->cpu_watchpoint[n]) {
6230         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6231         env->cpu_watchpoint[n] = NULL;
6232     }
6233 
6234     if (!extract64(wcr, 0, 1)) {
6235         /* E bit clear : watchpoint disabled */
6236         return;
6237     }
6238 
6239     switch (extract64(wcr, 3, 2)) {
6240     case 0:
6241         /* LSC 00 is reserved and must behave as if the wp is disabled */
6242         return;
6243     case 1:
6244         flags |= BP_MEM_READ;
6245         break;
6246     case 2:
6247         flags |= BP_MEM_WRITE;
6248         break;
6249     case 3:
6250         flags |= BP_MEM_ACCESS;
6251         break;
6252     }
6253 
6254     /* Attempts to use both MASK and BAS fields simultaneously are
6255      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6256      * thus generating a watchpoint for every byte in the masked region.
6257      */
6258     mask = extract64(wcr, 24, 4);
6259     if (mask == 1 || mask == 2) {
6260         /* Reserved values of MASK; we must act as if the mask value was
6261          * some non-reserved value, or as if the watchpoint were disabled.
6262          * We choose the latter.
6263          */
6264         return;
6265     } else if (mask) {
6266         /* Watchpoint covers an aligned area up to 2GB in size */
6267         len = 1ULL << mask;
6268         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6269          * whether the watchpoint fires when the unmasked bits match; we opt
6270          * to generate the exceptions.
6271          */
6272         wvr &= ~(len - 1);
6273     } else {
6274         /* Watchpoint covers bytes defined by the byte address select bits */
6275         int bas = extract64(wcr, 5, 8);
6276         int basstart;
6277 
6278         if (extract64(wvr, 2, 1)) {
6279             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6280              * ignored, and BAS[3:0] define which bytes to watch.
6281              */
6282             bas &= 0xf;
6283         }
6284 
6285         if (bas == 0) {
6286             /* This must act as if the watchpoint is disabled */
6287             return;
6288         }
6289 
6290         /* The BAS bits are supposed to be programmed to indicate a contiguous
6291          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6292          * we fire for each byte in the word/doubleword addressed by the WVR.
6293          * We choose to ignore any non-zero bits after the first range of 1s.
6294          */
6295         basstart = ctz32(bas);
6296         len = cto32(bas >> basstart);
6297         wvr += basstart;
6298     }
6299 
6300     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6301                           &env->cpu_watchpoint[n]);
6302 }
6303 
6304 void hw_watchpoint_update_all(ARMCPU *cpu)
6305 {
6306     int i;
6307     CPUARMState *env = &cpu->env;
6308 
6309     /* Completely clear out existing QEMU watchpoints and our array, to
6310      * avoid possible stale entries following migration load.
6311      */
6312     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6313     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6314 
6315     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6316         hw_watchpoint_update(cpu, i);
6317     }
6318 }
6319 
6320 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6321                          uint64_t value)
6322 {
6323     ARMCPU *cpu = env_archcpu(env);
6324     int i = ri->crm;
6325 
6326     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
6327      * register reads and behaves as if values written are sign extended.
6328      * Bits [1:0] are RES0.
6329      */
6330     value = sextract64(value, 0, 49) & ~3ULL;
6331 
6332     raw_write(env, ri, value);
6333     hw_watchpoint_update(cpu, i);
6334 }
6335 
6336 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6337                          uint64_t value)
6338 {
6339     ARMCPU *cpu = env_archcpu(env);
6340     int i = ri->crm;
6341 
6342     raw_write(env, ri, value);
6343     hw_watchpoint_update(cpu, i);
6344 }
6345 
6346 void hw_breakpoint_update(ARMCPU *cpu, int n)
6347 {
6348     CPUARMState *env = &cpu->env;
6349     uint64_t bvr = env->cp15.dbgbvr[n];
6350     uint64_t bcr = env->cp15.dbgbcr[n];
6351     vaddr addr;
6352     int bt;
6353     int flags = BP_CPU;
6354 
6355     if (env->cpu_breakpoint[n]) {
6356         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6357         env->cpu_breakpoint[n] = NULL;
6358     }
6359 
6360     if (!extract64(bcr, 0, 1)) {
6361         /* E bit clear : watchpoint disabled */
6362         return;
6363     }
6364 
6365     bt = extract64(bcr, 20, 4);
6366 
6367     switch (bt) {
6368     case 4: /* unlinked address mismatch (reserved if AArch64) */
6369     case 5: /* linked address mismatch (reserved if AArch64) */
6370         qemu_log_mask(LOG_UNIMP,
6371                       "arm: address mismatch breakpoint types not implemented\n");
6372         return;
6373     case 0: /* unlinked address match */
6374     case 1: /* linked address match */
6375     {
6376         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
6377          * we behave as if the register was sign extended. Bits [1:0] are
6378          * RES0. The BAS field is used to allow setting breakpoints on 16
6379          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6380          * a bp will fire if the addresses covered by the bp and the addresses
6381          * covered by the insn overlap but the insn doesn't start at the
6382          * start of the bp address range. We choose to require the insn and
6383          * the bp to have the same address. The constraints on writing to
6384          * BAS enforced in dbgbcr_write mean we have only four cases:
6385          *  0b0000  => no breakpoint
6386          *  0b0011  => breakpoint on addr
6387          *  0b1100  => breakpoint on addr + 2
6388          *  0b1111  => breakpoint on addr
6389          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6390          */
6391         int bas = extract64(bcr, 5, 4);
6392         addr = sextract64(bvr, 0, 49) & ~3ULL;
6393         if (bas == 0) {
6394             return;
6395         }
6396         if (bas == 0xc) {
6397             addr += 2;
6398         }
6399         break;
6400     }
6401     case 2: /* unlinked context ID match */
6402     case 8: /* unlinked VMID match (reserved if no EL2) */
6403     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6404         qemu_log_mask(LOG_UNIMP,
6405                       "arm: unlinked context breakpoint types not implemented\n");
6406         return;
6407     case 9: /* linked VMID match (reserved if no EL2) */
6408     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6409     case 3: /* linked context ID match */
6410     default:
6411         /* We must generate no events for Linked context matches (unless
6412          * they are linked to by some other bp/wp, which is handled in
6413          * updates for the linking bp/wp). We choose to also generate no events
6414          * for reserved values.
6415          */
6416         return;
6417     }
6418 
6419     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6420 }
6421 
6422 void hw_breakpoint_update_all(ARMCPU *cpu)
6423 {
6424     int i;
6425     CPUARMState *env = &cpu->env;
6426 
6427     /* Completely clear out existing QEMU breakpoints and our array, to
6428      * avoid possible stale entries following migration load.
6429      */
6430     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6431     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6432 
6433     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6434         hw_breakpoint_update(cpu, i);
6435     }
6436 }
6437 
6438 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6439                          uint64_t value)
6440 {
6441     ARMCPU *cpu = env_archcpu(env);
6442     int i = ri->crm;
6443 
6444     raw_write(env, ri, value);
6445     hw_breakpoint_update(cpu, i);
6446 }
6447 
6448 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6449                          uint64_t value)
6450 {
6451     ARMCPU *cpu = env_archcpu(env);
6452     int i = ri->crm;
6453 
6454     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6455      * copy of BAS[0].
6456      */
6457     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6458     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6459 
6460     raw_write(env, ri, value);
6461     hw_breakpoint_update(cpu, i);
6462 }
6463 
6464 static void define_debug_regs(ARMCPU *cpu)
6465 {
6466     /* Define v7 and v8 architectural debug registers.
6467      * These are just dummy implementations for now.
6468      */
6469     int i;
6470     int wrps, brps, ctx_cmps;
6471     ARMCPRegInfo dbgdidr = {
6472         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
6473         .access = PL0_R, .accessfn = access_tda,
6474         .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6475     };
6476 
6477     /* Note that all these register fields hold "number of Xs minus 1". */
6478     brps = arm_num_brps(cpu);
6479     wrps = arm_num_wrps(cpu);
6480     ctx_cmps = arm_num_ctx_cmps(cpu);
6481 
6482     assert(ctx_cmps <= brps);
6483 
6484     define_one_arm_cp_reg(cpu, &dbgdidr);
6485     define_arm_cp_regs(cpu, debug_cp_reginfo);
6486 
6487     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6488         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6489     }
6490 
6491     for (i = 0; i < brps; i++) {
6492         ARMCPRegInfo dbgregs[] = {
6493             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6494               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6495               .access = PL1_RW, .accessfn = access_tda,
6496               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6497               .writefn = dbgbvr_write, .raw_writefn = raw_write
6498             },
6499             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6500               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6501               .access = PL1_RW, .accessfn = access_tda,
6502               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6503               .writefn = dbgbcr_write, .raw_writefn = raw_write
6504             },
6505             REGINFO_SENTINEL
6506         };
6507         define_arm_cp_regs(cpu, dbgregs);
6508     }
6509 
6510     for (i = 0; i < wrps; i++) {
6511         ARMCPRegInfo dbgregs[] = {
6512             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6513               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6514               .access = PL1_RW, .accessfn = access_tda,
6515               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6516               .writefn = dbgwvr_write, .raw_writefn = raw_write
6517             },
6518             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6519               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6520               .access = PL1_RW, .accessfn = access_tda,
6521               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6522               .writefn = dbgwcr_write, .raw_writefn = raw_write
6523             },
6524             REGINFO_SENTINEL
6525         };
6526         define_arm_cp_regs(cpu, dbgregs);
6527     }
6528 }
6529 
6530 static void define_pmu_regs(ARMCPU *cpu)
6531 {
6532     /*
6533      * v7 performance monitor control register: same implementor
6534      * field as main ID register, and we implement four counters in
6535      * addition to the cycle count register.
6536      */
6537     unsigned int i, pmcrn = 4;
6538     ARMCPRegInfo pmcr = {
6539         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6540         .access = PL0_RW,
6541         .type = ARM_CP_IO | ARM_CP_ALIAS,
6542         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6543         .accessfn = pmreg_access, .writefn = pmcr_write,
6544         .raw_writefn = raw_write,
6545     };
6546     ARMCPRegInfo pmcr64 = {
6547         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6548         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6549         .access = PL0_RW, .accessfn = pmreg_access,
6550         .type = ARM_CP_IO,
6551         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6552         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6553                       PMCRLC,
6554         .writefn = pmcr_write, .raw_writefn = raw_write,
6555     };
6556     define_one_arm_cp_reg(cpu, &pmcr);
6557     define_one_arm_cp_reg(cpu, &pmcr64);
6558     for (i = 0; i < pmcrn; i++) {
6559         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6560         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6561         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6562         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6563         ARMCPRegInfo pmev_regs[] = {
6564             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6565               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6566               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6567               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6568               .accessfn = pmreg_access },
6569             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6570               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6571               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6572               .type = ARM_CP_IO,
6573               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6574               .raw_readfn = pmevcntr_rawread,
6575               .raw_writefn = pmevcntr_rawwrite },
6576             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6577               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6578               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6579               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6580               .accessfn = pmreg_access },
6581             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6582               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6583               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6584               .type = ARM_CP_IO,
6585               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6586               .raw_writefn = pmevtyper_rawwrite },
6587             REGINFO_SENTINEL
6588         };
6589         define_arm_cp_regs(cpu, pmev_regs);
6590         g_free(pmevcntr_name);
6591         g_free(pmevcntr_el0_name);
6592         g_free(pmevtyper_name);
6593         g_free(pmevtyper_el0_name);
6594     }
6595     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6596         ARMCPRegInfo v81_pmu_regs[] = {
6597             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6598               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6599               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6600               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6601             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6602               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6603               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6604               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6605             REGINFO_SENTINEL
6606         };
6607         define_arm_cp_regs(cpu, v81_pmu_regs);
6608     }
6609     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6610         static const ARMCPRegInfo v84_pmmir = {
6611             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6612             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6613             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6614             .resetvalue = 0
6615         };
6616         define_one_arm_cp_reg(cpu, &v84_pmmir);
6617     }
6618 }
6619 
6620 /* We don't know until after realize whether there's a GICv3
6621  * attached, and that is what registers the gicv3 sysregs.
6622  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6623  * at runtime.
6624  */
6625 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6626 {
6627     ARMCPU *cpu = env_archcpu(env);
6628     uint64_t pfr1 = cpu->id_pfr1;
6629 
6630     if (env->gicv3state) {
6631         pfr1 |= 1 << 28;
6632     }
6633     return pfr1;
6634 }
6635 
6636 #ifndef CONFIG_USER_ONLY
6637 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6638 {
6639     ARMCPU *cpu = env_archcpu(env);
6640     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6641 
6642     if (env->gicv3state) {
6643         pfr0 |= 1 << 24;
6644     }
6645     return pfr0;
6646 }
6647 #endif
6648 
6649 /* Shared logic between LORID and the rest of the LOR* registers.
6650  * Secure state has already been delt with.
6651  */
6652 static CPAccessResult access_lor_ns(CPUARMState *env)
6653 {
6654     int el = arm_current_el(env);
6655 
6656     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6657         return CP_ACCESS_TRAP_EL2;
6658     }
6659     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6660         return CP_ACCESS_TRAP_EL3;
6661     }
6662     return CP_ACCESS_OK;
6663 }
6664 
6665 static CPAccessResult access_lorid(CPUARMState *env, const ARMCPRegInfo *ri,
6666                                    bool isread)
6667 {
6668     if (arm_is_secure_below_el3(env)) {
6669         /* Access ok in secure mode.  */
6670         return CP_ACCESS_OK;
6671     }
6672     return access_lor_ns(env);
6673 }
6674 
6675 static CPAccessResult access_lor_other(CPUARMState *env,
6676                                        const ARMCPRegInfo *ri, bool isread)
6677 {
6678     if (arm_is_secure_below_el3(env)) {
6679         /* Access denied in secure mode.  */
6680         return CP_ACCESS_TRAP;
6681     }
6682     return access_lor_ns(env);
6683 }
6684 
6685 /*
6686  * A trivial implementation of ARMv8.1-LOR leaves all of these
6687  * registers fixed at 0, which indicates that there are zero
6688  * supported Limited Ordering regions.
6689  */
6690 static const ARMCPRegInfo lor_reginfo[] = {
6691     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6692       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6693       .access = PL1_RW, .accessfn = access_lor_other,
6694       .type = ARM_CP_CONST, .resetvalue = 0 },
6695     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6696       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6697       .access = PL1_RW, .accessfn = access_lor_other,
6698       .type = ARM_CP_CONST, .resetvalue = 0 },
6699     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6700       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6701       .access = PL1_RW, .accessfn = access_lor_other,
6702       .type = ARM_CP_CONST, .resetvalue = 0 },
6703     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6704       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6705       .access = PL1_RW, .accessfn = access_lor_other,
6706       .type = ARM_CP_CONST, .resetvalue = 0 },
6707     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6708       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6709       .access = PL1_R, .accessfn = access_lorid,
6710       .type = ARM_CP_CONST, .resetvalue = 0 },
6711     REGINFO_SENTINEL
6712 };
6713 
6714 #ifdef TARGET_AARCH64
6715 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6716                                    bool isread)
6717 {
6718     int el = arm_current_el(env);
6719 
6720     if (el < 2 &&
6721         arm_feature(env, ARM_FEATURE_EL2) &&
6722         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6723         return CP_ACCESS_TRAP_EL2;
6724     }
6725     if (el < 3 &&
6726         arm_feature(env, ARM_FEATURE_EL3) &&
6727         !(env->cp15.scr_el3 & SCR_APK)) {
6728         return CP_ACCESS_TRAP_EL3;
6729     }
6730     return CP_ACCESS_OK;
6731 }
6732 
6733 static const ARMCPRegInfo pauth_reginfo[] = {
6734     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6735       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6736       .access = PL1_RW, .accessfn = access_pauth,
6737       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6738     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6739       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6740       .access = PL1_RW, .accessfn = access_pauth,
6741       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6742     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6743       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6744       .access = PL1_RW, .accessfn = access_pauth,
6745       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6746     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6747       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6748       .access = PL1_RW, .accessfn = access_pauth,
6749       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6750     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6751       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6752       .access = PL1_RW, .accessfn = access_pauth,
6753       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6754     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6755       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6756       .access = PL1_RW, .accessfn = access_pauth,
6757       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6758     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6759       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6760       .access = PL1_RW, .accessfn = access_pauth,
6761       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6762     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6763       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6764       .access = PL1_RW, .accessfn = access_pauth,
6765       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6766     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6767       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6768       .access = PL1_RW, .accessfn = access_pauth,
6769       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6770     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6771       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6772       .access = PL1_RW, .accessfn = access_pauth,
6773       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6774     REGINFO_SENTINEL
6775 };
6776 
6777 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
6778 {
6779     Error *err = NULL;
6780     uint64_t ret;
6781 
6782     /* Success sets NZCV = 0000.  */
6783     env->NF = env->CF = env->VF = 0, env->ZF = 1;
6784 
6785     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
6786         /*
6787          * ??? Failed, for unknown reasons in the crypto subsystem.
6788          * The best we can do is log the reason and return the
6789          * timed-out indication to the guest.  There is no reason
6790          * we know to expect this failure to be transitory, so the
6791          * guest may well hang retrying the operation.
6792          */
6793         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
6794                       ri->name, error_get_pretty(err));
6795         error_free(err);
6796 
6797         env->ZF = 0; /* NZCF = 0100 */
6798         return 0;
6799     }
6800     return ret;
6801 }
6802 
6803 /* We do not support re-seeding, so the two registers operate the same.  */
6804 static const ARMCPRegInfo rndr_reginfo[] = {
6805     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
6806       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6807       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
6808       .access = PL0_R, .readfn = rndr_readfn },
6809     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
6810       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6811       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
6812       .access = PL0_R, .readfn = rndr_readfn },
6813     REGINFO_SENTINEL
6814 };
6815 
6816 #ifndef CONFIG_USER_ONLY
6817 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
6818                           uint64_t value)
6819 {
6820     ARMCPU *cpu = env_archcpu(env);
6821     /* CTR_EL0 System register -> DminLine, bits [19:16] */
6822     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
6823     uint64_t vaddr_in = (uint64_t) value;
6824     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
6825     void *haddr;
6826     int mem_idx = cpu_mmu_index(env, false);
6827 
6828     /* This won't be crossing page boundaries */
6829     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
6830     if (haddr) {
6831 
6832         ram_addr_t offset;
6833         MemoryRegion *mr;
6834 
6835         /* RCU lock is already being held */
6836         mr = memory_region_from_host(haddr, &offset);
6837 
6838         if (mr) {
6839             memory_region_writeback(mr, offset, dline_size);
6840         }
6841     }
6842 }
6843 
6844 static const ARMCPRegInfo dcpop_reg[] = {
6845     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
6846       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
6847       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6848       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6849     REGINFO_SENTINEL
6850 };
6851 
6852 static const ARMCPRegInfo dcpodp_reg[] = {
6853     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
6854       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
6855       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6856       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6857     REGINFO_SENTINEL
6858 };
6859 #endif /*CONFIG_USER_ONLY*/
6860 
6861 static CPAccessResult access_aa64_tid5(CPUARMState *env, const ARMCPRegInfo *ri,
6862                                        bool isread)
6863 {
6864     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID5)) {
6865         return CP_ACCESS_TRAP_EL2;
6866     }
6867 
6868     return CP_ACCESS_OK;
6869 }
6870 
6871 static CPAccessResult access_mte(CPUARMState *env, const ARMCPRegInfo *ri,
6872                                  bool isread)
6873 {
6874     int el = arm_current_el(env);
6875 
6876     if (el < 2 &&
6877         arm_feature(env, ARM_FEATURE_EL2) &&
6878         !(arm_hcr_el2_eff(env) & HCR_ATA)) {
6879         return CP_ACCESS_TRAP_EL2;
6880     }
6881     if (el < 3 &&
6882         arm_feature(env, ARM_FEATURE_EL3) &&
6883         !(env->cp15.scr_el3 & SCR_ATA)) {
6884         return CP_ACCESS_TRAP_EL3;
6885     }
6886     return CP_ACCESS_OK;
6887 }
6888 
6889 static uint64_t tco_read(CPUARMState *env, const ARMCPRegInfo *ri)
6890 {
6891     return env->pstate & PSTATE_TCO;
6892 }
6893 
6894 static void tco_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
6895 {
6896     env->pstate = (env->pstate & ~PSTATE_TCO) | (val & PSTATE_TCO);
6897 }
6898 
6899 static const ARMCPRegInfo mte_reginfo[] = {
6900     { .name = "TFSRE0_EL1", .state = ARM_CP_STATE_AA64,
6901       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 1,
6902       .access = PL1_RW, .accessfn = access_mte,
6903       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[0]) },
6904     { .name = "TFSR_EL1", .state = ARM_CP_STATE_AA64,
6905       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 0,
6906       .access = PL1_RW, .accessfn = access_mte,
6907       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[1]) },
6908     { .name = "TFSR_EL2", .state = ARM_CP_STATE_AA64,
6909       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 6, .opc2 = 0,
6910       .access = PL2_RW, .accessfn = access_mte,
6911       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[2]) },
6912     { .name = "TFSR_EL3", .state = ARM_CP_STATE_AA64,
6913       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 6, .opc2 = 0,
6914       .access = PL3_RW,
6915       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[3]) },
6916     { .name = "RGSR_EL1", .state = ARM_CP_STATE_AA64,
6917       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 5,
6918       .access = PL1_RW, .accessfn = access_mte,
6919       .fieldoffset = offsetof(CPUARMState, cp15.rgsr_el1) },
6920     { .name = "GCR_EL1", .state = ARM_CP_STATE_AA64,
6921       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 6,
6922       .access = PL1_RW, .accessfn = access_mte,
6923       .fieldoffset = offsetof(CPUARMState, cp15.gcr_el1) },
6924     { .name = "GMID_EL1", .state = ARM_CP_STATE_AA64,
6925       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 4,
6926       .access = PL1_R, .accessfn = access_aa64_tid5,
6927       .type = ARM_CP_CONST, .resetvalue = GMID_EL1_BS },
6928     { .name = "TCO", .state = ARM_CP_STATE_AA64,
6929       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
6930       .type = ARM_CP_NO_RAW,
6931       .access = PL0_RW, .readfn = tco_read, .writefn = tco_write },
6932     { .name = "DC_IGVAC", .state = ARM_CP_STATE_AA64,
6933       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 3,
6934       .type = ARM_CP_NOP, .access = PL1_W,
6935       .accessfn = aa64_cacheop_poc_access },
6936     { .name = "DC_IGSW", .state = ARM_CP_STATE_AA64,
6937       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 4,
6938       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
6939     { .name = "DC_IGDVAC", .state = ARM_CP_STATE_AA64,
6940       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 5,
6941       .type = ARM_CP_NOP, .access = PL1_W,
6942       .accessfn = aa64_cacheop_poc_access },
6943     { .name = "DC_IGDSW", .state = ARM_CP_STATE_AA64,
6944       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 6,
6945       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
6946     { .name = "DC_CGSW", .state = ARM_CP_STATE_AA64,
6947       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 4,
6948       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
6949     { .name = "DC_CGDSW", .state = ARM_CP_STATE_AA64,
6950       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 6,
6951       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
6952     { .name = "DC_CIGSW", .state = ARM_CP_STATE_AA64,
6953       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 4,
6954       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
6955     { .name = "DC_CIGDSW", .state = ARM_CP_STATE_AA64,
6956       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 6,
6957       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
6958     REGINFO_SENTINEL
6959 };
6960 
6961 static const ARMCPRegInfo mte_tco_ro_reginfo[] = {
6962     { .name = "TCO", .state = ARM_CP_STATE_AA64,
6963       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
6964       .type = ARM_CP_CONST, .access = PL0_RW, },
6965     REGINFO_SENTINEL
6966 };
6967 
6968 static const ARMCPRegInfo mte_el0_cacheop_reginfo[] = {
6969     { .name = "DC_CGVAC", .state = ARM_CP_STATE_AA64,
6970       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 3,
6971       .type = ARM_CP_NOP, .access = PL0_W,
6972       .accessfn = aa64_cacheop_poc_access },
6973     { .name = "DC_CGDVAC", .state = ARM_CP_STATE_AA64,
6974       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 5,
6975       .type = ARM_CP_NOP, .access = PL0_W,
6976       .accessfn = aa64_cacheop_poc_access },
6977     { .name = "DC_CGVAP", .state = ARM_CP_STATE_AA64,
6978       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 3,
6979       .type = ARM_CP_NOP, .access = PL0_W,
6980       .accessfn = aa64_cacheop_poc_access },
6981     { .name = "DC_CGDVAP", .state = ARM_CP_STATE_AA64,
6982       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 5,
6983       .type = ARM_CP_NOP, .access = PL0_W,
6984       .accessfn = aa64_cacheop_poc_access },
6985     { .name = "DC_CGVADP", .state = ARM_CP_STATE_AA64,
6986       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 3,
6987       .type = ARM_CP_NOP, .access = PL0_W,
6988       .accessfn = aa64_cacheop_poc_access },
6989     { .name = "DC_CGDVADP", .state = ARM_CP_STATE_AA64,
6990       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 5,
6991       .type = ARM_CP_NOP, .access = PL0_W,
6992       .accessfn = aa64_cacheop_poc_access },
6993     { .name = "DC_CIGVAC", .state = ARM_CP_STATE_AA64,
6994       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 3,
6995       .type = ARM_CP_NOP, .access = PL0_W,
6996       .accessfn = aa64_cacheop_poc_access },
6997     { .name = "DC_CIGDVAC", .state = ARM_CP_STATE_AA64,
6998       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 5,
6999       .type = ARM_CP_NOP, .access = PL0_W,
7000       .accessfn = aa64_cacheop_poc_access },
7001     { .name = "DC_GVA", .state = ARM_CP_STATE_AA64,
7002       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 3,
7003       .access = PL0_W, .type = ARM_CP_DC_GVA,
7004 #ifndef CONFIG_USER_ONLY
7005       /* Avoid overhead of an access check that always passes in user-mode */
7006       .accessfn = aa64_zva_access,
7007 #endif
7008     },
7009     { .name = "DC_GZVA", .state = ARM_CP_STATE_AA64,
7010       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 4,
7011       .access = PL0_W, .type = ARM_CP_DC_GZVA,
7012 #ifndef CONFIG_USER_ONLY
7013       /* Avoid overhead of an access check that always passes in user-mode */
7014       .accessfn = aa64_zva_access,
7015 #endif
7016     },
7017     REGINFO_SENTINEL
7018 };
7019 
7020 #endif
7021 
7022 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
7023                                      bool isread)
7024 {
7025     int el = arm_current_el(env);
7026 
7027     if (el == 0) {
7028         uint64_t sctlr = arm_sctlr(env, el);
7029         if (!(sctlr & SCTLR_EnRCTX)) {
7030             return CP_ACCESS_TRAP;
7031         }
7032     } else if (el == 1) {
7033         uint64_t hcr = arm_hcr_el2_eff(env);
7034         if (hcr & HCR_NV) {
7035             return CP_ACCESS_TRAP_EL2;
7036         }
7037     }
7038     return CP_ACCESS_OK;
7039 }
7040 
7041 static const ARMCPRegInfo predinv_reginfo[] = {
7042     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
7043       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
7044       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7045     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
7046       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
7047       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7048     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
7049       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
7050       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7051     /*
7052      * Note the AArch32 opcodes have a different OPC1.
7053      */
7054     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
7055       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
7056       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7057     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
7058       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
7059       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7060     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
7061       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
7062       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7063     REGINFO_SENTINEL
7064 };
7065 
7066 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
7067 {
7068     /* Read the high 32 bits of the current CCSIDR */
7069     return extract64(ccsidr_read(env, ri), 32, 32);
7070 }
7071 
7072 static const ARMCPRegInfo ccsidr2_reginfo[] = {
7073     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
7074       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
7075       .access = PL1_R,
7076       .accessfn = access_aa64_tid2,
7077       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7078     REGINFO_SENTINEL
7079 };
7080 
7081 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7082                                        bool isread)
7083 {
7084     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7085         return CP_ACCESS_TRAP_EL2;
7086     }
7087 
7088     return CP_ACCESS_OK;
7089 }
7090 
7091 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7092                                        bool isread)
7093 {
7094     if (arm_feature(env, ARM_FEATURE_V8)) {
7095         return access_aa64_tid3(env, ri, isread);
7096     }
7097 
7098     return CP_ACCESS_OK;
7099 }
7100 
7101 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7102                                      bool isread)
7103 {
7104     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7105         return CP_ACCESS_TRAP_EL2;
7106     }
7107 
7108     return CP_ACCESS_OK;
7109 }
7110 
7111 static const ARMCPRegInfo jazelle_regs[] = {
7112     { .name = "JIDR",
7113       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7114       .access = PL1_R, .accessfn = access_jazelle,
7115       .type = ARM_CP_CONST, .resetvalue = 0 },
7116     { .name = "JOSCR",
7117       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7118       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7119     { .name = "JMCR",
7120       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7121       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7122     REGINFO_SENTINEL
7123 };
7124 
7125 static const ARMCPRegInfo vhe_reginfo[] = {
7126     { .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7127       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7128       .access = PL2_RW,
7129       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2]) },
7130     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7131       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7132       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7133       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7134 #ifndef CONFIG_USER_ONLY
7135     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7136       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7137       .fieldoffset =
7138         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7139       .type = ARM_CP_IO, .access = PL2_RW,
7140       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7141     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7142       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7143       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7144       .resetfn = gt_hv_timer_reset,
7145       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7146     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7147       .type = ARM_CP_IO,
7148       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7149       .access = PL2_RW,
7150       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7151       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7152     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7153       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7154       .type = ARM_CP_IO | ARM_CP_ALIAS,
7155       .access = PL2_RW, .accessfn = e2h_access,
7156       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7157       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7158     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7159       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7160       .type = ARM_CP_IO | ARM_CP_ALIAS,
7161       .access = PL2_RW, .accessfn = e2h_access,
7162       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7163       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7164     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7165       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7166       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7167       .access = PL2_RW, .accessfn = e2h_access,
7168       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7169     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7170       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7171       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7172       .access = PL2_RW, .accessfn = e2h_access,
7173       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7174     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7175       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7176       .type = ARM_CP_IO | ARM_CP_ALIAS,
7177       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7178       .access = PL2_RW, .accessfn = e2h_access,
7179       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7180     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7181       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7182       .type = ARM_CP_IO | ARM_CP_ALIAS,
7183       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7184       .access = PL2_RW, .accessfn = e2h_access,
7185       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7186 #endif
7187     REGINFO_SENTINEL
7188 };
7189 
7190 #ifndef CONFIG_USER_ONLY
7191 static const ARMCPRegInfo ats1e1_reginfo[] = {
7192     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7193       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7194       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7195       .writefn = ats_write64 },
7196     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7197       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7198       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7199       .writefn = ats_write64 },
7200     REGINFO_SENTINEL
7201 };
7202 
7203 static const ARMCPRegInfo ats1cp_reginfo[] = {
7204     { .name = "ATS1CPRP",
7205       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7206       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7207       .writefn = ats_write },
7208     { .name = "ATS1CPWP",
7209       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7210       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7211       .writefn = ats_write },
7212     REGINFO_SENTINEL
7213 };
7214 #endif
7215 
7216 /*
7217  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7218  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7219  * is non-zero, which is never for ARMv7, optionally in ARMv8
7220  * and mandatorily for ARMv8.2 and up.
7221  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7222  * implementation is RAZ/WI we can ignore this detail, as we
7223  * do for ACTLR.
7224  */
7225 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7226     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7227       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7228       .access = PL1_RW, .accessfn = access_tacr,
7229       .type = ARM_CP_CONST, .resetvalue = 0 },
7230     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7231       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7232       .access = PL2_RW, .type = ARM_CP_CONST,
7233       .resetvalue = 0 },
7234     REGINFO_SENTINEL
7235 };
7236 
7237 void register_cp_regs_for_features(ARMCPU *cpu)
7238 {
7239     /* Register all the coprocessor registers based on feature bits */
7240     CPUARMState *env = &cpu->env;
7241     if (arm_feature(env, ARM_FEATURE_M)) {
7242         /* M profile has no coprocessor registers */
7243         return;
7244     }
7245 
7246     define_arm_cp_regs(cpu, cp_reginfo);
7247     if (!arm_feature(env, ARM_FEATURE_V8)) {
7248         /* Must go early as it is full of wildcards that may be
7249          * overridden by later definitions.
7250          */
7251         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7252     }
7253 
7254     if (arm_feature(env, ARM_FEATURE_V6)) {
7255         /* The ID registers all have impdef reset values */
7256         ARMCPRegInfo v6_idregs[] = {
7257             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7258               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7259               .access = PL1_R, .type = ARM_CP_CONST,
7260               .accessfn = access_aa32_tid3,
7261               .resetvalue = cpu->id_pfr0 },
7262             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7263              * the value of the GIC field until after we define these regs.
7264              */
7265             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7266               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7267               .access = PL1_R, .type = ARM_CP_NO_RAW,
7268               .accessfn = access_aa32_tid3,
7269               .readfn = id_pfr1_read,
7270               .writefn = arm_cp_write_ignore },
7271             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7272               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7273               .access = PL1_R, .type = ARM_CP_CONST,
7274               .accessfn = access_aa32_tid3,
7275               .resetvalue = cpu->isar.id_dfr0 },
7276             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7277               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7278               .access = PL1_R, .type = ARM_CP_CONST,
7279               .accessfn = access_aa32_tid3,
7280               .resetvalue = cpu->id_afr0 },
7281             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7282               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7283               .access = PL1_R, .type = ARM_CP_CONST,
7284               .accessfn = access_aa32_tid3,
7285               .resetvalue = cpu->isar.id_mmfr0 },
7286             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7287               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7288               .access = PL1_R, .type = ARM_CP_CONST,
7289               .accessfn = access_aa32_tid3,
7290               .resetvalue = cpu->isar.id_mmfr1 },
7291             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7292               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7293               .access = PL1_R, .type = ARM_CP_CONST,
7294               .accessfn = access_aa32_tid3,
7295               .resetvalue = cpu->isar.id_mmfr2 },
7296             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7297               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7298               .access = PL1_R, .type = ARM_CP_CONST,
7299               .accessfn = access_aa32_tid3,
7300               .resetvalue = cpu->isar.id_mmfr3 },
7301             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7302               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7303               .access = PL1_R, .type = ARM_CP_CONST,
7304               .accessfn = access_aa32_tid3,
7305               .resetvalue = cpu->isar.id_isar0 },
7306             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7307               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7308               .access = PL1_R, .type = ARM_CP_CONST,
7309               .accessfn = access_aa32_tid3,
7310               .resetvalue = cpu->isar.id_isar1 },
7311             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7312               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7313               .access = PL1_R, .type = ARM_CP_CONST,
7314               .accessfn = access_aa32_tid3,
7315               .resetvalue = cpu->isar.id_isar2 },
7316             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7317               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7318               .access = PL1_R, .type = ARM_CP_CONST,
7319               .accessfn = access_aa32_tid3,
7320               .resetvalue = cpu->isar.id_isar3 },
7321             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7322               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7323               .access = PL1_R, .type = ARM_CP_CONST,
7324               .accessfn = access_aa32_tid3,
7325               .resetvalue = cpu->isar.id_isar4 },
7326             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7327               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7328               .access = PL1_R, .type = ARM_CP_CONST,
7329               .accessfn = access_aa32_tid3,
7330               .resetvalue = cpu->isar.id_isar5 },
7331             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7332               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7333               .access = PL1_R, .type = ARM_CP_CONST,
7334               .accessfn = access_aa32_tid3,
7335               .resetvalue = cpu->isar.id_mmfr4 },
7336             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7337               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7338               .access = PL1_R, .type = ARM_CP_CONST,
7339               .accessfn = access_aa32_tid3,
7340               .resetvalue = cpu->isar.id_isar6 },
7341             REGINFO_SENTINEL
7342         };
7343         define_arm_cp_regs(cpu, v6_idregs);
7344         define_arm_cp_regs(cpu, v6_cp_reginfo);
7345     } else {
7346         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7347     }
7348     if (arm_feature(env, ARM_FEATURE_V6K)) {
7349         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7350     }
7351     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7352         !arm_feature(env, ARM_FEATURE_PMSA)) {
7353         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7354     }
7355     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7356         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7357     }
7358     if (arm_feature(env, ARM_FEATURE_V7)) {
7359         ARMCPRegInfo clidr = {
7360             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7361             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7362             .access = PL1_R, .type = ARM_CP_CONST,
7363             .accessfn = access_aa64_tid2,
7364             .resetvalue = cpu->clidr
7365         };
7366         define_one_arm_cp_reg(cpu, &clidr);
7367         define_arm_cp_regs(cpu, v7_cp_reginfo);
7368         define_debug_regs(cpu);
7369         define_pmu_regs(cpu);
7370     } else {
7371         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7372     }
7373     if (arm_feature(env, ARM_FEATURE_V8)) {
7374         /* AArch64 ID registers, which all have impdef reset values.
7375          * Note that within the ID register ranges the unused slots
7376          * must all RAZ, not UNDEF; future architecture versions may
7377          * define new registers here.
7378          */
7379         ARMCPRegInfo v8_idregs[] = {
7380             /*
7381              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7382              * emulation because we don't know the right value for the
7383              * GIC field until after we define these regs.
7384              */
7385             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7386               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7387               .access = PL1_R,
7388 #ifdef CONFIG_USER_ONLY
7389               .type = ARM_CP_CONST,
7390               .resetvalue = cpu->isar.id_aa64pfr0
7391 #else
7392               .type = ARM_CP_NO_RAW,
7393               .accessfn = access_aa64_tid3,
7394               .readfn = id_aa64pfr0_read,
7395               .writefn = arm_cp_write_ignore
7396 #endif
7397             },
7398             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7399               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7400               .access = PL1_R, .type = ARM_CP_CONST,
7401               .accessfn = access_aa64_tid3,
7402               .resetvalue = cpu->isar.id_aa64pfr1},
7403             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7404               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7405               .access = PL1_R, .type = ARM_CP_CONST,
7406               .accessfn = access_aa64_tid3,
7407               .resetvalue = 0 },
7408             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7409               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7410               .access = PL1_R, .type = ARM_CP_CONST,
7411               .accessfn = access_aa64_tid3,
7412               .resetvalue = 0 },
7413             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7414               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7415               .access = PL1_R, .type = ARM_CP_CONST,
7416               .accessfn = access_aa64_tid3,
7417               /* At present, only SVEver == 0 is defined anyway.  */
7418               .resetvalue = 0 },
7419             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7420               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7421               .access = PL1_R, .type = ARM_CP_CONST,
7422               .accessfn = access_aa64_tid3,
7423               .resetvalue = 0 },
7424             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7425               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7426               .access = PL1_R, .type = ARM_CP_CONST,
7427               .accessfn = access_aa64_tid3,
7428               .resetvalue = 0 },
7429             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7430               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7431               .access = PL1_R, .type = ARM_CP_CONST,
7432               .accessfn = access_aa64_tid3,
7433               .resetvalue = 0 },
7434             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7435               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7436               .access = PL1_R, .type = ARM_CP_CONST,
7437               .accessfn = access_aa64_tid3,
7438               .resetvalue = cpu->isar.id_aa64dfr0 },
7439             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7440               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7441               .access = PL1_R, .type = ARM_CP_CONST,
7442               .accessfn = access_aa64_tid3,
7443               .resetvalue = cpu->isar.id_aa64dfr1 },
7444             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7445               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7446               .access = PL1_R, .type = ARM_CP_CONST,
7447               .accessfn = access_aa64_tid3,
7448               .resetvalue = 0 },
7449             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7450               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7451               .access = PL1_R, .type = ARM_CP_CONST,
7452               .accessfn = access_aa64_tid3,
7453               .resetvalue = 0 },
7454             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7455               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7456               .access = PL1_R, .type = ARM_CP_CONST,
7457               .accessfn = access_aa64_tid3,
7458               .resetvalue = cpu->id_aa64afr0 },
7459             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7460               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7461               .access = PL1_R, .type = ARM_CP_CONST,
7462               .accessfn = access_aa64_tid3,
7463               .resetvalue = cpu->id_aa64afr1 },
7464             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7465               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7466               .access = PL1_R, .type = ARM_CP_CONST,
7467               .accessfn = access_aa64_tid3,
7468               .resetvalue = 0 },
7469             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7470               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7471               .access = PL1_R, .type = ARM_CP_CONST,
7472               .accessfn = access_aa64_tid3,
7473               .resetvalue = 0 },
7474             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7475               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7476               .access = PL1_R, .type = ARM_CP_CONST,
7477               .accessfn = access_aa64_tid3,
7478               .resetvalue = cpu->isar.id_aa64isar0 },
7479             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7480               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7481               .access = PL1_R, .type = ARM_CP_CONST,
7482               .accessfn = access_aa64_tid3,
7483               .resetvalue = cpu->isar.id_aa64isar1 },
7484             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7485               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7486               .access = PL1_R, .type = ARM_CP_CONST,
7487               .accessfn = access_aa64_tid3,
7488               .resetvalue = 0 },
7489             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7490               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7491               .access = PL1_R, .type = ARM_CP_CONST,
7492               .accessfn = access_aa64_tid3,
7493               .resetvalue = 0 },
7494             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7495               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7496               .access = PL1_R, .type = ARM_CP_CONST,
7497               .accessfn = access_aa64_tid3,
7498               .resetvalue = 0 },
7499             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7500               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7501               .access = PL1_R, .type = ARM_CP_CONST,
7502               .accessfn = access_aa64_tid3,
7503               .resetvalue = 0 },
7504             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7505               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7506               .access = PL1_R, .type = ARM_CP_CONST,
7507               .accessfn = access_aa64_tid3,
7508               .resetvalue = 0 },
7509             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7510               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7511               .access = PL1_R, .type = ARM_CP_CONST,
7512               .accessfn = access_aa64_tid3,
7513               .resetvalue = 0 },
7514             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7515               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7516               .access = PL1_R, .type = ARM_CP_CONST,
7517               .accessfn = access_aa64_tid3,
7518               .resetvalue = cpu->isar.id_aa64mmfr0 },
7519             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7520               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7521               .access = PL1_R, .type = ARM_CP_CONST,
7522               .accessfn = access_aa64_tid3,
7523               .resetvalue = cpu->isar.id_aa64mmfr1 },
7524             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7525               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7526               .access = PL1_R, .type = ARM_CP_CONST,
7527               .accessfn = access_aa64_tid3,
7528               .resetvalue = cpu->isar.id_aa64mmfr2 },
7529             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7530               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7531               .access = PL1_R, .type = ARM_CP_CONST,
7532               .accessfn = access_aa64_tid3,
7533               .resetvalue = 0 },
7534             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7535               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7536               .access = PL1_R, .type = ARM_CP_CONST,
7537               .accessfn = access_aa64_tid3,
7538               .resetvalue = 0 },
7539             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7540               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7541               .access = PL1_R, .type = ARM_CP_CONST,
7542               .accessfn = access_aa64_tid3,
7543               .resetvalue = 0 },
7544             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7545               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7546               .access = PL1_R, .type = ARM_CP_CONST,
7547               .accessfn = access_aa64_tid3,
7548               .resetvalue = 0 },
7549             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7550               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7551               .access = PL1_R, .type = ARM_CP_CONST,
7552               .accessfn = access_aa64_tid3,
7553               .resetvalue = 0 },
7554             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7555               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7556               .access = PL1_R, .type = ARM_CP_CONST,
7557               .accessfn = access_aa64_tid3,
7558               .resetvalue = cpu->isar.mvfr0 },
7559             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7560               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7561               .access = PL1_R, .type = ARM_CP_CONST,
7562               .accessfn = access_aa64_tid3,
7563               .resetvalue = cpu->isar.mvfr1 },
7564             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7565               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7566               .access = PL1_R, .type = ARM_CP_CONST,
7567               .accessfn = access_aa64_tid3,
7568               .resetvalue = cpu->isar.mvfr2 },
7569             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7570               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7571               .access = PL1_R, .type = ARM_CP_CONST,
7572               .accessfn = access_aa64_tid3,
7573               .resetvalue = 0 },
7574             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7575               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7576               .access = PL1_R, .type = ARM_CP_CONST,
7577               .accessfn = access_aa64_tid3,
7578               .resetvalue = 0 },
7579             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7580               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7581               .access = PL1_R, .type = ARM_CP_CONST,
7582               .accessfn = access_aa64_tid3,
7583               .resetvalue = 0 },
7584             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7585               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7586               .access = PL1_R, .type = ARM_CP_CONST,
7587               .accessfn = access_aa64_tid3,
7588               .resetvalue = 0 },
7589             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7590               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7591               .access = PL1_R, .type = ARM_CP_CONST,
7592               .accessfn = access_aa64_tid3,
7593               .resetvalue = 0 },
7594             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7595               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7596               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7597               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7598             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7599               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7600               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7601               .resetvalue = cpu->pmceid0 },
7602             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7603               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7604               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7605               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7606             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7607               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7608               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7609               .resetvalue = cpu->pmceid1 },
7610             REGINFO_SENTINEL
7611         };
7612 #ifdef CONFIG_USER_ONLY
7613         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7614             { .name = "ID_AA64PFR0_EL1",
7615               .exported_bits = 0x000f000f00ff0000,
7616               .fixed_bits    = 0x0000000000000011 },
7617             { .name = "ID_AA64PFR1_EL1",
7618               .exported_bits = 0x00000000000000f0 },
7619             { .name = "ID_AA64PFR*_EL1_RESERVED",
7620               .is_glob = true                     },
7621             { .name = "ID_AA64ZFR0_EL1"           },
7622             { .name = "ID_AA64MMFR0_EL1",
7623               .fixed_bits    = 0x00000000ff000000 },
7624             { .name = "ID_AA64MMFR1_EL1"          },
7625             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7626               .is_glob = true                     },
7627             { .name = "ID_AA64DFR0_EL1",
7628               .fixed_bits    = 0x0000000000000006 },
7629             { .name = "ID_AA64DFR1_EL1"           },
7630             { .name = "ID_AA64DFR*_EL1_RESERVED",
7631               .is_glob = true                     },
7632             { .name = "ID_AA64AFR*",
7633               .is_glob = true                     },
7634             { .name = "ID_AA64ISAR0_EL1",
7635               .exported_bits = 0x00fffffff0fffff0 },
7636             { .name = "ID_AA64ISAR1_EL1",
7637               .exported_bits = 0x000000f0ffffffff },
7638             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7639               .is_glob = true                     },
7640             REGUSERINFO_SENTINEL
7641         };
7642         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7643 #endif
7644         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7645         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7646             !arm_feature(env, ARM_FEATURE_EL2)) {
7647             ARMCPRegInfo rvbar = {
7648                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7649                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7650                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
7651             };
7652             define_one_arm_cp_reg(cpu, &rvbar);
7653         }
7654         define_arm_cp_regs(cpu, v8_idregs);
7655         define_arm_cp_regs(cpu, v8_cp_reginfo);
7656     }
7657     if (arm_feature(env, ARM_FEATURE_EL2)) {
7658         uint64_t vmpidr_def = mpidr_read_val(env);
7659         ARMCPRegInfo vpidr_regs[] = {
7660             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7661               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7662               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7663               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
7664               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7665             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7666               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7667               .access = PL2_RW, .resetvalue = cpu->midr,
7668               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7669             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7670               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7671               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7672               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
7673               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7674             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7675               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7676               .access = PL2_RW,
7677               .resetvalue = vmpidr_def,
7678               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7679             REGINFO_SENTINEL
7680         };
7681         define_arm_cp_regs(cpu, vpidr_regs);
7682         define_arm_cp_regs(cpu, el2_cp_reginfo);
7683         if (arm_feature(env, ARM_FEATURE_V8)) {
7684             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
7685         }
7686         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
7687         if (!arm_feature(env, ARM_FEATURE_EL3)) {
7688             ARMCPRegInfo rvbar = {
7689                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
7690                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
7691                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
7692             };
7693             define_one_arm_cp_reg(cpu, &rvbar);
7694         }
7695     } else {
7696         /* If EL2 is missing but higher ELs are enabled, we need to
7697          * register the no_el2 reginfos.
7698          */
7699         if (arm_feature(env, ARM_FEATURE_EL3)) {
7700             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
7701              * of MIDR_EL1 and MPIDR_EL1.
7702              */
7703             ARMCPRegInfo vpidr_regs[] = {
7704                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7705                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7706                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
7707                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
7708                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7709                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7710                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7711                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
7712                   .type = ARM_CP_NO_RAW,
7713                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
7714                 REGINFO_SENTINEL
7715             };
7716             define_arm_cp_regs(cpu, vpidr_regs);
7717             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
7718             if (arm_feature(env, ARM_FEATURE_V8)) {
7719                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
7720             }
7721         }
7722     }
7723     if (arm_feature(env, ARM_FEATURE_EL3)) {
7724         define_arm_cp_regs(cpu, el3_cp_reginfo);
7725         ARMCPRegInfo el3_regs[] = {
7726             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
7727               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
7728               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
7729             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
7730               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
7731               .access = PL3_RW,
7732               .raw_writefn = raw_write, .writefn = sctlr_write,
7733               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
7734               .resetvalue = cpu->reset_sctlr },
7735             REGINFO_SENTINEL
7736         };
7737 
7738         define_arm_cp_regs(cpu, el3_regs);
7739     }
7740     /* The behaviour of NSACR is sufficiently various that we don't
7741      * try to describe it in a single reginfo:
7742      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
7743      *     reads as constant 0xc00 from NS EL1 and NS EL2
7744      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
7745      *  if v7 without EL3, register doesn't exist
7746      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
7747      */
7748     if (arm_feature(env, ARM_FEATURE_EL3)) {
7749         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7750             ARMCPRegInfo nsacr = {
7751                 .name = "NSACR", .type = ARM_CP_CONST,
7752                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7753                 .access = PL1_RW, .accessfn = nsacr_access,
7754                 .resetvalue = 0xc00
7755             };
7756             define_one_arm_cp_reg(cpu, &nsacr);
7757         } else {
7758             ARMCPRegInfo nsacr = {
7759                 .name = "NSACR",
7760                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7761                 .access = PL3_RW | PL1_R,
7762                 .resetvalue = 0,
7763                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
7764             };
7765             define_one_arm_cp_reg(cpu, &nsacr);
7766         }
7767     } else {
7768         if (arm_feature(env, ARM_FEATURE_V8)) {
7769             ARMCPRegInfo nsacr = {
7770                 .name = "NSACR", .type = ARM_CP_CONST,
7771                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7772                 .access = PL1_R,
7773                 .resetvalue = 0xc00
7774             };
7775             define_one_arm_cp_reg(cpu, &nsacr);
7776         }
7777     }
7778 
7779     if (arm_feature(env, ARM_FEATURE_PMSA)) {
7780         if (arm_feature(env, ARM_FEATURE_V6)) {
7781             /* PMSAv6 not implemented */
7782             assert(arm_feature(env, ARM_FEATURE_V7));
7783             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7784             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
7785         } else {
7786             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
7787         }
7788     } else {
7789         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7790         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
7791         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
7792         if (cpu_isar_feature(aa32_hpd, cpu)) {
7793             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
7794         }
7795     }
7796     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
7797         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
7798     }
7799     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
7800         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
7801     }
7802     if (arm_feature(env, ARM_FEATURE_VAPA)) {
7803         define_arm_cp_regs(cpu, vapa_cp_reginfo);
7804     }
7805     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
7806         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
7807     }
7808     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
7809         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
7810     }
7811     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
7812         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
7813     }
7814     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
7815         define_arm_cp_regs(cpu, omap_cp_reginfo);
7816     }
7817     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
7818         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
7819     }
7820     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
7821         define_arm_cp_regs(cpu, xscale_cp_reginfo);
7822     }
7823     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
7824         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
7825     }
7826     if (arm_feature(env, ARM_FEATURE_LPAE)) {
7827         define_arm_cp_regs(cpu, lpae_cp_reginfo);
7828     }
7829     if (cpu_isar_feature(aa32_jazelle, cpu)) {
7830         define_arm_cp_regs(cpu, jazelle_regs);
7831     }
7832     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
7833      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
7834      * be read-only (ie write causes UNDEF exception).
7835      */
7836     {
7837         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
7838             /* Pre-v8 MIDR space.
7839              * Note that the MIDR isn't a simple constant register because
7840              * of the TI925 behaviour where writes to another register can
7841              * cause the MIDR value to change.
7842              *
7843              * Unimplemented registers in the c15 0 0 0 space default to
7844              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
7845              * and friends override accordingly.
7846              */
7847             { .name = "MIDR",
7848               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
7849               .access = PL1_R, .resetvalue = cpu->midr,
7850               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
7851               .readfn = midr_read,
7852               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7853               .type = ARM_CP_OVERRIDE },
7854             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
7855             { .name = "DUMMY",
7856               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
7857               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7858             { .name = "DUMMY",
7859               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
7860               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7861             { .name = "DUMMY",
7862               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
7863               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7864             { .name = "DUMMY",
7865               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
7866               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7867             { .name = "DUMMY",
7868               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
7869               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7870             REGINFO_SENTINEL
7871         };
7872         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
7873             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
7874               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
7875               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
7876               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7877               .readfn = midr_read },
7878             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
7879             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
7880               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
7881               .access = PL1_R, .resetvalue = cpu->midr },
7882             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
7883               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
7884               .access = PL1_R, .resetvalue = cpu->midr },
7885             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
7886               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
7887               .access = PL1_R,
7888               .accessfn = access_aa64_tid1,
7889               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
7890             REGINFO_SENTINEL
7891         };
7892         ARMCPRegInfo id_cp_reginfo[] = {
7893             /* These are common to v8 and pre-v8 */
7894             { .name = "CTR",
7895               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
7896               .access = PL1_R, .accessfn = ctr_el0_access,
7897               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
7898             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
7899               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
7900               .access = PL0_R, .accessfn = ctr_el0_access,
7901               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
7902             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
7903             { .name = "TCMTR",
7904               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
7905               .access = PL1_R,
7906               .accessfn = access_aa32_tid1,
7907               .type = ARM_CP_CONST, .resetvalue = 0 },
7908             REGINFO_SENTINEL
7909         };
7910         /* TLBTR is specific to VMSA */
7911         ARMCPRegInfo id_tlbtr_reginfo = {
7912               .name = "TLBTR",
7913               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
7914               .access = PL1_R,
7915               .accessfn = access_aa32_tid1,
7916               .type = ARM_CP_CONST, .resetvalue = 0,
7917         };
7918         /* MPUIR is specific to PMSA V6+ */
7919         ARMCPRegInfo id_mpuir_reginfo = {
7920               .name = "MPUIR",
7921               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
7922               .access = PL1_R, .type = ARM_CP_CONST,
7923               .resetvalue = cpu->pmsav7_dregion << 8
7924         };
7925         ARMCPRegInfo crn0_wi_reginfo = {
7926             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
7927             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
7928             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
7929         };
7930 #ifdef CONFIG_USER_ONLY
7931         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
7932             { .name = "MIDR_EL1",
7933               .exported_bits = 0x00000000ffffffff },
7934             { .name = "REVIDR_EL1"                },
7935             REGUSERINFO_SENTINEL
7936         };
7937         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
7938 #endif
7939         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
7940             arm_feature(env, ARM_FEATURE_STRONGARM)) {
7941             ARMCPRegInfo *r;
7942             /* Register the blanket "writes ignored" value first to cover the
7943              * whole space. Then update the specific ID registers to allow write
7944              * access, so that they ignore writes rather than causing them to
7945              * UNDEF.
7946              */
7947             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
7948             for (r = id_pre_v8_midr_cp_reginfo;
7949                  r->type != ARM_CP_SENTINEL; r++) {
7950                 r->access = PL1_RW;
7951             }
7952             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
7953                 r->access = PL1_RW;
7954             }
7955             id_mpuir_reginfo.access = PL1_RW;
7956             id_tlbtr_reginfo.access = PL1_RW;
7957         }
7958         if (arm_feature(env, ARM_FEATURE_V8)) {
7959             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
7960         } else {
7961             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
7962         }
7963         define_arm_cp_regs(cpu, id_cp_reginfo);
7964         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
7965             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
7966         } else if (arm_feature(env, ARM_FEATURE_V7)) {
7967             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
7968         }
7969     }
7970 
7971     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
7972         ARMCPRegInfo mpidr_cp_reginfo[] = {
7973             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
7974               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
7975               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
7976             REGINFO_SENTINEL
7977         };
7978 #ifdef CONFIG_USER_ONLY
7979         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
7980             { .name = "MPIDR_EL1",
7981               .fixed_bits = 0x0000000080000000 },
7982             REGUSERINFO_SENTINEL
7983         };
7984         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
7985 #endif
7986         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
7987     }
7988 
7989     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
7990         ARMCPRegInfo auxcr_reginfo[] = {
7991             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
7992               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
7993               .access = PL1_RW, .accessfn = access_tacr,
7994               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
7995             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
7996               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
7997               .access = PL2_RW, .type = ARM_CP_CONST,
7998               .resetvalue = 0 },
7999             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
8000               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
8001               .access = PL3_RW, .type = ARM_CP_CONST,
8002               .resetvalue = 0 },
8003             REGINFO_SENTINEL
8004         };
8005         define_arm_cp_regs(cpu, auxcr_reginfo);
8006         if (cpu_isar_feature(aa32_ac2, cpu)) {
8007             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
8008         }
8009     }
8010 
8011     if (arm_feature(env, ARM_FEATURE_CBAR)) {
8012         /*
8013          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
8014          * There are two flavours:
8015          *  (1) older 32-bit only cores have a simple 32-bit CBAR
8016          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
8017          *      32-bit register visible to AArch32 at a different encoding
8018          *      to the "flavour 1" register and with the bits rearranged to
8019          *      be able to squash a 64-bit address into the 32-bit view.
8020          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
8021          * in future if we support AArch32-only configs of some of the
8022          * AArch64 cores we might need to add a specific feature flag
8023          * to indicate cores with "flavour 2" CBAR.
8024          */
8025         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8026             /* 32 bit view is [31:18] 0...0 [43:32]. */
8027             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
8028                 | extract64(cpu->reset_cbar, 32, 12);
8029             ARMCPRegInfo cbar_reginfo[] = {
8030                 { .name = "CBAR",
8031                   .type = ARM_CP_CONST,
8032                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
8033                   .access = PL1_R, .resetvalue = cbar32 },
8034                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
8035                   .type = ARM_CP_CONST,
8036                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
8037                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
8038                 REGINFO_SENTINEL
8039             };
8040             /* We don't implement a r/w 64 bit CBAR currently */
8041             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
8042             define_arm_cp_regs(cpu, cbar_reginfo);
8043         } else {
8044             ARMCPRegInfo cbar = {
8045                 .name = "CBAR",
8046                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
8047                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
8048                 .fieldoffset = offsetof(CPUARMState,
8049                                         cp15.c15_config_base_address)
8050             };
8051             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
8052                 cbar.access = PL1_R;
8053                 cbar.fieldoffset = 0;
8054                 cbar.type = ARM_CP_CONST;
8055             }
8056             define_one_arm_cp_reg(cpu, &cbar);
8057         }
8058     }
8059 
8060     if (arm_feature(env, ARM_FEATURE_VBAR)) {
8061         ARMCPRegInfo vbar_cp_reginfo[] = {
8062             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
8063               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
8064               .access = PL1_RW, .writefn = vbar_write,
8065               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
8066                                      offsetof(CPUARMState, cp15.vbar_ns) },
8067               .resetvalue = 0 },
8068             REGINFO_SENTINEL
8069         };
8070         define_arm_cp_regs(cpu, vbar_cp_reginfo);
8071     }
8072 
8073     /* Generic registers whose values depend on the implementation */
8074     {
8075         ARMCPRegInfo sctlr = {
8076             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8077             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8078             .access = PL1_RW, .accessfn = access_tvm_trvm,
8079             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8080                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8081             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8082             .raw_writefn = raw_write,
8083         };
8084         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8085             /* Normally we would always end the TB on an SCTLR write, but Linux
8086              * arch/arm/mach-pxa/sleep.S expects two instructions following
8087              * an MMU enable to execute from cache.  Imitate this behaviour.
8088              */
8089             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8090         }
8091         define_one_arm_cp_reg(cpu, &sctlr);
8092     }
8093 
8094     if (cpu_isar_feature(aa64_lor, cpu)) {
8095         define_arm_cp_regs(cpu, lor_reginfo);
8096     }
8097     if (cpu_isar_feature(aa64_pan, cpu)) {
8098         define_one_arm_cp_reg(cpu, &pan_reginfo);
8099     }
8100 #ifndef CONFIG_USER_ONLY
8101     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8102         define_arm_cp_regs(cpu, ats1e1_reginfo);
8103     }
8104     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8105         define_arm_cp_regs(cpu, ats1cp_reginfo);
8106     }
8107 #endif
8108     if (cpu_isar_feature(aa64_uao, cpu)) {
8109         define_one_arm_cp_reg(cpu, &uao_reginfo);
8110     }
8111 
8112     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8113         define_arm_cp_regs(cpu, vhe_reginfo);
8114     }
8115 
8116     if (cpu_isar_feature(aa64_sve, cpu)) {
8117         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
8118         if (arm_feature(env, ARM_FEATURE_EL2)) {
8119             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
8120         } else {
8121             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
8122         }
8123         if (arm_feature(env, ARM_FEATURE_EL3)) {
8124             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
8125         }
8126     }
8127 
8128 #ifdef TARGET_AARCH64
8129     if (cpu_isar_feature(aa64_pauth, cpu)) {
8130         define_arm_cp_regs(cpu, pauth_reginfo);
8131     }
8132     if (cpu_isar_feature(aa64_rndr, cpu)) {
8133         define_arm_cp_regs(cpu, rndr_reginfo);
8134     }
8135 #ifndef CONFIG_USER_ONLY
8136     /* Data Cache clean instructions up to PoP */
8137     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8138         define_one_arm_cp_reg(cpu, dcpop_reg);
8139 
8140         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8141             define_one_arm_cp_reg(cpu, dcpodp_reg);
8142         }
8143     }
8144 #endif /*CONFIG_USER_ONLY*/
8145 
8146     /*
8147      * If full MTE is enabled, add all of the system registers.
8148      * If only "instructions available at EL0" are enabled,
8149      * then define only a RAZ/WI version of PSTATE.TCO.
8150      */
8151     if (cpu_isar_feature(aa64_mte, cpu)) {
8152         define_arm_cp_regs(cpu, mte_reginfo);
8153         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8154     } else if (cpu_isar_feature(aa64_mte_insn_reg, cpu)) {
8155         define_arm_cp_regs(cpu, mte_tco_ro_reginfo);
8156         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8157     }
8158 #endif
8159 
8160     if (cpu_isar_feature(any_predinv, cpu)) {
8161         define_arm_cp_regs(cpu, predinv_reginfo);
8162     }
8163 
8164     if (cpu_isar_feature(any_ccidx, cpu)) {
8165         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8166     }
8167 
8168 #ifndef CONFIG_USER_ONLY
8169     /*
8170      * Register redirections and aliases must be done last,
8171      * after the registers from the other extensions have been defined.
8172      */
8173     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8174         define_arm_vh_e2h_redirects_aliases(cpu);
8175     }
8176 #endif
8177 }
8178 
8179 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
8180 {
8181     CPUState *cs = CPU(cpu);
8182     CPUARMState *env = &cpu->env;
8183 
8184     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8185         /*
8186          * The lower part of each SVE register aliases to the FPU
8187          * registers so we don't need to include both.
8188          */
8189 #ifdef TARGET_AARCH64
8190         if (isar_feature_aa64_sve(&cpu->isar)) {
8191             gdb_register_coprocessor(cs, arm_gdb_get_svereg, arm_gdb_set_svereg,
8192                                      arm_gen_dynamic_svereg_xml(cs, cs->gdb_num_regs),
8193                                      "sve-registers.xml", 0);
8194         } else
8195 #endif
8196         {
8197             gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
8198                                      aarch64_fpu_gdb_set_reg,
8199                                      34, "aarch64-fpu.xml", 0);
8200         }
8201     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
8202         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8203                                  51, "arm-neon.xml", 0);
8204     } else if (cpu_isar_feature(aa32_simd_r32, cpu)) {
8205         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8206                                  35, "arm-vfp3.xml", 0);
8207     } else if (cpu_isar_feature(aa32_vfp_simd, cpu)) {
8208         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8209                                  19, "arm-vfp.xml", 0);
8210     }
8211     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
8212                              arm_gen_dynamic_sysreg_xml(cs, cs->gdb_num_regs),
8213                              "system-registers.xml", 0);
8214 
8215 }
8216 
8217 /* Sort alphabetically by type name, except for "any". */
8218 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8219 {
8220     ObjectClass *class_a = (ObjectClass *)a;
8221     ObjectClass *class_b = (ObjectClass *)b;
8222     const char *name_a, *name_b;
8223 
8224     name_a = object_class_get_name(class_a);
8225     name_b = object_class_get_name(class_b);
8226     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8227         return 1;
8228     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8229         return -1;
8230     } else {
8231         return strcmp(name_a, name_b);
8232     }
8233 }
8234 
8235 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8236 {
8237     ObjectClass *oc = data;
8238     const char *typename;
8239     char *name;
8240 
8241     typename = object_class_get_name(oc);
8242     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8243     qemu_printf("  %s\n", name);
8244     g_free(name);
8245 }
8246 
8247 void arm_cpu_list(void)
8248 {
8249     GSList *list;
8250 
8251     list = object_class_get_list(TYPE_ARM_CPU, false);
8252     list = g_slist_sort(list, arm_cpu_list_compare);
8253     qemu_printf("Available CPUs:\n");
8254     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8255     g_slist_free(list);
8256 }
8257 
8258 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8259 {
8260     ObjectClass *oc = data;
8261     CpuDefinitionInfoList **cpu_list = user_data;
8262     CpuDefinitionInfoList *entry;
8263     CpuDefinitionInfo *info;
8264     const char *typename;
8265 
8266     typename = object_class_get_name(oc);
8267     info = g_malloc0(sizeof(*info));
8268     info->name = g_strndup(typename,
8269                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8270     info->q_typename = g_strdup(typename);
8271 
8272     entry = g_malloc0(sizeof(*entry));
8273     entry->value = info;
8274     entry->next = *cpu_list;
8275     *cpu_list = entry;
8276 }
8277 
8278 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8279 {
8280     CpuDefinitionInfoList *cpu_list = NULL;
8281     GSList *list;
8282 
8283     list = object_class_get_list(TYPE_ARM_CPU, false);
8284     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8285     g_slist_free(list);
8286 
8287     return cpu_list;
8288 }
8289 
8290 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8291                                    void *opaque, int state, int secstate,
8292                                    int crm, int opc1, int opc2,
8293                                    const char *name)
8294 {
8295     /* Private utility function for define_one_arm_cp_reg_with_opaque():
8296      * add a single reginfo struct to the hash table.
8297      */
8298     uint32_t *key = g_new(uint32_t, 1);
8299     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
8300     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
8301     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
8302 
8303     r2->name = g_strdup(name);
8304     /* Reset the secure state to the specific incoming state.  This is
8305      * necessary as the register may have been defined with both states.
8306      */
8307     r2->secure = secstate;
8308 
8309     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8310         /* Register is banked (using both entries in array).
8311          * Overwriting fieldoffset as the array is only used to define
8312          * banked registers but later only fieldoffset is used.
8313          */
8314         r2->fieldoffset = r->bank_fieldoffsets[ns];
8315     }
8316 
8317     if (state == ARM_CP_STATE_AA32) {
8318         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8319             /* If the register is banked then we don't need to migrate or
8320              * reset the 32-bit instance in certain cases:
8321              *
8322              * 1) If the register has both 32-bit and 64-bit instances then we
8323              *    can count on the 64-bit instance taking care of the
8324              *    non-secure bank.
8325              * 2) If ARMv8 is enabled then we can count on a 64-bit version
8326              *    taking care of the secure bank.  This requires that separate
8327              *    32 and 64-bit definitions are provided.
8328              */
8329             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8330                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
8331                 r2->type |= ARM_CP_ALIAS;
8332             }
8333         } else if ((secstate != r->secure) && !ns) {
8334             /* The register is not banked so we only want to allow migration of
8335              * the non-secure instance.
8336              */
8337             r2->type |= ARM_CP_ALIAS;
8338         }
8339 
8340         if (r->state == ARM_CP_STATE_BOTH) {
8341             /* We assume it is a cp15 register if the .cp field is left unset.
8342              */
8343             if (r2->cp == 0) {
8344                 r2->cp = 15;
8345             }
8346 
8347 #ifdef HOST_WORDS_BIGENDIAN
8348             if (r2->fieldoffset) {
8349                 r2->fieldoffset += sizeof(uint32_t);
8350             }
8351 #endif
8352         }
8353     }
8354     if (state == ARM_CP_STATE_AA64) {
8355         /* To allow abbreviation of ARMCPRegInfo
8356          * definitions, we treat cp == 0 as equivalent to
8357          * the value for "standard guest-visible sysreg".
8358          * STATE_BOTH definitions are also always "standard
8359          * sysreg" in their AArch64 view (the .cp value may
8360          * be non-zero for the benefit of the AArch32 view).
8361          */
8362         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8363             r2->cp = CP_REG_ARM64_SYSREG_CP;
8364         }
8365         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
8366                                   r2->opc0, opc1, opc2);
8367     } else {
8368         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
8369     }
8370     if (opaque) {
8371         r2->opaque = opaque;
8372     }
8373     /* reginfo passed to helpers is correct for the actual access,
8374      * and is never ARM_CP_STATE_BOTH:
8375      */
8376     r2->state = state;
8377     /* Make sure reginfo passed to helpers for wildcarded regs
8378      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
8379      */
8380     r2->crm = crm;
8381     r2->opc1 = opc1;
8382     r2->opc2 = opc2;
8383     /* By convention, for wildcarded registers only the first
8384      * entry is used for migration; the others are marked as
8385      * ALIAS so we don't try to transfer the register
8386      * multiple times. Special registers (ie NOP/WFI) are
8387      * never migratable and not even raw-accessible.
8388      */
8389     if ((r->type & ARM_CP_SPECIAL)) {
8390         r2->type |= ARM_CP_NO_RAW;
8391     }
8392     if (((r->crm == CP_ANY) && crm != 0) ||
8393         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8394         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8395         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8396     }
8397 
8398     /* Check that raw accesses are either forbidden or handled. Note that
8399      * we can't assert this earlier because the setup of fieldoffset for
8400      * banked registers has to be done first.
8401      */
8402     if (!(r2->type & ARM_CP_NO_RAW)) {
8403         assert(!raw_accessors_invalid(r2));
8404     }
8405 
8406     /* Overriding of an existing definition must be explicitly
8407      * requested.
8408      */
8409     if (!(r->type & ARM_CP_OVERRIDE)) {
8410         ARMCPRegInfo *oldreg;
8411         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
8412         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
8413             fprintf(stderr, "Register redefined: cp=%d %d bit "
8414                     "crn=%d crm=%d opc1=%d opc2=%d, "
8415                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
8416                     r2->crn, r2->crm, r2->opc1, r2->opc2,
8417                     oldreg->name, r2->name);
8418             g_assert_not_reached();
8419         }
8420     }
8421     g_hash_table_insert(cpu->cp_regs, key, r2);
8422 }
8423 
8424 
8425 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8426                                        const ARMCPRegInfo *r, void *opaque)
8427 {
8428     /* Define implementations of coprocessor registers.
8429      * We store these in a hashtable because typically
8430      * there are less than 150 registers in a space which
8431      * is 16*16*16*8*8 = 262144 in size.
8432      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8433      * If a register is defined twice then the second definition is
8434      * used, so this can be used to define some generic registers and
8435      * then override them with implementation specific variations.
8436      * At least one of the original and the second definition should
8437      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8438      * against accidental use.
8439      *
8440      * The state field defines whether the register is to be
8441      * visible in the AArch32 or AArch64 execution state. If the
8442      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8443      * reginfo structure for the AArch32 view, which sees the lower
8444      * 32 bits of the 64 bit register.
8445      *
8446      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8447      * be wildcarded. AArch64 registers are always considered to be 64
8448      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8449      * the register, if any.
8450      */
8451     int crm, opc1, opc2, state;
8452     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8453     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8454     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8455     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8456     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8457     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8458     /* 64 bit registers have only CRm and Opc1 fields */
8459     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8460     /* op0 only exists in the AArch64 encodings */
8461     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8462     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8463     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8464     /*
8465      * This API is only for Arm's system coprocessors (14 and 15) or
8466      * (M-profile or v7A-and-earlier only) for implementation defined
8467      * coprocessors in the range 0..7.  Our decode assumes this, since
8468      * 8..13 can be used for other insns including VFP and Neon. See
8469      * valid_cp() in translate.c.  Assert here that we haven't tried
8470      * to use an invalid coprocessor number.
8471      */
8472     switch (r->state) {
8473     case ARM_CP_STATE_BOTH:
8474         /* 0 has a special meaning, but otherwise the same rules as AA32. */
8475         if (r->cp == 0) {
8476             break;
8477         }
8478         /* fall through */
8479     case ARM_CP_STATE_AA32:
8480         if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
8481             !arm_feature(&cpu->env, ARM_FEATURE_M)) {
8482             assert(r->cp >= 14 && r->cp <= 15);
8483         } else {
8484             assert(r->cp < 8 || (r->cp >= 14 && r->cp <= 15));
8485         }
8486         break;
8487     case ARM_CP_STATE_AA64:
8488         assert(r->cp == 0 || r->cp == CP_REG_ARM64_SYSREG_CP);
8489         break;
8490     default:
8491         g_assert_not_reached();
8492     }
8493     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8494      * encodes a minimum access level for the register. We roll this
8495      * runtime check into our general permission check code, so check
8496      * here that the reginfo's specified permissions are strict enough
8497      * to encompass the generic architectural permission check.
8498      */
8499     if (r->state != ARM_CP_STATE_AA32) {
8500         int mask = 0;
8501         switch (r->opc1) {
8502         case 0:
8503             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8504             mask = PL0U_R | PL1_RW;
8505             break;
8506         case 1: case 2:
8507             /* min_EL EL1 */
8508             mask = PL1_RW;
8509             break;
8510         case 3:
8511             /* min_EL EL0 */
8512             mask = PL0_RW;
8513             break;
8514         case 4:
8515         case 5:
8516             /* min_EL EL2 */
8517             mask = PL2_RW;
8518             break;
8519         case 6:
8520             /* min_EL EL3 */
8521             mask = PL3_RW;
8522             break;
8523         case 7:
8524             /* min_EL EL1, secure mode only (we don't check the latter) */
8525             mask = PL1_RW;
8526             break;
8527         default:
8528             /* broken reginfo with out-of-range opc1 */
8529             assert(false);
8530             break;
8531         }
8532         /* assert our permissions are not too lax (stricter is fine) */
8533         assert((r->access & ~mask) == 0);
8534     }
8535 
8536     /* Check that the register definition has enough info to handle
8537      * reads and writes if they are permitted.
8538      */
8539     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
8540         if (r->access & PL3_R) {
8541             assert((r->fieldoffset ||
8542                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8543                    r->readfn);
8544         }
8545         if (r->access & PL3_W) {
8546             assert((r->fieldoffset ||
8547                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8548                    r->writefn);
8549         }
8550     }
8551     /* Bad type field probably means missing sentinel at end of reg list */
8552     assert(cptype_valid(r->type));
8553     for (crm = crmmin; crm <= crmmax; crm++) {
8554         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8555             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8556                 for (state = ARM_CP_STATE_AA32;
8557                      state <= ARM_CP_STATE_AA64; state++) {
8558                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8559                         continue;
8560                     }
8561                     if (state == ARM_CP_STATE_AA32) {
8562                         /* Under AArch32 CP registers can be common
8563                          * (same for secure and non-secure world) or banked.
8564                          */
8565                         char *name;
8566 
8567                         switch (r->secure) {
8568                         case ARM_CP_SECSTATE_S:
8569                         case ARM_CP_SECSTATE_NS:
8570                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8571                                                    r->secure, crm, opc1, opc2,
8572                                                    r->name);
8573                             break;
8574                         default:
8575                             name = g_strdup_printf("%s_S", r->name);
8576                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8577                                                    ARM_CP_SECSTATE_S,
8578                                                    crm, opc1, opc2, name);
8579                             g_free(name);
8580                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8581                                                    ARM_CP_SECSTATE_NS,
8582                                                    crm, opc1, opc2, r->name);
8583                             break;
8584                         }
8585                     } else {
8586                         /* AArch64 registers get mapped to non-secure instance
8587                          * of AArch32 */
8588                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8589                                                ARM_CP_SECSTATE_NS,
8590                                                crm, opc1, opc2, r->name);
8591                     }
8592                 }
8593             }
8594         }
8595     }
8596 }
8597 
8598 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
8599                                     const ARMCPRegInfo *regs, void *opaque)
8600 {
8601     /* Define a whole list of registers */
8602     const ARMCPRegInfo *r;
8603     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8604         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
8605     }
8606 }
8607 
8608 /*
8609  * Modify ARMCPRegInfo for access from userspace.
8610  *
8611  * This is a data driven modification directed by
8612  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8613  * user-space cannot alter any values and dynamic values pertaining to
8614  * execution state are hidden from user space view anyway.
8615  */
8616 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
8617 {
8618     const ARMCPRegUserSpaceInfo *m;
8619     ARMCPRegInfo *r;
8620 
8621     for (m = mods; m->name; m++) {
8622         GPatternSpec *pat = NULL;
8623         if (m->is_glob) {
8624             pat = g_pattern_spec_new(m->name);
8625         }
8626         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8627             if (pat && g_pattern_match_string(pat, r->name)) {
8628                 r->type = ARM_CP_CONST;
8629                 r->access = PL0U_R;
8630                 r->resetvalue = 0;
8631                 /* continue */
8632             } else if (strcmp(r->name, m->name) == 0) {
8633                 r->type = ARM_CP_CONST;
8634                 r->access = PL0U_R;
8635                 r->resetvalue &= m->exported_bits;
8636                 r->resetvalue |= m->fixed_bits;
8637                 break;
8638             }
8639         }
8640         if (pat) {
8641             g_pattern_spec_free(pat);
8642         }
8643     }
8644 }
8645 
8646 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8647 {
8648     return g_hash_table_lookup(cpregs, &encoded_cp);
8649 }
8650 
8651 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8652                          uint64_t value)
8653 {
8654     /* Helper coprocessor write function for write-ignore registers */
8655 }
8656 
8657 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8658 {
8659     /* Helper coprocessor write function for read-as-zero registers */
8660     return 0;
8661 }
8662 
8663 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8664 {
8665     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8666 }
8667 
8668 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8669 {
8670     /* Return true if it is not valid for us to switch to
8671      * this CPU mode (ie all the UNPREDICTABLE cases in
8672      * the ARM ARM CPSRWriteByInstr pseudocode).
8673      */
8674 
8675     /* Changes to or from Hyp via MSR and CPS are illegal. */
8676     if (write_type == CPSRWriteByInstr &&
8677         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8678          mode == ARM_CPU_MODE_HYP)) {
8679         return 1;
8680     }
8681 
8682     switch (mode) {
8683     case ARM_CPU_MODE_USR:
8684         return 0;
8685     case ARM_CPU_MODE_SYS:
8686     case ARM_CPU_MODE_SVC:
8687     case ARM_CPU_MODE_ABT:
8688     case ARM_CPU_MODE_UND:
8689     case ARM_CPU_MODE_IRQ:
8690     case ARM_CPU_MODE_FIQ:
8691         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
8692          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
8693          */
8694         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
8695          * and CPS are treated as illegal mode changes.
8696          */
8697         if (write_type == CPSRWriteByInstr &&
8698             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
8699             (arm_hcr_el2_eff(env) & HCR_TGE)) {
8700             return 1;
8701         }
8702         return 0;
8703     case ARM_CPU_MODE_HYP:
8704         return !arm_feature(env, ARM_FEATURE_EL2)
8705             || arm_current_el(env) < 2 || arm_is_secure_below_el3(env);
8706     case ARM_CPU_MODE_MON:
8707         return arm_current_el(env) < 3;
8708     default:
8709         return 1;
8710     }
8711 }
8712 
8713 uint32_t cpsr_read(CPUARMState *env)
8714 {
8715     int ZF;
8716     ZF = (env->ZF == 0);
8717     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
8718         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
8719         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
8720         | ((env->condexec_bits & 0xfc) << 8)
8721         | (env->GE << 16) | (env->daif & CPSR_AIF);
8722 }
8723 
8724 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
8725                 CPSRWriteType write_type)
8726 {
8727     uint32_t changed_daif;
8728 
8729     if (mask & CPSR_NZCV) {
8730         env->ZF = (~val) & CPSR_Z;
8731         env->NF = val;
8732         env->CF = (val >> 29) & 1;
8733         env->VF = (val << 3) & 0x80000000;
8734     }
8735     if (mask & CPSR_Q)
8736         env->QF = ((val & CPSR_Q) != 0);
8737     if (mask & CPSR_T)
8738         env->thumb = ((val & CPSR_T) != 0);
8739     if (mask & CPSR_IT_0_1) {
8740         env->condexec_bits &= ~3;
8741         env->condexec_bits |= (val >> 25) & 3;
8742     }
8743     if (mask & CPSR_IT_2_7) {
8744         env->condexec_bits &= 3;
8745         env->condexec_bits |= (val >> 8) & 0xfc;
8746     }
8747     if (mask & CPSR_GE) {
8748         env->GE = (val >> 16) & 0xf;
8749     }
8750 
8751     /* In a V7 implementation that includes the security extensions but does
8752      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
8753      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
8754      * bits respectively.
8755      *
8756      * In a V8 implementation, it is permitted for privileged software to
8757      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
8758      */
8759     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
8760         arm_feature(env, ARM_FEATURE_EL3) &&
8761         !arm_feature(env, ARM_FEATURE_EL2) &&
8762         !arm_is_secure(env)) {
8763 
8764         changed_daif = (env->daif ^ val) & mask;
8765 
8766         if (changed_daif & CPSR_A) {
8767             /* Check to see if we are allowed to change the masking of async
8768              * abort exceptions from a non-secure state.
8769              */
8770             if (!(env->cp15.scr_el3 & SCR_AW)) {
8771                 qemu_log_mask(LOG_GUEST_ERROR,
8772                               "Ignoring attempt to switch CPSR_A flag from "
8773                               "non-secure world with SCR.AW bit clear\n");
8774                 mask &= ~CPSR_A;
8775             }
8776         }
8777 
8778         if (changed_daif & CPSR_F) {
8779             /* Check to see if we are allowed to change the masking of FIQ
8780              * exceptions from a non-secure state.
8781              */
8782             if (!(env->cp15.scr_el3 & SCR_FW)) {
8783                 qemu_log_mask(LOG_GUEST_ERROR,
8784                               "Ignoring attempt to switch CPSR_F flag from "
8785                               "non-secure world with SCR.FW bit clear\n");
8786                 mask &= ~CPSR_F;
8787             }
8788 
8789             /* Check whether non-maskable FIQ (NMFI) support is enabled.
8790              * If this bit is set software is not allowed to mask
8791              * FIQs, but is allowed to set CPSR_F to 0.
8792              */
8793             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
8794                 (val & CPSR_F)) {
8795                 qemu_log_mask(LOG_GUEST_ERROR,
8796                               "Ignoring attempt to enable CPSR_F flag "
8797                               "(non-maskable FIQ [NMFI] support enabled)\n");
8798                 mask &= ~CPSR_F;
8799             }
8800         }
8801     }
8802 
8803     env->daif &= ~(CPSR_AIF & mask);
8804     env->daif |= val & CPSR_AIF & mask;
8805 
8806     if (write_type != CPSRWriteRaw &&
8807         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
8808         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
8809             /* Note that we can only get here in USR mode if this is a
8810              * gdb stub write; for this case we follow the architectural
8811              * behaviour for guest writes in USR mode of ignoring an attempt
8812              * to switch mode. (Those are caught by translate.c for writes
8813              * triggered by guest instructions.)
8814              */
8815             mask &= ~CPSR_M;
8816         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
8817             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
8818              * v7, and has defined behaviour in v8:
8819              *  + leave CPSR.M untouched
8820              *  + allow changes to the other CPSR fields
8821              *  + set PSTATE.IL
8822              * For user changes via the GDB stub, we don't set PSTATE.IL,
8823              * as this would be unnecessarily harsh for a user error.
8824              */
8825             mask &= ~CPSR_M;
8826             if (write_type != CPSRWriteByGDBStub &&
8827                 arm_feature(env, ARM_FEATURE_V8)) {
8828                 mask |= CPSR_IL;
8829                 val |= CPSR_IL;
8830             }
8831             qemu_log_mask(LOG_GUEST_ERROR,
8832                           "Illegal AArch32 mode switch attempt from %s to %s\n",
8833                           aarch32_mode_name(env->uncached_cpsr),
8834                           aarch32_mode_name(val));
8835         } else {
8836             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
8837                           write_type == CPSRWriteExceptionReturn ?
8838                           "Exception return from AArch32" :
8839                           "AArch32 mode switch from",
8840                           aarch32_mode_name(env->uncached_cpsr),
8841                           aarch32_mode_name(val), env->regs[15]);
8842             switch_mode(env, val & CPSR_M);
8843         }
8844     }
8845     mask &= ~CACHED_CPSR_BITS;
8846     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
8847 }
8848 
8849 /* Sign/zero extend */
8850 uint32_t HELPER(sxtb16)(uint32_t x)
8851 {
8852     uint32_t res;
8853     res = (uint16_t)(int8_t)x;
8854     res |= (uint32_t)(int8_t)(x >> 16) << 16;
8855     return res;
8856 }
8857 
8858 uint32_t HELPER(uxtb16)(uint32_t x)
8859 {
8860     uint32_t res;
8861     res = (uint16_t)(uint8_t)x;
8862     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
8863     return res;
8864 }
8865 
8866 int32_t HELPER(sdiv)(int32_t num, int32_t den)
8867 {
8868     if (den == 0)
8869       return 0;
8870     if (num == INT_MIN && den == -1)
8871       return INT_MIN;
8872     return num / den;
8873 }
8874 
8875 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
8876 {
8877     if (den == 0)
8878       return 0;
8879     return num / den;
8880 }
8881 
8882 uint32_t HELPER(rbit)(uint32_t x)
8883 {
8884     return revbit32(x);
8885 }
8886 
8887 #ifdef CONFIG_USER_ONLY
8888 
8889 static void switch_mode(CPUARMState *env, int mode)
8890 {
8891     ARMCPU *cpu = env_archcpu(env);
8892 
8893     if (mode != ARM_CPU_MODE_USR) {
8894         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
8895     }
8896 }
8897 
8898 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
8899                                  uint32_t cur_el, bool secure)
8900 {
8901     return 1;
8902 }
8903 
8904 void aarch64_sync_64_to_32(CPUARMState *env)
8905 {
8906     g_assert_not_reached();
8907 }
8908 
8909 #else
8910 
8911 static void switch_mode(CPUARMState *env, int mode)
8912 {
8913     int old_mode;
8914     int i;
8915 
8916     old_mode = env->uncached_cpsr & CPSR_M;
8917     if (mode == old_mode)
8918         return;
8919 
8920     if (old_mode == ARM_CPU_MODE_FIQ) {
8921         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
8922         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
8923     } else if (mode == ARM_CPU_MODE_FIQ) {
8924         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
8925         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
8926     }
8927 
8928     i = bank_number(old_mode);
8929     env->banked_r13[i] = env->regs[13];
8930     env->banked_spsr[i] = env->spsr;
8931 
8932     i = bank_number(mode);
8933     env->regs[13] = env->banked_r13[i];
8934     env->spsr = env->banked_spsr[i];
8935 
8936     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
8937     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
8938 }
8939 
8940 /* Physical Interrupt Target EL Lookup Table
8941  *
8942  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
8943  *
8944  * The below multi-dimensional table is used for looking up the target
8945  * exception level given numerous condition criteria.  Specifically, the
8946  * target EL is based on SCR and HCR routing controls as well as the
8947  * currently executing EL and secure state.
8948  *
8949  *    Dimensions:
8950  *    target_el_table[2][2][2][2][2][4]
8951  *                    |  |  |  |  |  +--- Current EL
8952  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
8953  *                    |  |  |  +--------- HCR mask override
8954  *                    |  |  +------------ SCR exec state control
8955  *                    |  +--------------- SCR mask override
8956  *                    +------------------ 32-bit(0)/64-bit(1) EL3
8957  *
8958  *    The table values are as such:
8959  *    0-3 = EL0-EL3
8960  *     -1 = Cannot occur
8961  *
8962  * The ARM ARM target EL table includes entries indicating that an "exception
8963  * is not taken".  The two cases where this is applicable are:
8964  *    1) An exception is taken from EL3 but the SCR does not have the exception
8965  *    routed to EL3.
8966  *    2) An exception is taken from EL2 but the HCR does not have the exception
8967  *    routed to EL2.
8968  * In these two cases, the below table contain a target of EL1.  This value is
8969  * returned as it is expected that the consumer of the table data will check
8970  * for "target EL >= current EL" to ensure the exception is not taken.
8971  *
8972  *            SCR     HCR
8973  *         64  EA     AMO                 From
8974  *        BIT IRQ     IMO      Non-secure         Secure
8975  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
8976  */
8977 static const int8_t target_el_table[2][2][2][2][2][4] = {
8978     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
8979        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
8980       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
8981        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
8982      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
8983        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
8984       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
8985        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
8986     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
8987        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
8988       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
8989        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
8990      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
8991        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
8992       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
8993        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
8994 };
8995 
8996 /*
8997  * Determine the target EL for physical exceptions
8998  */
8999 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9000                                  uint32_t cur_el, bool secure)
9001 {
9002     CPUARMState *env = cs->env_ptr;
9003     bool rw;
9004     bool scr;
9005     bool hcr;
9006     int target_el;
9007     /* Is the highest EL AArch64? */
9008     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
9009     uint64_t hcr_el2;
9010 
9011     if (arm_feature(env, ARM_FEATURE_EL3)) {
9012         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
9013     } else {
9014         /* Either EL2 is the highest EL (and so the EL2 register width
9015          * is given by is64); or there is no EL2 or EL3, in which case
9016          * the value of 'rw' does not affect the table lookup anyway.
9017          */
9018         rw = is64;
9019     }
9020 
9021     hcr_el2 = arm_hcr_el2_eff(env);
9022     switch (excp_idx) {
9023     case EXCP_IRQ:
9024         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
9025         hcr = hcr_el2 & HCR_IMO;
9026         break;
9027     case EXCP_FIQ:
9028         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
9029         hcr = hcr_el2 & HCR_FMO;
9030         break;
9031     default:
9032         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
9033         hcr = hcr_el2 & HCR_AMO;
9034         break;
9035     };
9036 
9037     /*
9038      * For these purposes, TGE and AMO/IMO/FMO both force the
9039      * interrupt to EL2.  Fold TGE into the bit extracted above.
9040      */
9041     hcr |= (hcr_el2 & HCR_TGE) != 0;
9042 
9043     /* Perform a table-lookup for the target EL given the current state */
9044     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
9045 
9046     assert(target_el > 0);
9047 
9048     return target_el;
9049 }
9050 
9051 void arm_log_exception(int idx)
9052 {
9053     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9054         const char *exc = NULL;
9055         static const char * const excnames[] = {
9056             [EXCP_UDEF] = "Undefined Instruction",
9057             [EXCP_SWI] = "SVC",
9058             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9059             [EXCP_DATA_ABORT] = "Data Abort",
9060             [EXCP_IRQ] = "IRQ",
9061             [EXCP_FIQ] = "FIQ",
9062             [EXCP_BKPT] = "Breakpoint",
9063             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9064             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9065             [EXCP_HVC] = "Hypervisor Call",
9066             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9067             [EXCP_SMC] = "Secure Monitor Call",
9068             [EXCP_VIRQ] = "Virtual IRQ",
9069             [EXCP_VFIQ] = "Virtual FIQ",
9070             [EXCP_SEMIHOST] = "Semihosting call",
9071             [EXCP_NOCP] = "v7M NOCP UsageFault",
9072             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9073             [EXCP_STKOF] = "v8M STKOF UsageFault",
9074             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9075             [EXCP_LSERR] = "v8M LSERR UsageFault",
9076             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9077         };
9078 
9079         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9080             exc = excnames[idx];
9081         }
9082         if (!exc) {
9083             exc = "unknown";
9084         }
9085         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
9086     }
9087 }
9088 
9089 /*
9090  * Function used to synchronize QEMU's AArch64 register set with AArch32
9091  * register set.  This is necessary when switching between AArch32 and AArch64
9092  * execution state.
9093  */
9094 void aarch64_sync_32_to_64(CPUARMState *env)
9095 {
9096     int i;
9097     uint32_t mode = env->uncached_cpsr & CPSR_M;
9098 
9099     /* We can blanket copy R[0:7] to X[0:7] */
9100     for (i = 0; i < 8; i++) {
9101         env->xregs[i] = env->regs[i];
9102     }
9103 
9104     /*
9105      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9106      * Otherwise, they come from the banked user regs.
9107      */
9108     if (mode == ARM_CPU_MODE_FIQ) {
9109         for (i = 8; i < 13; i++) {
9110             env->xregs[i] = env->usr_regs[i - 8];
9111         }
9112     } else {
9113         for (i = 8; i < 13; i++) {
9114             env->xregs[i] = env->regs[i];
9115         }
9116     }
9117 
9118     /*
9119      * Registers x13-x23 are the various mode SP and FP registers. Registers
9120      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9121      * from the mode banked register.
9122      */
9123     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9124         env->xregs[13] = env->regs[13];
9125         env->xregs[14] = env->regs[14];
9126     } else {
9127         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9128         /* HYP is an exception in that it is copied from r14 */
9129         if (mode == ARM_CPU_MODE_HYP) {
9130             env->xregs[14] = env->regs[14];
9131         } else {
9132             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9133         }
9134     }
9135 
9136     if (mode == ARM_CPU_MODE_HYP) {
9137         env->xregs[15] = env->regs[13];
9138     } else {
9139         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9140     }
9141 
9142     if (mode == ARM_CPU_MODE_IRQ) {
9143         env->xregs[16] = env->regs[14];
9144         env->xregs[17] = env->regs[13];
9145     } else {
9146         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9147         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9148     }
9149 
9150     if (mode == ARM_CPU_MODE_SVC) {
9151         env->xregs[18] = env->regs[14];
9152         env->xregs[19] = env->regs[13];
9153     } else {
9154         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9155         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9156     }
9157 
9158     if (mode == ARM_CPU_MODE_ABT) {
9159         env->xregs[20] = env->regs[14];
9160         env->xregs[21] = env->regs[13];
9161     } else {
9162         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9163         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9164     }
9165 
9166     if (mode == ARM_CPU_MODE_UND) {
9167         env->xregs[22] = env->regs[14];
9168         env->xregs[23] = env->regs[13];
9169     } else {
9170         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9171         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9172     }
9173 
9174     /*
9175      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9176      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9177      * FIQ bank for r8-r14.
9178      */
9179     if (mode == ARM_CPU_MODE_FIQ) {
9180         for (i = 24; i < 31; i++) {
9181             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9182         }
9183     } else {
9184         for (i = 24; i < 29; i++) {
9185             env->xregs[i] = env->fiq_regs[i - 24];
9186         }
9187         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9188         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9189     }
9190 
9191     env->pc = env->regs[15];
9192 }
9193 
9194 /*
9195  * Function used to synchronize QEMU's AArch32 register set with AArch64
9196  * register set.  This is necessary when switching between AArch32 and AArch64
9197  * execution state.
9198  */
9199 void aarch64_sync_64_to_32(CPUARMState *env)
9200 {
9201     int i;
9202     uint32_t mode = env->uncached_cpsr & CPSR_M;
9203 
9204     /* We can blanket copy X[0:7] to R[0:7] */
9205     for (i = 0; i < 8; i++) {
9206         env->regs[i] = env->xregs[i];
9207     }
9208 
9209     /*
9210      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9211      * Otherwise, we copy x8-x12 into the banked user regs.
9212      */
9213     if (mode == ARM_CPU_MODE_FIQ) {
9214         for (i = 8; i < 13; i++) {
9215             env->usr_regs[i - 8] = env->xregs[i];
9216         }
9217     } else {
9218         for (i = 8; i < 13; i++) {
9219             env->regs[i] = env->xregs[i];
9220         }
9221     }
9222 
9223     /*
9224      * Registers r13 & r14 depend on the current mode.
9225      * If we are in a given mode, we copy the corresponding x registers to r13
9226      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9227      * for the mode.
9228      */
9229     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9230         env->regs[13] = env->xregs[13];
9231         env->regs[14] = env->xregs[14];
9232     } else {
9233         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9234 
9235         /*
9236          * HYP is an exception in that it does not have its own banked r14 but
9237          * shares the USR r14
9238          */
9239         if (mode == ARM_CPU_MODE_HYP) {
9240             env->regs[14] = env->xregs[14];
9241         } else {
9242             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9243         }
9244     }
9245 
9246     if (mode == ARM_CPU_MODE_HYP) {
9247         env->regs[13] = env->xregs[15];
9248     } else {
9249         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9250     }
9251 
9252     if (mode == ARM_CPU_MODE_IRQ) {
9253         env->regs[14] = env->xregs[16];
9254         env->regs[13] = env->xregs[17];
9255     } else {
9256         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9257         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9258     }
9259 
9260     if (mode == ARM_CPU_MODE_SVC) {
9261         env->regs[14] = env->xregs[18];
9262         env->regs[13] = env->xregs[19];
9263     } else {
9264         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9265         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9266     }
9267 
9268     if (mode == ARM_CPU_MODE_ABT) {
9269         env->regs[14] = env->xregs[20];
9270         env->regs[13] = env->xregs[21];
9271     } else {
9272         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9273         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9274     }
9275 
9276     if (mode == ARM_CPU_MODE_UND) {
9277         env->regs[14] = env->xregs[22];
9278         env->regs[13] = env->xregs[23];
9279     } else {
9280         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9281         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9282     }
9283 
9284     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9285      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9286      * FIQ bank for r8-r14.
9287      */
9288     if (mode == ARM_CPU_MODE_FIQ) {
9289         for (i = 24; i < 31; i++) {
9290             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9291         }
9292     } else {
9293         for (i = 24; i < 29; i++) {
9294             env->fiq_regs[i - 24] = env->xregs[i];
9295         }
9296         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9297         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9298     }
9299 
9300     env->regs[15] = env->pc;
9301 }
9302 
9303 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9304                                    uint32_t mask, uint32_t offset,
9305                                    uint32_t newpc)
9306 {
9307     int new_el;
9308 
9309     /* Change the CPU state so as to actually take the exception. */
9310     switch_mode(env, new_mode);
9311 
9312     /*
9313      * For exceptions taken to AArch32 we must clear the SS bit in both
9314      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9315      */
9316     env->uncached_cpsr &= ~PSTATE_SS;
9317     env->spsr = cpsr_read(env);
9318     /* Clear IT bits.  */
9319     env->condexec_bits = 0;
9320     /* Switch to the new mode, and to the correct instruction set.  */
9321     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9322 
9323     /* This must be after mode switching. */
9324     new_el = arm_current_el(env);
9325 
9326     /* Set new mode endianness */
9327     env->uncached_cpsr &= ~CPSR_E;
9328     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9329         env->uncached_cpsr |= CPSR_E;
9330     }
9331     /* J and IL must always be cleared for exception entry */
9332     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9333     env->daif |= mask;
9334 
9335     if (new_mode == ARM_CPU_MODE_HYP) {
9336         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9337         env->elr_el[2] = env->regs[15];
9338     } else {
9339         /* CPSR.PAN is normally preserved preserved unless...  */
9340         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9341             switch (new_el) {
9342             case 3:
9343                 if (!arm_is_secure_below_el3(env)) {
9344                     /* ... the target is EL3, from non-secure state.  */
9345                     env->uncached_cpsr &= ~CPSR_PAN;
9346                     break;
9347                 }
9348                 /* ... the target is EL3, from secure state ... */
9349                 /* fall through */
9350             case 1:
9351                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9352                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9353                     env->uncached_cpsr |= CPSR_PAN;
9354                 }
9355                 break;
9356             }
9357         }
9358         /*
9359          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9360          * and we should just guard the thumb mode on V4
9361          */
9362         if (arm_feature(env, ARM_FEATURE_V4T)) {
9363             env->thumb =
9364                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9365         }
9366         env->regs[14] = env->regs[15] + offset;
9367     }
9368     env->regs[15] = newpc;
9369     arm_rebuild_hflags(env);
9370 }
9371 
9372 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9373 {
9374     /*
9375      * Handle exception entry to Hyp mode; this is sufficiently
9376      * different to entry to other AArch32 modes that we handle it
9377      * separately here.
9378      *
9379      * The vector table entry used is always the 0x14 Hyp mode entry point,
9380      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
9381      * The offset applied to the preferred return address is always zero
9382      * (see DDI0487C.a section G1.12.3).
9383      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9384      */
9385     uint32_t addr, mask;
9386     ARMCPU *cpu = ARM_CPU(cs);
9387     CPUARMState *env = &cpu->env;
9388 
9389     switch (cs->exception_index) {
9390     case EXCP_UDEF:
9391         addr = 0x04;
9392         break;
9393     case EXCP_SWI:
9394         addr = 0x14;
9395         break;
9396     case EXCP_BKPT:
9397         /* Fall through to prefetch abort.  */
9398     case EXCP_PREFETCH_ABORT:
9399         env->cp15.ifar_s = env->exception.vaddress;
9400         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9401                       (uint32_t)env->exception.vaddress);
9402         addr = 0x0c;
9403         break;
9404     case EXCP_DATA_ABORT:
9405         env->cp15.dfar_s = env->exception.vaddress;
9406         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9407                       (uint32_t)env->exception.vaddress);
9408         addr = 0x10;
9409         break;
9410     case EXCP_IRQ:
9411         addr = 0x18;
9412         break;
9413     case EXCP_FIQ:
9414         addr = 0x1c;
9415         break;
9416     case EXCP_HVC:
9417         addr = 0x08;
9418         break;
9419     case EXCP_HYP_TRAP:
9420         addr = 0x14;
9421         break;
9422     default:
9423         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9424     }
9425 
9426     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9427         if (!arm_feature(env, ARM_FEATURE_V8)) {
9428             /*
9429              * QEMU syndrome values are v8-style. v7 has the IL bit
9430              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9431              * If this is a v7 CPU, squash the IL bit in those cases.
9432              */
9433             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9434                 (cs->exception_index == EXCP_DATA_ABORT &&
9435                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9436                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9437                 env->exception.syndrome &= ~ARM_EL_IL;
9438             }
9439         }
9440         env->cp15.esr_el[2] = env->exception.syndrome;
9441     }
9442 
9443     if (arm_current_el(env) != 2 && addr < 0x14) {
9444         addr = 0x14;
9445     }
9446 
9447     mask = 0;
9448     if (!(env->cp15.scr_el3 & SCR_EA)) {
9449         mask |= CPSR_A;
9450     }
9451     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9452         mask |= CPSR_I;
9453     }
9454     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9455         mask |= CPSR_F;
9456     }
9457 
9458     addr += env->cp15.hvbar;
9459 
9460     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9461 }
9462 
9463 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9464 {
9465     ARMCPU *cpu = ARM_CPU(cs);
9466     CPUARMState *env = &cpu->env;
9467     uint32_t addr;
9468     uint32_t mask;
9469     int new_mode;
9470     uint32_t offset;
9471     uint32_t moe;
9472 
9473     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9474     switch (syn_get_ec(env->exception.syndrome)) {
9475     case EC_BREAKPOINT:
9476     case EC_BREAKPOINT_SAME_EL:
9477         moe = 1;
9478         break;
9479     case EC_WATCHPOINT:
9480     case EC_WATCHPOINT_SAME_EL:
9481         moe = 10;
9482         break;
9483     case EC_AA32_BKPT:
9484         moe = 3;
9485         break;
9486     case EC_VECTORCATCH:
9487         moe = 5;
9488         break;
9489     default:
9490         moe = 0;
9491         break;
9492     }
9493 
9494     if (moe) {
9495         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9496     }
9497 
9498     if (env->exception.target_el == 2) {
9499         arm_cpu_do_interrupt_aarch32_hyp(cs);
9500         return;
9501     }
9502 
9503     switch (cs->exception_index) {
9504     case EXCP_UDEF:
9505         new_mode = ARM_CPU_MODE_UND;
9506         addr = 0x04;
9507         mask = CPSR_I;
9508         if (env->thumb)
9509             offset = 2;
9510         else
9511             offset = 4;
9512         break;
9513     case EXCP_SWI:
9514         new_mode = ARM_CPU_MODE_SVC;
9515         addr = 0x08;
9516         mask = CPSR_I;
9517         /* The PC already points to the next instruction.  */
9518         offset = 0;
9519         break;
9520     case EXCP_BKPT:
9521         /* Fall through to prefetch abort.  */
9522     case EXCP_PREFETCH_ABORT:
9523         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9524         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9525         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9526                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9527         new_mode = ARM_CPU_MODE_ABT;
9528         addr = 0x0c;
9529         mask = CPSR_A | CPSR_I;
9530         offset = 4;
9531         break;
9532     case EXCP_DATA_ABORT:
9533         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9534         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9535         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9536                       env->exception.fsr,
9537                       (uint32_t)env->exception.vaddress);
9538         new_mode = ARM_CPU_MODE_ABT;
9539         addr = 0x10;
9540         mask = CPSR_A | CPSR_I;
9541         offset = 8;
9542         break;
9543     case EXCP_IRQ:
9544         new_mode = ARM_CPU_MODE_IRQ;
9545         addr = 0x18;
9546         /* Disable IRQ and imprecise data aborts.  */
9547         mask = CPSR_A | CPSR_I;
9548         offset = 4;
9549         if (env->cp15.scr_el3 & SCR_IRQ) {
9550             /* IRQ routed to monitor mode */
9551             new_mode = ARM_CPU_MODE_MON;
9552             mask |= CPSR_F;
9553         }
9554         break;
9555     case EXCP_FIQ:
9556         new_mode = ARM_CPU_MODE_FIQ;
9557         addr = 0x1c;
9558         /* Disable FIQ, IRQ and imprecise data aborts.  */
9559         mask = CPSR_A | CPSR_I | CPSR_F;
9560         if (env->cp15.scr_el3 & SCR_FIQ) {
9561             /* FIQ routed to monitor mode */
9562             new_mode = ARM_CPU_MODE_MON;
9563         }
9564         offset = 4;
9565         break;
9566     case EXCP_VIRQ:
9567         new_mode = ARM_CPU_MODE_IRQ;
9568         addr = 0x18;
9569         /* Disable IRQ and imprecise data aborts.  */
9570         mask = CPSR_A | CPSR_I;
9571         offset = 4;
9572         break;
9573     case EXCP_VFIQ:
9574         new_mode = ARM_CPU_MODE_FIQ;
9575         addr = 0x1c;
9576         /* Disable FIQ, IRQ and imprecise data aborts.  */
9577         mask = CPSR_A | CPSR_I | CPSR_F;
9578         offset = 4;
9579         break;
9580     case EXCP_SMC:
9581         new_mode = ARM_CPU_MODE_MON;
9582         addr = 0x08;
9583         mask = CPSR_A | CPSR_I | CPSR_F;
9584         offset = 0;
9585         break;
9586     default:
9587         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9588         return; /* Never happens.  Keep compiler happy.  */
9589     }
9590 
9591     if (new_mode == ARM_CPU_MODE_MON) {
9592         addr += env->cp15.mvbar;
9593     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9594         /* High vectors. When enabled, base address cannot be remapped. */
9595         addr += 0xffff0000;
9596     } else {
9597         /* ARM v7 architectures provide a vector base address register to remap
9598          * the interrupt vector table.
9599          * This register is only followed in non-monitor mode, and is banked.
9600          * Note: only bits 31:5 are valid.
9601          */
9602         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9603     }
9604 
9605     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9606         env->cp15.scr_el3 &= ~SCR_NS;
9607     }
9608 
9609     take_aarch32_exception(env, new_mode, mask, offset, addr);
9610 }
9611 
9612 static int aarch64_regnum(CPUARMState *env, int aarch32_reg)
9613 {
9614     /*
9615      * Return the register number of the AArch64 view of the AArch32
9616      * register @aarch32_reg. The CPUARMState CPSR is assumed to still
9617      * be that of the AArch32 mode the exception came from.
9618      */
9619     int mode = env->uncached_cpsr & CPSR_M;
9620 
9621     switch (aarch32_reg) {
9622     case 0 ... 7:
9623         return aarch32_reg;
9624     case 8 ... 12:
9625         return mode == ARM_CPU_MODE_FIQ ? aarch32_reg + 16 : aarch32_reg;
9626     case 13:
9627         switch (mode) {
9628         case ARM_CPU_MODE_USR:
9629         case ARM_CPU_MODE_SYS:
9630             return 13;
9631         case ARM_CPU_MODE_HYP:
9632             return 15;
9633         case ARM_CPU_MODE_IRQ:
9634             return 17;
9635         case ARM_CPU_MODE_SVC:
9636             return 19;
9637         case ARM_CPU_MODE_ABT:
9638             return 21;
9639         case ARM_CPU_MODE_UND:
9640             return 23;
9641         case ARM_CPU_MODE_FIQ:
9642             return 29;
9643         default:
9644             g_assert_not_reached();
9645         }
9646     case 14:
9647         switch (mode) {
9648         case ARM_CPU_MODE_USR:
9649         case ARM_CPU_MODE_SYS:
9650         case ARM_CPU_MODE_HYP:
9651             return 14;
9652         case ARM_CPU_MODE_IRQ:
9653             return 16;
9654         case ARM_CPU_MODE_SVC:
9655             return 18;
9656         case ARM_CPU_MODE_ABT:
9657             return 20;
9658         case ARM_CPU_MODE_UND:
9659             return 22;
9660         case ARM_CPU_MODE_FIQ:
9661             return 30;
9662         default:
9663             g_assert_not_reached();
9664         }
9665     case 15:
9666         return 31;
9667     default:
9668         g_assert_not_reached();
9669     }
9670 }
9671 
9672 /* Handle exception entry to a target EL which is using AArch64 */
9673 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
9674 {
9675     ARMCPU *cpu = ARM_CPU(cs);
9676     CPUARMState *env = &cpu->env;
9677     unsigned int new_el = env->exception.target_el;
9678     target_ulong addr = env->cp15.vbar_el[new_el];
9679     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
9680     unsigned int old_mode;
9681     unsigned int cur_el = arm_current_el(env);
9682     int rt;
9683 
9684     /*
9685      * Note that new_el can never be 0.  If cur_el is 0, then
9686      * el0_a64 is is_a64(), else el0_a64 is ignored.
9687      */
9688     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
9689 
9690     if (cur_el < new_el) {
9691         /* Entry vector offset depends on whether the implemented EL
9692          * immediately lower than the target level is using AArch32 or AArch64
9693          */
9694         bool is_aa64;
9695         uint64_t hcr;
9696 
9697         switch (new_el) {
9698         case 3:
9699             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
9700             break;
9701         case 2:
9702             hcr = arm_hcr_el2_eff(env);
9703             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
9704                 is_aa64 = (hcr & HCR_RW) != 0;
9705                 break;
9706             }
9707             /* fall through */
9708         case 1:
9709             is_aa64 = is_a64(env);
9710             break;
9711         default:
9712             g_assert_not_reached();
9713         }
9714 
9715         if (is_aa64) {
9716             addr += 0x400;
9717         } else {
9718             addr += 0x600;
9719         }
9720     } else if (pstate_read(env) & PSTATE_SP) {
9721         addr += 0x200;
9722     }
9723 
9724     switch (cs->exception_index) {
9725     case EXCP_PREFETCH_ABORT:
9726     case EXCP_DATA_ABORT:
9727         env->cp15.far_el[new_el] = env->exception.vaddress;
9728         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
9729                       env->cp15.far_el[new_el]);
9730         /* fall through */
9731     case EXCP_BKPT:
9732     case EXCP_UDEF:
9733     case EXCP_SWI:
9734     case EXCP_HVC:
9735     case EXCP_HYP_TRAP:
9736     case EXCP_SMC:
9737         switch (syn_get_ec(env->exception.syndrome)) {
9738         case EC_ADVSIMDFPACCESSTRAP:
9739             /*
9740              * QEMU internal FP/SIMD syndromes from AArch32 include the
9741              * TA and coproc fields which are only exposed if the exception
9742              * is taken to AArch32 Hyp mode. Mask them out to get a valid
9743              * AArch64 format syndrome.
9744              */
9745             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
9746             break;
9747         case EC_CP14RTTRAP:
9748         case EC_CP15RTTRAP:
9749         case EC_CP14DTTRAP:
9750             /*
9751              * For a trap on AArch32 MRC/MCR/LDC/STC the Rt field is currently
9752              * the raw register field from the insn; when taking this to
9753              * AArch64 we must convert it to the AArch64 view of the register
9754              * number. Notice that we read a 4-bit AArch32 register number and
9755              * write back a 5-bit AArch64 one.
9756              */
9757             rt = extract32(env->exception.syndrome, 5, 4);
9758             rt = aarch64_regnum(env, rt);
9759             env->exception.syndrome = deposit32(env->exception.syndrome,
9760                                                 5, 5, rt);
9761             break;
9762         case EC_CP15RRTTRAP:
9763         case EC_CP14RRTTRAP:
9764             /* Similarly for MRRC/MCRR traps for Rt and Rt2 fields */
9765             rt = extract32(env->exception.syndrome, 5, 4);
9766             rt = aarch64_regnum(env, rt);
9767             env->exception.syndrome = deposit32(env->exception.syndrome,
9768                                                 5, 5, rt);
9769             rt = extract32(env->exception.syndrome, 10, 4);
9770             rt = aarch64_regnum(env, rt);
9771             env->exception.syndrome = deposit32(env->exception.syndrome,
9772                                                 10, 5, rt);
9773             break;
9774         }
9775         env->cp15.esr_el[new_el] = env->exception.syndrome;
9776         break;
9777     case EXCP_IRQ:
9778     case EXCP_VIRQ:
9779         addr += 0x80;
9780         break;
9781     case EXCP_FIQ:
9782     case EXCP_VFIQ:
9783         addr += 0x100;
9784         break;
9785     default:
9786         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9787     }
9788 
9789     if (is_a64(env)) {
9790         old_mode = pstate_read(env);
9791         aarch64_save_sp(env, arm_current_el(env));
9792         env->elr_el[new_el] = env->pc;
9793     } else {
9794         old_mode = cpsr_read(env);
9795         env->elr_el[new_el] = env->regs[15];
9796 
9797         aarch64_sync_32_to_64(env);
9798 
9799         env->condexec_bits = 0;
9800     }
9801     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
9802 
9803     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
9804                   env->elr_el[new_el]);
9805 
9806     if (cpu_isar_feature(aa64_pan, cpu)) {
9807         /* The value of PSTATE.PAN is normally preserved, except when ... */
9808         new_mode |= old_mode & PSTATE_PAN;
9809         switch (new_el) {
9810         case 2:
9811             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
9812             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
9813                 != (HCR_E2H | HCR_TGE)) {
9814                 break;
9815             }
9816             /* fall through */
9817         case 1:
9818             /* ... the target is EL1 ... */
9819             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
9820             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
9821                 new_mode |= PSTATE_PAN;
9822             }
9823             break;
9824         }
9825     }
9826     if (cpu_isar_feature(aa64_mte, cpu)) {
9827         new_mode |= PSTATE_TCO;
9828     }
9829 
9830     pstate_write(env, PSTATE_DAIF | new_mode);
9831     env->aarch64 = 1;
9832     aarch64_restore_sp(env, new_el);
9833     helper_rebuild_hflags_a64(env, new_el);
9834 
9835     env->pc = addr;
9836 
9837     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
9838                   new_el, env->pc, pstate_read(env));
9839 }
9840 
9841 /*
9842  * Do semihosting call and set the appropriate return value. All the
9843  * permission and validity checks have been done at translate time.
9844  *
9845  * We only see semihosting exceptions in TCG only as they are not
9846  * trapped to the hypervisor in KVM.
9847  */
9848 #ifdef CONFIG_TCG
9849 static void handle_semihosting(CPUState *cs)
9850 {
9851     ARMCPU *cpu = ARM_CPU(cs);
9852     CPUARMState *env = &cpu->env;
9853 
9854     if (is_a64(env)) {
9855         qemu_log_mask(CPU_LOG_INT,
9856                       "...handling as semihosting call 0x%" PRIx64 "\n",
9857                       env->xregs[0]);
9858         env->xregs[0] = do_arm_semihosting(env);
9859         env->pc += 4;
9860     } else {
9861         qemu_log_mask(CPU_LOG_INT,
9862                       "...handling as semihosting call 0x%x\n",
9863                       env->regs[0]);
9864         env->regs[0] = do_arm_semihosting(env);
9865         env->regs[15] += env->thumb ? 2 : 4;
9866     }
9867 }
9868 #endif
9869 
9870 /* Handle a CPU exception for A and R profile CPUs.
9871  * Do any appropriate logging, handle PSCI calls, and then hand off
9872  * to the AArch64-entry or AArch32-entry function depending on the
9873  * target exception level's register width.
9874  */
9875 void arm_cpu_do_interrupt(CPUState *cs)
9876 {
9877     ARMCPU *cpu = ARM_CPU(cs);
9878     CPUARMState *env = &cpu->env;
9879     unsigned int new_el = env->exception.target_el;
9880 
9881     assert(!arm_feature(env, ARM_FEATURE_M));
9882 
9883     arm_log_exception(cs->exception_index);
9884     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
9885                   new_el);
9886     if (qemu_loglevel_mask(CPU_LOG_INT)
9887         && !excp_is_internal(cs->exception_index)) {
9888         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
9889                       syn_get_ec(env->exception.syndrome),
9890                       env->exception.syndrome);
9891     }
9892 
9893     if (arm_is_psci_call(cpu, cs->exception_index)) {
9894         arm_handle_psci_call(cpu);
9895         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
9896         return;
9897     }
9898 
9899     /*
9900      * Semihosting semantics depend on the register width of the code
9901      * that caused the exception, not the target exception level, so
9902      * must be handled here.
9903      */
9904 #ifdef CONFIG_TCG
9905     if (cs->exception_index == EXCP_SEMIHOST) {
9906         handle_semihosting(cs);
9907         return;
9908     }
9909 #endif
9910 
9911     /* Hooks may change global state so BQL should be held, also the
9912      * BQL needs to be held for any modification of
9913      * cs->interrupt_request.
9914      */
9915     g_assert(qemu_mutex_iothread_locked());
9916 
9917     arm_call_pre_el_change_hook(cpu);
9918 
9919     assert(!excp_is_internal(cs->exception_index));
9920     if (arm_el_is_aa64(env, new_el)) {
9921         arm_cpu_do_interrupt_aarch64(cs);
9922     } else {
9923         arm_cpu_do_interrupt_aarch32(cs);
9924     }
9925 
9926     arm_call_el_change_hook(cpu);
9927 
9928     if (!kvm_enabled()) {
9929         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
9930     }
9931 }
9932 #endif /* !CONFIG_USER_ONLY */
9933 
9934 uint64_t arm_sctlr(CPUARMState *env, int el)
9935 {
9936     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
9937     if (el == 0) {
9938         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
9939         el = (mmu_idx == ARMMMUIdx_E20_0 ? 2 : 1);
9940     }
9941     return env->cp15.sctlr_el[el];
9942 }
9943 
9944 /* Return the SCTLR value which controls this address translation regime */
9945 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
9946 {
9947     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
9948 }
9949 
9950 #ifndef CONFIG_USER_ONLY
9951 
9952 /* Return true if the specified stage of address translation is disabled */
9953 static inline bool regime_translation_disabled(CPUARMState *env,
9954                                                ARMMMUIdx mmu_idx)
9955 {
9956     if (arm_feature(env, ARM_FEATURE_M)) {
9957         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
9958                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
9959         case R_V7M_MPU_CTRL_ENABLE_MASK:
9960             /* Enabled, but not for HardFault and NMI */
9961             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
9962         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
9963             /* Enabled for all cases */
9964             return false;
9965         case 0:
9966         default:
9967             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
9968              * we warned about that in armv7m_nvic.c when the guest set it.
9969              */
9970             return true;
9971         }
9972     }
9973 
9974     if (mmu_idx == ARMMMUIdx_Stage2) {
9975         /* HCR.DC means HCR.VM behaves as 1 */
9976         return (env->cp15.hcr_el2 & (HCR_DC | HCR_VM)) == 0;
9977     }
9978 
9979     if (env->cp15.hcr_el2 & HCR_TGE) {
9980         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
9981         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
9982             return true;
9983         }
9984     }
9985 
9986     if ((env->cp15.hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
9987         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
9988         return true;
9989     }
9990 
9991     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
9992 }
9993 
9994 static inline bool regime_translation_big_endian(CPUARMState *env,
9995                                                  ARMMMUIdx mmu_idx)
9996 {
9997     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
9998 }
9999 
10000 /* Return the TTBR associated with this translation regime */
10001 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10002                                    int ttbrn)
10003 {
10004     if (mmu_idx == ARMMMUIdx_Stage2) {
10005         return env->cp15.vttbr_el2;
10006     }
10007     if (ttbrn == 0) {
10008         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10009     } else {
10010         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10011     }
10012 }
10013 
10014 #endif /* !CONFIG_USER_ONLY */
10015 
10016 /* Convert a possible stage1+2 MMU index into the appropriate
10017  * stage 1 MMU index
10018  */
10019 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10020 {
10021     switch (mmu_idx) {
10022     case ARMMMUIdx_E10_0:
10023         return ARMMMUIdx_Stage1_E0;
10024     case ARMMMUIdx_E10_1:
10025         return ARMMMUIdx_Stage1_E1;
10026     case ARMMMUIdx_E10_1_PAN:
10027         return ARMMMUIdx_Stage1_E1_PAN;
10028     default:
10029         return mmu_idx;
10030     }
10031 }
10032 
10033 /* Return true if the translation regime is using LPAE format page tables */
10034 static inline bool regime_using_lpae_format(CPUARMState *env,
10035                                             ARMMMUIdx mmu_idx)
10036 {
10037     int el = regime_el(env, mmu_idx);
10038     if (el == 2 || arm_el_is_aa64(env, el)) {
10039         return true;
10040     }
10041     if (arm_feature(env, ARM_FEATURE_LPAE)
10042         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10043         return true;
10044     }
10045     return false;
10046 }
10047 
10048 /* Returns true if the stage 1 translation regime is using LPAE format page
10049  * tables. Used when raising alignment exceptions, whose FSR changes depending
10050  * on whether the long or short descriptor format is in use. */
10051 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10052 {
10053     mmu_idx = stage_1_mmu_idx(mmu_idx);
10054 
10055     return regime_using_lpae_format(env, mmu_idx);
10056 }
10057 
10058 #ifndef CONFIG_USER_ONLY
10059 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10060 {
10061     switch (mmu_idx) {
10062     case ARMMMUIdx_SE10_0:
10063     case ARMMMUIdx_E20_0:
10064     case ARMMMUIdx_Stage1_E0:
10065     case ARMMMUIdx_MUser:
10066     case ARMMMUIdx_MSUser:
10067     case ARMMMUIdx_MUserNegPri:
10068     case ARMMMUIdx_MSUserNegPri:
10069         return true;
10070     default:
10071         return false;
10072     case ARMMMUIdx_E10_0:
10073     case ARMMMUIdx_E10_1:
10074     case ARMMMUIdx_E10_1_PAN:
10075         g_assert_not_reached();
10076     }
10077 }
10078 
10079 /* Translate section/page access permissions to page
10080  * R/W protection flags
10081  *
10082  * @env:         CPUARMState
10083  * @mmu_idx:     MMU index indicating required translation regime
10084  * @ap:          The 3-bit access permissions (AP[2:0])
10085  * @domain_prot: The 2-bit domain access permissions
10086  */
10087 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10088                                 int ap, int domain_prot)
10089 {
10090     bool is_user = regime_is_user(env, mmu_idx);
10091 
10092     if (domain_prot == 3) {
10093         return PAGE_READ | PAGE_WRITE;
10094     }
10095 
10096     switch (ap) {
10097     case 0:
10098         if (arm_feature(env, ARM_FEATURE_V7)) {
10099             return 0;
10100         }
10101         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10102         case SCTLR_S:
10103             return is_user ? 0 : PAGE_READ;
10104         case SCTLR_R:
10105             return PAGE_READ;
10106         default:
10107             return 0;
10108         }
10109     case 1:
10110         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10111     case 2:
10112         if (is_user) {
10113             return PAGE_READ;
10114         } else {
10115             return PAGE_READ | PAGE_WRITE;
10116         }
10117     case 3:
10118         return PAGE_READ | PAGE_WRITE;
10119     case 4: /* Reserved.  */
10120         return 0;
10121     case 5:
10122         return is_user ? 0 : PAGE_READ;
10123     case 6:
10124         return PAGE_READ;
10125     case 7:
10126         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10127             return 0;
10128         }
10129         return PAGE_READ;
10130     default:
10131         g_assert_not_reached();
10132     }
10133 }
10134 
10135 /* Translate section/page access permissions to page
10136  * R/W protection flags.
10137  *
10138  * @ap:      The 2-bit simple AP (AP[2:1])
10139  * @is_user: TRUE if accessing from PL0
10140  */
10141 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10142 {
10143     switch (ap) {
10144     case 0:
10145         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10146     case 1:
10147         return PAGE_READ | PAGE_WRITE;
10148     case 2:
10149         return is_user ? 0 : PAGE_READ;
10150     case 3:
10151         return PAGE_READ;
10152     default:
10153         g_assert_not_reached();
10154     }
10155 }
10156 
10157 static inline int
10158 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10159 {
10160     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10161 }
10162 
10163 /* Translate S2 section/page access permissions to protection flags
10164  *
10165  * @env:     CPUARMState
10166  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10167  * @xn:      XN (execute-never) bits
10168  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
10169  */
10170 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
10171 {
10172     int prot = 0;
10173 
10174     if (s2ap & 1) {
10175         prot |= PAGE_READ;
10176     }
10177     if (s2ap & 2) {
10178         prot |= PAGE_WRITE;
10179     }
10180 
10181     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
10182         switch (xn) {
10183         case 0:
10184             prot |= PAGE_EXEC;
10185             break;
10186         case 1:
10187             if (s1_is_el0) {
10188                 prot |= PAGE_EXEC;
10189             }
10190             break;
10191         case 2:
10192             break;
10193         case 3:
10194             if (!s1_is_el0) {
10195                 prot |= PAGE_EXEC;
10196             }
10197             break;
10198         default:
10199             g_assert_not_reached();
10200         }
10201     } else {
10202         if (!extract32(xn, 1, 1)) {
10203             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10204                 prot |= PAGE_EXEC;
10205             }
10206         }
10207     }
10208     return prot;
10209 }
10210 
10211 /* Translate section/page access permissions to protection flags
10212  *
10213  * @env:     CPUARMState
10214  * @mmu_idx: MMU index indicating required translation regime
10215  * @is_aa64: TRUE if AArch64
10216  * @ap:      The 2-bit simple AP (AP[2:1])
10217  * @ns:      NS (non-secure) bit
10218  * @xn:      XN (execute-never) bit
10219  * @pxn:     PXN (privileged execute-never) bit
10220  */
10221 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10222                       int ap, int ns, int xn, int pxn)
10223 {
10224     bool is_user = regime_is_user(env, mmu_idx);
10225     int prot_rw, user_rw;
10226     bool have_wxn;
10227     int wxn = 0;
10228 
10229     assert(mmu_idx != ARMMMUIdx_Stage2);
10230 
10231     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10232     if (is_user) {
10233         prot_rw = user_rw;
10234     } else {
10235         if (user_rw && regime_is_pan(env, mmu_idx)) {
10236             /* PAN forbids data accesses but doesn't affect insn fetch */
10237             prot_rw = 0;
10238         } else {
10239             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10240         }
10241     }
10242 
10243     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10244         return prot_rw;
10245     }
10246 
10247     /* TODO have_wxn should be replaced with
10248      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10249      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10250      * compatible processors have EL2, which is required for [U]WXN.
10251      */
10252     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10253 
10254     if (have_wxn) {
10255         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10256     }
10257 
10258     if (is_aa64) {
10259         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10260             xn = pxn || (user_rw & PAGE_WRITE);
10261         }
10262     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10263         switch (regime_el(env, mmu_idx)) {
10264         case 1:
10265         case 3:
10266             if (is_user) {
10267                 xn = xn || !(user_rw & PAGE_READ);
10268             } else {
10269                 int uwxn = 0;
10270                 if (have_wxn) {
10271                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10272                 }
10273                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10274                      (uwxn && (user_rw & PAGE_WRITE));
10275             }
10276             break;
10277         case 2:
10278             break;
10279         }
10280     } else {
10281         xn = wxn = 0;
10282     }
10283 
10284     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10285         return prot_rw;
10286     }
10287     return prot_rw | PAGE_EXEC;
10288 }
10289 
10290 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10291                                      uint32_t *table, uint32_t address)
10292 {
10293     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10294     TCR *tcr = regime_tcr(env, mmu_idx);
10295 
10296     if (address & tcr->mask) {
10297         if (tcr->raw_tcr & TTBCR_PD1) {
10298             /* Translation table walk disabled for TTBR1 */
10299             return false;
10300         }
10301         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10302     } else {
10303         if (tcr->raw_tcr & TTBCR_PD0) {
10304             /* Translation table walk disabled for TTBR0 */
10305             return false;
10306         }
10307         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10308     }
10309     *table |= (address >> 18) & 0x3ffc;
10310     return true;
10311 }
10312 
10313 /* Translate a S1 pagetable walk through S2 if needed.  */
10314 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10315                                hwaddr addr, MemTxAttrs txattrs,
10316                                ARMMMUFaultInfo *fi)
10317 {
10318     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10319         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10320         target_ulong s2size;
10321         hwaddr s2pa;
10322         int s2prot;
10323         int ret;
10324         ARMCacheAttrs cacheattrs = {};
10325 
10326         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, ARMMMUIdx_Stage2,
10327                                  false,
10328                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10329                                  &cacheattrs);
10330         if (ret) {
10331             assert(fi->type != ARMFault_None);
10332             fi->s2addr = addr;
10333             fi->stage2 = true;
10334             fi->s1ptw = true;
10335             return ~0;
10336         }
10337         if ((env->cp15.hcr_el2 & HCR_PTW) && (cacheattrs.attrs & 0xf0) == 0) {
10338             /*
10339              * PTW set and S1 walk touched S2 Device memory:
10340              * generate Permission fault.
10341              */
10342             fi->type = ARMFault_Permission;
10343             fi->s2addr = addr;
10344             fi->stage2 = true;
10345             fi->s1ptw = true;
10346             return ~0;
10347         }
10348         addr = s2pa;
10349     }
10350     return addr;
10351 }
10352 
10353 /* All loads done in the course of a page table walk go through here. */
10354 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10355                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10356 {
10357     ARMCPU *cpu = ARM_CPU(cs);
10358     CPUARMState *env = &cpu->env;
10359     MemTxAttrs attrs = {};
10360     MemTxResult result = MEMTX_OK;
10361     AddressSpace *as;
10362     uint32_t data;
10363 
10364     attrs.secure = is_secure;
10365     as = arm_addressspace(cs, attrs);
10366     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10367     if (fi->s1ptw) {
10368         return 0;
10369     }
10370     if (regime_translation_big_endian(env, mmu_idx)) {
10371         data = address_space_ldl_be(as, addr, attrs, &result);
10372     } else {
10373         data = address_space_ldl_le(as, addr, attrs, &result);
10374     }
10375     if (result == MEMTX_OK) {
10376         return data;
10377     }
10378     fi->type = ARMFault_SyncExternalOnWalk;
10379     fi->ea = arm_extabort_type(result);
10380     return 0;
10381 }
10382 
10383 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10384                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10385 {
10386     ARMCPU *cpu = ARM_CPU(cs);
10387     CPUARMState *env = &cpu->env;
10388     MemTxAttrs attrs = {};
10389     MemTxResult result = MEMTX_OK;
10390     AddressSpace *as;
10391     uint64_t data;
10392 
10393     attrs.secure = is_secure;
10394     as = arm_addressspace(cs, attrs);
10395     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10396     if (fi->s1ptw) {
10397         return 0;
10398     }
10399     if (regime_translation_big_endian(env, mmu_idx)) {
10400         data = address_space_ldq_be(as, addr, attrs, &result);
10401     } else {
10402         data = address_space_ldq_le(as, addr, attrs, &result);
10403     }
10404     if (result == MEMTX_OK) {
10405         return data;
10406     }
10407     fi->type = ARMFault_SyncExternalOnWalk;
10408     fi->ea = arm_extabort_type(result);
10409     return 0;
10410 }
10411 
10412 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10413                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10414                              hwaddr *phys_ptr, int *prot,
10415                              target_ulong *page_size,
10416                              ARMMMUFaultInfo *fi)
10417 {
10418     CPUState *cs = env_cpu(env);
10419     int level = 1;
10420     uint32_t table;
10421     uint32_t desc;
10422     int type;
10423     int ap;
10424     int domain = 0;
10425     int domain_prot;
10426     hwaddr phys_addr;
10427     uint32_t dacr;
10428 
10429     /* Pagetable walk.  */
10430     /* Lookup l1 descriptor.  */
10431     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10432         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10433         fi->type = ARMFault_Translation;
10434         goto do_fault;
10435     }
10436     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10437                        mmu_idx, fi);
10438     if (fi->type != ARMFault_None) {
10439         goto do_fault;
10440     }
10441     type = (desc & 3);
10442     domain = (desc >> 5) & 0x0f;
10443     if (regime_el(env, mmu_idx) == 1) {
10444         dacr = env->cp15.dacr_ns;
10445     } else {
10446         dacr = env->cp15.dacr_s;
10447     }
10448     domain_prot = (dacr >> (domain * 2)) & 3;
10449     if (type == 0) {
10450         /* Section translation fault.  */
10451         fi->type = ARMFault_Translation;
10452         goto do_fault;
10453     }
10454     if (type != 2) {
10455         level = 2;
10456     }
10457     if (domain_prot == 0 || domain_prot == 2) {
10458         fi->type = ARMFault_Domain;
10459         goto do_fault;
10460     }
10461     if (type == 2) {
10462         /* 1Mb section.  */
10463         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10464         ap = (desc >> 10) & 3;
10465         *page_size = 1024 * 1024;
10466     } else {
10467         /* Lookup l2 entry.  */
10468         if (type == 1) {
10469             /* Coarse pagetable.  */
10470             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10471         } else {
10472             /* Fine pagetable.  */
10473             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10474         }
10475         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10476                            mmu_idx, fi);
10477         if (fi->type != ARMFault_None) {
10478             goto do_fault;
10479         }
10480         switch (desc & 3) {
10481         case 0: /* Page translation fault.  */
10482             fi->type = ARMFault_Translation;
10483             goto do_fault;
10484         case 1: /* 64k page.  */
10485             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10486             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10487             *page_size = 0x10000;
10488             break;
10489         case 2: /* 4k page.  */
10490             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10491             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10492             *page_size = 0x1000;
10493             break;
10494         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10495             if (type == 1) {
10496                 /* ARMv6/XScale extended small page format */
10497                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10498                     || arm_feature(env, ARM_FEATURE_V6)) {
10499                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10500                     *page_size = 0x1000;
10501                 } else {
10502                     /* UNPREDICTABLE in ARMv5; we choose to take a
10503                      * page translation fault.
10504                      */
10505                     fi->type = ARMFault_Translation;
10506                     goto do_fault;
10507                 }
10508             } else {
10509                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10510                 *page_size = 0x400;
10511             }
10512             ap = (desc >> 4) & 3;
10513             break;
10514         default:
10515             /* Never happens, but compiler isn't smart enough to tell.  */
10516             abort();
10517         }
10518     }
10519     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10520     *prot |= *prot ? PAGE_EXEC : 0;
10521     if (!(*prot & (1 << access_type))) {
10522         /* Access permission fault.  */
10523         fi->type = ARMFault_Permission;
10524         goto do_fault;
10525     }
10526     *phys_ptr = phys_addr;
10527     return false;
10528 do_fault:
10529     fi->domain = domain;
10530     fi->level = level;
10531     return true;
10532 }
10533 
10534 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10535                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10536                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10537                              target_ulong *page_size, ARMMMUFaultInfo *fi)
10538 {
10539     CPUState *cs = env_cpu(env);
10540     int level = 1;
10541     uint32_t table;
10542     uint32_t desc;
10543     uint32_t xn;
10544     uint32_t pxn = 0;
10545     int type;
10546     int ap;
10547     int domain = 0;
10548     int domain_prot;
10549     hwaddr phys_addr;
10550     uint32_t dacr;
10551     bool ns;
10552 
10553     /* Pagetable walk.  */
10554     /* Lookup l1 descriptor.  */
10555     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10556         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10557         fi->type = ARMFault_Translation;
10558         goto do_fault;
10559     }
10560     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10561                        mmu_idx, fi);
10562     if (fi->type != ARMFault_None) {
10563         goto do_fault;
10564     }
10565     type = (desc & 3);
10566     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
10567         /* Section translation fault, or attempt to use the encoding
10568          * which is Reserved on implementations without PXN.
10569          */
10570         fi->type = ARMFault_Translation;
10571         goto do_fault;
10572     }
10573     if ((type == 1) || !(desc & (1 << 18))) {
10574         /* Page or Section.  */
10575         domain = (desc >> 5) & 0x0f;
10576     }
10577     if (regime_el(env, mmu_idx) == 1) {
10578         dacr = env->cp15.dacr_ns;
10579     } else {
10580         dacr = env->cp15.dacr_s;
10581     }
10582     if (type == 1) {
10583         level = 2;
10584     }
10585     domain_prot = (dacr >> (domain * 2)) & 3;
10586     if (domain_prot == 0 || domain_prot == 2) {
10587         /* Section or Page domain fault */
10588         fi->type = ARMFault_Domain;
10589         goto do_fault;
10590     }
10591     if (type != 1) {
10592         if (desc & (1 << 18)) {
10593             /* Supersection.  */
10594             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
10595             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
10596             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
10597             *page_size = 0x1000000;
10598         } else {
10599             /* Section.  */
10600             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10601             *page_size = 0x100000;
10602         }
10603         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
10604         xn = desc & (1 << 4);
10605         pxn = desc & 1;
10606         ns = extract32(desc, 19, 1);
10607     } else {
10608         if (arm_feature(env, ARM_FEATURE_PXN)) {
10609             pxn = (desc >> 2) & 1;
10610         }
10611         ns = extract32(desc, 3, 1);
10612         /* Lookup l2 entry.  */
10613         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10614         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10615                            mmu_idx, fi);
10616         if (fi->type != ARMFault_None) {
10617             goto do_fault;
10618         }
10619         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
10620         switch (desc & 3) {
10621         case 0: /* Page translation fault.  */
10622             fi->type = ARMFault_Translation;
10623             goto do_fault;
10624         case 1: /* 64k page.  */
10625             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10626             xn = desc & (1 << 15);
10627             *page_size = 0x10000;
10628             break;
10629         case 2: case 3: /* 4k page.  */
10630             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10631             xn = desc & 1;
10632             *page_size = 0x1000;
10633             break;
10634         default:
10635             /* Never happens, but compiler isn't smart enough to tell.  */
10636             abort();
10637         }
10638     }
10639     if (domain_prot == 3) {
10640         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10641     } else {
10642         if (pxn && !regime_is_user(env, mmu_idx)) {
10643             xn = 1;
10644         }
10645         if (xn && access_type == MMU_INST_FETCH) {
10646             fi->type = ARMFault_Permission;
10647             goto do_fault;
10648         }
10649 
10650         if (arm_feature(env, ARM_FEATURE_V6K) &&
10651                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
10652             /* The simplified model uses AP[0] as an access control bit.  */
10653             if ((ap & 1) == 0) {
10654                 /* Access flag fault.  */
10655                 fi->type = ARMFault_AccessFlag;
10656                 goto do_fault;
10657             }
10658             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
10659         } else {
10660             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10661         }
10662         if (*prot && !xn) {
10663             *prot |= PAGE_EXEC;
10664         }
10665         if (!(*prot & (1 << access_type))) {
10666             /* Access permission fault.  */
10667             fi->type = ARMFault_Permission;
10668             goto do_fault;
10669         }
10670     }
10671     if (ns) {
10672         /* The NS bit will (as required by the architecture) have no effect if
10673          * the CPU doesn't support TZ or this is a non-secure translation
10674          * regime, because the attribute will already be non-secure.
10675          */
10676         attrs->secure = false;
10677     }
10678     *phys_ptr = phys_addr;
10679     return false;
10680 do_fault:
10681     fi->domain = domain;
10682     fi->level = level;
10683     return true;
10684 }
10685 
10686 /*
10687  * check_s2_mmu_setup
10688  * @cpu:        ARMCPU
10689  * @is_aa64:    True if the translation regime is in AArch64 state
10690  * @startlevel: Suggested starting level
10691  * @inputsize:  Bitsize of IPAs
10692  * @stride:     Page-table stride (See the ARM ARM)
10693  *
10694  * Returns true if the suggested S2 translation parameters are OK and
10695  * false otherwise.
10696  */
10697 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
10698                                int inputsize, int stride)
10699 {
10700     const int grainsize = stride + 3;
10701     int startsizecheck;
10702 
10703     /* Negative levels are never allowed.  */
10704     if (level < 0) {
10705         return false;
10706     }
10707 
10708     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
10709     if (startsizecheck < 1 || startsizecheck > stride + 4) {
10710         return false;
10711     }
10712 
10713     if (is_aa64) {
10714         CPUARMState *env = &cpu->env;
10715         unsigned int pamax = arm_pamax(cpu);
10716 
10717         switch (stride) {
10718         case 13: /* 64KB Pages.  */
10719             if (level == 0 || (level == 1 && pamax <= 42)) {
10720                 return false;
10721             }
10722             break;
10723         case 11: /* 16KB Pages.  */
10724             if (level == 0 || (level == 1 && pamax <= 40)) {
10725                 return false;
10726             }
10727             break;
10728         case 9: /* 4KB Pages.  */
10729             if (level == 0 && pamax <= 42) {
10730                 return false;
10731             }
10732             break;
10733         default:
10734             g_assert_not_reached();
10735         }
10736 
10737         /* Inputsize checks.  */
10738         if (inputsize > pamax &&
10739             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
10740             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
10741             return false;
10742         }
10743     } else {
10744         /* AArch32 only supports 4KB pages. Assert on that.  */
10745         assert(stride == 9);
10746 
10747         if (level == 0) {
10748             return false;
10749         }
10750     }
10751     return true;
10752 }
10753 
10754 /* Translate from the 4-bit stage 2 representation of
10755  * memory attributes (without cache-allocation hints) to
10756  * the 8-bit representation of the stage 1 MAIR registers
10757  * (which includes allocation hints).
10758  *
10759  * ref: shared/translation/attrs/S2AttrDecode()
10760  *      .../S2ConvertAttrsHints()
10761  */
10762 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
10763 {
10764     uint8_t hiattr = extract32(s2attrs, 2, 2);
10765     uint8_t loattr = extract32(s2attrs, 0, 2);
10766     uint8_t hihint = 0, lohint = 0;
10767 
10768     if (hiattr != 0) { /* normal memory */
10769         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
10770             hiattr = loattr = 1; /* non-cacheable */
10771         } else {
10772             if (hiattr != 1) { /* Write-through or write-back */
10773                 hihint = 3; /* RW allocate */
10774             }
10775             if (loattr != 1) { /* Write-through or write-back */
10776                 lohint = 3; /* RW allocate */
10777             }
10778         }
10779     }
10780 
10781     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
10782 }
10783 #endif /* !CONFIG_USER_ONLY */
10784 
10785 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
10786 {
10787     if (regime_has_2_ranges(mmu_idx)) {
10788         return extract64(tcr, 37, 2);
10789     } else if (mmu_idx == ARMMMUIdx_Stage2) {
10790         return 0; /* VTCR_EL2 */
10791     } else {
10792         /* Replicate the single TBI bit so we always have 2 bits.  */
10793         return extract32(tcr, 20, 1) * 3;
10794     }
10795 }
10796 
10797 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
10798 {
10799     if (regime_has_2_ranges(mmu_idx)) {
10800         return extract64(tcr, 51, 2);
10801     } else if (mmu_idx == ARMMMUIdx_Stage2) {
10802         return 0; /* VTCR_EL2 */
10803     } else {
10804         /* Replicate the single TBID bit so we always have 2 bits.  */
10805         return extract32(tcr, 29, 1) * 3;
10806     }
10807 }
10808 
10809 static int aa64_va_parameter_tcma(uint64_t tcr, ARMMMUIdx mmu_idx)
10810 {
10811     if (regime_has_2_ranges(mmu_idx)) {
10812         return extract64(tcr, 57, 2);
10813     } else {
10814         /* Replicate the single TCMA bit so we always have 2 bits.  */
10815         return extract32(tcr, 30, 1) * 3;
10816     }
10817 }
10818 
10819 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
10820                                    ARMMMUIdx mmu_idx, bool data)
10821 {
10822     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
10823     bool epd, hpd, using16k, using64k;
10824     int select, tsz, tbi;
10825 
10826     if (!regime_has_2_ranges(mmu_idx)) {
10827         select = 0;
10828         tsz = extract32(tcr, 0, 6);
10829         using64k = extract32(tcr, 14, 1);
10830         using16k = extract32(tcr, 15, 1);
10831         if (mmu_idx == ARMMMUIdx_Stage2) {
10832             /* VTCR_EL2 */
10833             hpd = false;
10834         } else {
10835             hpd = extract32(tcr, 24, 1);
10836         }
10837         epd = false;
10838     } else {
10839         /*
10840          * Bit 55 is always between the two regions, and is canonical for
10841          * determining if address tagging is enabled.
10842          */
10843         select = extract64(va, 55, 1);
10844         if (!select) {
10845             tsz = extract32(tcr, 0, 6);
10846             epd = extract32(tcr, 7, 1);
10847             using64k = extract32(tcr, 14, 1);
10848             using16k = extract32(tcr, 15, 1);
10849             hpd = extract64(tcr, 41, 1);
10850         } else {
10851             int tg = extract32(tcr, 30, 2);
10852             using16k = tg == 1;
10853             using64k = tg == 3;
10854             tsz = extract32(tcr, 16, 6);
10855             epd = extract32(tcr, 23, 1);
10856             hpd = extract64(tcr, 42, 1);
10857         }
10858     }
10859     tsz = MIN(tsz, 39);  /* TODO: ARMv8.4-TTST */
10860     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
10861 
10862     /* Present TBI as a composite with TBID.  */
10863     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
10864     if (!data) {
10865         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
10866     }
10867     tbi = (tbi >> select) & 1;
10868 
10869     return (ARMVAParameters) {
10870         .tsz = tsz,
10871         .select = select,
10872         .tbi = tbi,
10873         .epd = epd,
10874         .hpd = hpd,
10875         .using16k = using16k,
10876         .using64k = using64k,
10877     };
10878 }
10879 
10880 #ifndef CONFIG_USER_ONLY
10881 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
10882                                           ARMMMUIdx mmu_idx)
10883 {
10884     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
10885     uint32_t el = regime_el(env, mmu_idx);
10886     int select, tsz;
10887     bool epd, hpd;
10888 
10889     if (mmu_idx == ARMMMUIdx_Stage2) {
10890         /* VTCR */
10891         bool sext = extract32(tcr, 4, 1);
10892         bool sign = extract32(tcr, 3, 1);
10893 
10894         /*
10895          * If the sign-extend bit is not the same as t0sz[3], the result
10896          * is unpredictable. Flag this as a guest error.
10897          */
10898         if (sign != sext) {
10899             qemu_log_mask(LOG_GUEST_ERROR,
10900                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
10901         }
10902         tsz = sextract32(tcr, 0, 4) + 8;
10903         select = 0;
10904         hpd = false;
10905         epd = false;
10906     } else if (el == 2) {
10907         /* HTCR */
10908         tsz = extract32(tcr, 0, 3);
10909         select = 0;
10910         hpd = extract64(tcr, 24, 1);
10911         epd = false;
10912     } else {
10913         int t0sz = extract32(tcr, 0, 3);
10914         int t1sz = extract32(tcr, 16, 3);
10915 
10916         if (t1sz == 0) {
10917             select = va > (0xffffffffu >> t0sz);
10918         } else {
10919             /* Note that we will detect errors later.  */
10920             select = va >= ~(0xffffffffu >> t1sz);
10921         }
10922         if (!select) {
10923             tsz = t0sz;
10924             epd = extract32(tcr, 7, 1);
10925             hpd = extract64(tcr, 41, 1);
10926         } else {
10927             tsz = t1sz;
10928             epd = extract32(tcr, 23, 1);
10929             hpd = extract64(tcr, 42, 1);
10930         }
10931         /* For aarch32, hpd0 is not enabled without t2e as well.  */
10932         hpd &= extract32(tcr, 6, 1);
10933     }
10934 
10935     return (ARMVAParameters) {
10936         .tsz = tsz,
10937         .select = select,
10938         .epd = epd,
10939         .hpd = hpd,
10940     };
10941 }
10942 
10943 /**
10944  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
10945  *
10946  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
10947  * prot and page_size may not be filled in, and the populated fsr value provides
10948  * information on why the translation aborted, in the format of a long-format
10949  * DFSR/IFSR fault register, with the following caveats:
10950  *  * the WnR bit is never set (the caller must do this).
10951  *
10952  * @env: CPUARMState
10953  * @address: virtual address to get physical address for
10954  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
10955  * @mmu_idx: MMU index indicating required translation regime
10956  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
10957  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
10958  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
10959  * @phys_ptr: set to the physical address corresponding to the virtual address
10960  * @attrs: set to the memory transaction attributes to use
10961  * @prot: set to the permissions for the page containing phys_ptr
10962  * @page_size_ptr: set to the size of the page containing phys_ptr
10963  * @fi: set to fault info if the translation fails
10964  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
10965  */
10966 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
10967                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
10968                                bool s1_is_el0,
10969                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
10970                                target_ulong *page_size_ptr,
10971                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10972 {
10973     ARMCPU *cpu = env_archcpu(env);
10974     CPUState *cs = CPU(cpu);
10975     /* Read an LPAE long-descriptor translation table. */
10976     ARMFaultType fault_type = ARMFault_Translation;
10977     uint32_t level;
10978     ARMVAParameters param;
10979     uint64_t ttbr;
10980     hwaddr descaddr, indexmask, indexmask_grainsize;
10981     uint32_t tableattrs;
10982     target_ulong page_size;
10983     uint32_t attrs;
10984     int32_t stride;
10985     int addrsize, inputsize;
10986     TCR *tcr = regime_tcr(env, mmu_idx);
10987     int ap, ns, xn, pxn;
10988     uint32_t el = regime_el(env, mmu_idx);
10989     uint64_t descaddrmask;
10990     bool aarch64 = arm_el_is_aa64(env, el);
10991     bool guarded = false;
10992 
10993     /* TODO: This code does not support shareability levels. */
10994     if (aarch64) {
10995         param = aa64_va_parameters(env, address, mmu_idx,
10996                                    access_type != MMU_INST_FETCH);
10997         level = 0;
10998         addrsize = 64 - 8 * param.tbi;
10999         inputsize = 64 - param.tsz;
11000     } else {
11001         param = aa32_va_parameters(env, address, mmu_idx);
11002         level = 1;
11003         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
11004         inputsize = addrsize - param.tsz;
11005     }
11006 
11007     /*
11008      * We determined the region when collecting the parameters, but we
11009      * have not yet validated that the address is valid for the region.
11010      * Extract the top bits and verify that they all match select.
11011      *
11012      * For aa32, if inputsize == addrsize, then we have selected the
11013      * region by exclusion in aa32_va_parameters and there is no more
11014      * validation to do here.
11015      */
11016     if (inputsize < addrsize) {
11017         target_ulong top_bits = sextract64(address, inputsize,
11018                                            addrsize - inputsize);
11019         if (-top_bits != param.select) {
11020             /* The gap between the two regions is a Translation fault */
11021             fault_type = ARMFault_Translation;
11022             goto do_fault;
11023         }
11024     }
11025 
11026     if (param.using64k) {
11027         stride = 13;
11028     } else if (param.using16k) {
11029         stride = 11;
11030     } else {
11031         stride = 9;
11032     }
11033 
11034     /* Note that QEMU ignores shareability and cacheability attributes,
11035      * so we don't need to do anything with the SH, ORGN, IRGN fields
11036      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11037      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11038      * implement any ASID-like capability so we can ignore it (instead
11039      * we will always flush the TLB any time the ASID is changed).
11040      */
11041     ttbr = regime_ttbr(env, mmu_idx, param.select);
11042 
11043     /* Here we should have set up all the parameters for the translation:
11044      * inputsize, ttbr, epd, stride, tbi
11045      */
11046 
11047     if (param.epd) {
11048         /* Translation table walk disabled => Translation fault on TLB miss
11049          * Note: This is always 0 on 64-bit EL2 and EL3.
11050          */
11051         goto do_fault;
11052     }
11053 
11054     if (mmu_idx != ARMMMUIdx_Stage2) {
11055         /* The starting level depends on the virtual address size (which can
11056          * be up to 48 bits) and the translation granule size. It indicates
11057          * the number of strides (stride bits at a time) needed to
11058          * consume the bits of the input address. In the pseudocode this is:
11059          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11060          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11061          * our 'stride + 3' and 'stride' is our 'stride'.
11062          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11063          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11064          * = 4 - (inputsize - 4) / stride;
11065          */
11066         level = 4 - (inputsize - 4) / stride;
11067     } else {
11068         /* For stage 2 translations the starting level is specified by the
11069          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11070          */
11071         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11072         uint32_t startlevel;
11073         bool ok;
11074 
11075         if (!aarch64 || stride == 9) {
11076             /* AArch32 or 4KB pages */
11077             startlevel = 2 - sl0;
11078         } else {
11079             /* 16KB or 64KB pages */
11080             startlevel = 3 - sl0;
11081         }
11082 
11083         /* Check that the starting level is valid. */
11084         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11085                                 inputsize, stride);
11086         if (!ok) {
11087             fault_type = ARMFault_Translation;
11088             goto do_fault;
11089         }
11090         level = startlevel;
11091     }
11092 
11093     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
11094     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
11095 
11096     /* Now we can extract the actual base address from the TTBR */
11097     descaddr = extract64(ttbr, 0, 48);
11098     /*
11099      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
11100      * and also to mask out CnP (bit 0) which could validly be non-zero.
11101      */
11102     descaddr &= ~indexmask;
11103 
11104     /* The address field in the descriptor goes up to bit 39 for ARMv7
11105      * but up to bit 47 for ARMv8, but we use the descaddrmask
11106      * up to bit 39 for AArch32, because we don't need other bits in that case
11107      * to construct next descriptor address (anyway they should be all zeroes).
11108      */
11109     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
11110                    ~indexmask_grainsize;
11111 
11112     /* Secure accesses start with the page table in secure memory and
11113      * can be downgraded to non-secure at any step. Non-secure accesses
11114      * remain non-secure. We implement this by just ORing in the NSTable/NS
11115      * bits at each step.
11116      */
11117     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11118     for (;;) {
11119         uint64_t descriptor;
11120         bool nstable;
11121 
11122         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11123         descaddr &= ~7ULL;
11124         nstable = extract32(tableattrs, 4, 1);
11125         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11126         if (fi->type != ARMFault_None) {
11127             goto do_fault;
11128         }
11129 
11130         if (!(descriptor & 1) ||
11131             (!(descriptor & 2) && (level == 3))) {
11132             /* Invalid, or the Reserved level 3 encoding */
11133             goto do_fault;
11134         }
11135         descaddr = descriptor & descaddrmask;
11136 
11137         if ((descriptor & 2) && (level < 3)) {
11138             /* Table entry. The top five bits are attributes which may
11139              * propagate down through lower levels of the table (and
11140              * which are all arranged so that 0 means "no effect", so
11141              * we can gather them up by ORing in the bits at each level).
11142              */
11143             tableattrs |= extract64(descriptor, 59, 5);
11144             level++;
11145             indexmask = indexmask_grainsize;
11146             continue;
11147         }
11148         /* Block entry at level 1 or 2, or page entry at level 3.
11149          * These are basically the same thing, although the number
11150          * of bits we pull in from the vaddr varies.
11151          */
11152         page_size = (1ULL << ((stride * (4 - level)) + 3));
11153         descaddr |= (address & (page_size - 1));
11154         /* Extract attributes from the descriptor */
11155         attrs = extract64(descriptor, 2, 10)
11156             | (extract64(descriptor, 52, 12) << 10);
11157 
11158         if (mmu_idx == ARMMMUIdx_Stage2) {
11159             /* Stage 2 table descriptors do not include any attribute fields */
11160             break;
11161         }
11162         /* Merge in attributes from table descriptors */
11163         attrs |= nstable << 3; /* NS */
11164         guarded = extract64(descriptor, 50, 1);  /* GP */
11165         if (param.hpd) {
11166             /* HPD disables all the table attributes except NSTable.  */
11167             break;
11168         }
11169         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11170         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11171          * means "force PL1 access only", which means forcing AP[1] to 0.
11172          */
11173         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11174         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11175         break;
11176     }
11177     /* Here descaddr is the final physical address, and attributes
11178      * are all in attrs.
11179      */
11180     fault_type = ARMFault_AccessFlag;
11181     if ((attrs & (1 << 8)) == 0) {
11182         /* Access flag */
11183         goto do_fault;
11184     }
11185 
11186     ap = extract32(attrs, 4, 2);
11187 
11188     if (mmu_idx == ARMMMUIdx_Stage2) {
11189         ns = true;
11190         xn = extract32(attrs, 11, 2);
11191         *prot = get_S2prot(env, ap, xn, s1_is_el0);
11192     } else {
11193         ns = extract32(attrs, 3, 1);
11194         xn = extract32(attrs, 12, 1);
11195         pxn = extract32(attrs, 11, 1);
11196         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11197     }
11198 
11199     fault_type = ARMFault_Permission;
11200     if (!(*prot & (1 << access_type))) {
11201         goto do_fault;
11202     }
11203 
11204     if (ns) {
11205         /* The NS bit will (as required by the architecture) have no effect if
11206          * the CPU doesn't support TZ or this is a non-secure translation
11207          * regime, because the attribute will already be non-secure.
11208          */
11209         txattrs->secure = false;
11210     }
11211     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11212     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11213         arm_tlb_bti_gp(txattrs) = true;
11214     }
11215 
11216     if (mmu_idx == ARMMMUIdx_Stage2) {
11217         cacheattrs->attrs = convert_stage2_attrs(env, extract32(attrs, 0, 4));
11218     } else {
11219         /* Index into MAIR registers for cache attributes */
11220         uint8_t attrindx = extract32(attrs, 0, 3);
11221         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11222         assert(attrindx <= 7);
11223         cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11224     }
11225     cacheattrs->shareability = extract32(attrs, 6, 2);
11226 
11227     *phys_ptr = descaddr;
11228     *page_size_ptr = page_size;
11229     return false;
11230 
11231 do_fault:
11232     fi->type = fault_type;
11233     fi->level = level;
11234     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11235     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2);
11236     return true;
11237 }
11238 
11239 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11240                                                 ARMMMUIdx mmu_idx,
11241                                                 int32_t address, int *prot)
11242 {
11243     if (!arm_feature(env, ARM_FEATURE_M)) {
11244         *prot = PAGE_READ | PAGE_WRITE;
11245         switch (address) {
11246         case 0xF0000000 ... 0xFFFFFFFF:
11247             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11248                 /* hivecs execing is ok */
11249                 *prot |= PAGE_EXEC;
11250             }
11251             break;
11252         case 0x00000000 ... 0x7FFFFFFF:
11253             *prot |= PAGE_EXEC;
11254             break;
11255         }
11256     } else {
11257         /* Default system address map for M profile cores.
11258          * The architecture specifies which regions are execute-never;
11259          * at the MPU level no other checks are defined.
11260          */
11261         switch (address) {
11262         case 0x00000000 ... 0x1fffffff: /* ROM */
11263         case 0x20000000 ... 0x3fffffff: /* SRAM */
11264         case 0x60000000 ... 0x7fffffff: /* RAM */
11265         case 0x80000000 ... 0x9fffffff: /* RAM */
11266             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11267             break;
11268         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11269         case 0xa0000000 ... 0xbfffffff: /* Device */
11270         case 0xc0000000 ... 0xdfffffff: /* Device */
11271         case 0xe0000000 ... 0xffffffff: /* System */
11272             *prot = PAGE_READ | PAGE_WRITE;
11273             break;
11274         default:
11275             g_assert_not_reached();
11276         }
11277     }
11278 }
11279 
11280 static bool pmsav7_use_background_region(ARMCPU *cpu,
11281                                          ARMMMUIdx mmu_idx, bool is_user)
11282 {
11283     /* Return true if we should use the default memory map as a
11284      * "background" region if there are no hits against any MPU regions.
11285      */
11286     CPUARMState *env = &cpu->env;
11287 
11288     if (is_user) {
11289         return false;
11290     }
11291 
11292     if (arm_feature(env, ARM_FEATURE_M)) {
11293         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11294             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11295     } else {
11296         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11297     }
11298 }
11299 
11300 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11301 {
11302     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11303     return arm_feature(env, ARM_FEATURE_M) &&
11304         extract32(address, 20, 12) == 0xe00;
11305 }
11306 
11307 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11308 {
11309     /* True if address is in the M profile system region
11310      * 0xe0000000 - 0xffffffff
11311      */
11312     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11313 }
11314 
11315 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11316                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11317                                  hwaddr *phys_ptr, int *prot,
11318                                  target_ulong *page_size,
11319                                  ARMMMUFaultInfo *fi)
11320 {
11321     ARMCPU *cpu = env_archcpu(env);
11322     int n;
11323     bool is_user = regime_is_user(env, mmu_idx);
11324 
11325     *phys_ptr = address;
11326     *page_size = TARGET_PAGE_SIZE;
11327     *prot = 0;
11328 
11329     if (regime_translation_disabled(env, mmu_idx) ||
11330         m_is_ppb_region(env, address)) {
11331         /* MPU disabled or M profile PPB access: use default memory map.
11332          * The other case which uses the default memory map in the
11333          * v7M ARM ARM pseudocode is exception vector reads from the vector
11334          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11335          * which always does a direct read using address_space_ldl(), rather
11336          * than going via this function, so we don't need to check that here.
11337          */
11338         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11339     } else { /* MPU enabled */
11340         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11341             /* region search */
11342             uint32_t base = env->pmsav7.drbar[n];
11343             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11344             uint32_t rmask;
11345             bool srdis = false;
11346 
11347             if (!(env->pmsav7.drsr[n] & 0x1)) {
11348                 continue;
11349             }
11350 
11351             if (!rsize) {
11352                 qemu_log_mask(LOG_GUEST_ERROR,
11353                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11354                 continue;
11355             }
11356             rsize++;
11357             rmask = (1ull << rsize) - 1;
11358 
11359             if (base & rmask) {
11360                 qemu_log_mask(LOG_GUEST_ERROR,
11361                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11362                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11363                               n, base, rmask);
11364                 continue;
11365             }
11366 
11367             if (address < base || address > base + rmask) {
11368                 /*
11369                  * Address not in this region. We must check whether the
11370                  * region covers addresses in the same page as our address.
11371                  * In that case we must not report a size that covers the
11372                  * whole page for a subsequent hit against a different MPU
11373                  * region or the background region, because it would result in
11374                  * incorrect TLB hits for subsequent accesses to addresses that
11375                  * are in this MPU region.
11376                  */
11377                 if (ranges_overlap(base, rmask,
11378                                    address & TARGET_PAGE_MASK,
11379                                    TARGET_PAGE_SIZE)) {
11380                     *page_size = 1;
11381                 }
11382                 continue;
11383             }
11384 
11385             /* Region matched */
11386 
11387             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11388                 int i, snd;
11389                 uint32_t srdis_mask;
11390 
11391                 rsize -= 3; /* sub region size (power of 2) */
11392                 snd = ((address - base) >> rsize) & 0x7;
11393                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11394 
11395                 srdis_mask = srdis ? 0x3 : 0x0;
11396                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11397                     /* This will check in groups of 2, 4 and then 8, whether
11398                      * the subregion bits are consistent. rsize is incremented
11399                      * back up to give the region size, considering consistent
11400                      * adjacent subregions as one region. Stop testing if rsize
11401                      * is already big enough for an entire QEMU page.
11402                      */
11403                     int snd_rounded = snd & ~(i - 1);
11404                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11405                                                      snd_rounded + 8, i);
11406                     if (srdis_mask ^ srdis_multi) {
11407                         break;
11408                     }
11409                     srdis_mask = (srdis_mask << i) | srdis_mask;
11410                     rsize++;
11411                 }
11412             }
11413             if (srdis) {
11414                 continue;
11415             }
11416             if (rsize < TARGET_PAGE_BITS) {
11417                 *page_size = 1 << rsize;
11418             }
11419             break;
11420         }
11421 
11422         if (n == -1) { /* no hits */
11423             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11424                 /* background fault */
11425                 fi->type = ARMFault_Background;
11426                 return true;
11427             }
11428             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11429         } else { /* a MPU hit! */
11430             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
11431             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
11432 
11433             if (m_is_system_region(env, address)) {
11434                 /* System space is always execute never */
11435                 xn = 1;
11436             }
11437 
11438             if (is_user) { /* User mode AP bit decoding */
11439                 switch (ap) {
11440                 case 0:
11441                 case 1:
11442                 case 5:
11443                     break; /* no access */
11444                 case 3:
11445                     *prot |= PAGE_WRITE;
11446                     /* fall through */
11447                 case 2:
11448                 case 6:
11449                     *prot |= PAGE_READ | PAGE_EXEC;
11450                     break;
11451                 case 7:
11452                     /* for v7M, same as 6; for R profile a reserved value */
11453                     if (arm_feature(env, ARM_FEATURE_M)) {
11454                         *prot |= PAGE_READ | PAGE_EXEC;
11455                         break;
11456                     }
11457                     /* fall through */
11458                 default:
11459                     qemu_log_mask(LOG_GUEST_ERROR,
11460                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11461                                   PRIx32 "\n", n, ap);
11462                 }
11463             } else { /* Priv. mode AP bits decoding */
11464                 switch (ap) {
11465                 case 0:
11466                     break; /* no access */
11467                 case 1:
11468                 case 2:
11469                 case 3:
11470                     *prot |= PAGE_WRITE;
11471                     /* fall through */
11472                 case 5:
11473                 case 6:
11474                     *prot |= PAGE_READ | PAGE_EXEC;
11475                     break;
11476                 case 7:
11477                     /* for v7M, same as 6; for R profile a reserved value */
11478                     if (arm_feature(env, ARM_FEATURE_M)) {
11479                         *prot |= PAGE_READ | PAGE_EXEC;
11480                         break;
11481                     }
11482                     /* fall through */
11483                 default:
11484                     qemu_log_mask(LOG_GUEST_ERROR,
11485                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11486                                   PRIx32 "\n", n, ap);
11487                 }
11488             }
11489 
11490             /* execute never */
11491             if (xn) {
11492                 *prot &= ~PAGE_EXEC;
11493             }
11494         }
11495     }
11496 
11497     fi->type = ARMFault_Permission;
11498     fi->level = 1;
11499     return !(*prot & (1 << access_type));
11500 }
11501 
11502 static bool v8m_is_sau_exempt(CPUARMState *env,
11503                               uint32_t address, MMUAccessType access_type)
11504 {
11505     /* The architecture specifies that certain address ranges are
11506      * exempt from v8M SAU/IDAU checks.
11507      */
11508     return
11509         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
11510         (address >= 0xe0000000 && address <= 0xe0002fff) ||
11511         (address >= 0xe000e000 && address <= 0xe000efff) ||
11512         (address >= 0xe002e000 && address <= 0xe002efff) ||
11513         (address >= 0xe0040000 && address <= 0xe0041fff) ||
11514         (address >= 0xe00ff000 && address <= 0xe00fffff);
11515 }
11516 
11517 void v8m_security_lookup(CPUARMState *env, uint32_t address,
11518                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
11519                                 V8M_SAttributes *sattrs)
11520 {
11521     /* Look up the security attributes for this address. Compare the
11522      * pseudocode SecurityCheck() function.
11523      * We assume the caller has zero-initialized *sattrs.
11524      */
11525     ARMCPU *cpu = env_archcpu(env);
11526     int r;
11527     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
11528     int idau_region = IREGION_NOTVALID;
11529     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11530     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11531 
11532     if (cpu->idau) {
11533         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
11534         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
11535 
11536         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
11537                    &idau_nsc);
11538     }
11539 
11540     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
11541         /* 0xf0000000..0xffffffff is always S for insn fetches */
11542         return;
11543     }
11544 
11545     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
11546         sattrs->ns = !regime_is_secure(env, mmu_idx);
11547         return;
11548     }
11549 
11550     if (idau_region != IREGION_NOTVALID) {
11551         sattrs->irvalid = true;
11552         sattrs->iregion = idau_region;
11553     }
11554 
11555     switch (env->sau.ctrl & 3) {
11556     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
11557         break;
11558     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
11559         sattrs->ns = true;
11560         break;
11561     default: /* SAU.ENABLE == 1 */
11562         for (r = 0; r < cpu->sau_sregion; r++) {
11563             if (env->sau.rlar[r] & 1) {
11564                 uint32_t base = env->sau.rbar[r] & ~0x1f;
11565                 uint32_t limit = env->sau.rlar[r] | 0x1f;
11566 
11567                 if (base <= address && limit >= address) {
11568                     if (base > addr_page_base || limit < addr_page_limit) {
11569                         sattrs->subpage = true;
11570                     }
11571                     if (sattrs->srvalid) {
11572                         /* If we hit in more than one region then we must report
11573                          * as Secure, not NS-Callable, with no valid region
11574                          * number info.
11575                          */
11576                         sattrs->ns = false;
11577                         sattrs->nsc = false;
11578                         sattrs->sregion = 0;
11579                         sattrs->srvalid = false;
11580                         break;
11581                     } else {
11582                         if (env->sau.rlar[r] & 2) {
11583                             sattrs->nsc = true;
11584                         } else {
11585                             sattrs->ns = true;
11586                         }
11587                         sattrs->srvalid = true;
11588                         sattrs->sregion = r;
11589                     }
11590                 } else {
11591                     /*
11592                      * Address not in this region. We must check whether the
11593                      * region covers addresses in the same page as our address.
11594                      * In that case we must not report a size that covers the
11595                      * whole page for a subsequent hit against a different MPU
11596                      * region or the background region, because it would result
11597                      * in incorrect TLB hits for subsequent accesses to
11598                      * addresses that are in this MPU region.
11599                      */
11600                     if (limit >= base &&
11601                         ranges_overlap(base, limit - base + 1,
11602                                        addr_page_base,
11603                                        TARGET_PAGE_SIZE)) {
11604                         sattrs->subpage = true;
11605                     }
11606                 }
11607             }
11608         }
11609         break;
11610     }
11611 
11612     /*
11613      * The IDAU will override the SAU lookup results if it specifies
11614      * higher security than the SAU does.
11615      */
11616     if (!idau_ns) {
11617         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
11618             sattrs->ns = false;
11619             sattrs->nsc = idau_nsc;
11620         }
11621     }
11622 }
11623 
11624 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
11625                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
11626                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
11627                               int *prot, bool *is_subpage,
11628                               ARMMMUFaultInfo *fi, uint32_t *mregion)
11629 {
11630     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
11631      * that a full phys-to-virt translation does).
11632      * mregion is (if not NULL) set to the region number which matched,
11633      * or -1 if no region number is returned (MPU off, address did not
11634      * hit a region, address hit in multiple regions).
11635      * We set is_subpage to true if the region hit doesn't cover the
11636      * entire TARGET_PAGE the address is within.
11637      */
11638     ARMCPU *cpu = env_archcpu(env);
11639     bool is_user = regime_is_user(env, mmu_idx);
11640     uint32_t secure = regime_is_secure(env, mmu_idx);
11641     int n;
11642     int matchregion = -1;
11643     bool hit = false;
11644     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11645     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11646 
11647     *is_subpage = false;
11648     *phys_ptr = address;
11649     *prot = 0;
11650     if (mregion) {
11651         *mregion = -1;
11652     }
11653 
11654     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
11655      * was an exception vector read from the vector table (which is always
11656      * done using the default system address map), because those accesses
11657      * are done in arm_v7m_load_vector(), which always does a direct
11658      * read using address_space_ldl(), rather than going via this function.
11659      */
11660     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
11661         hit = true;
11662     } else if (m_is_ppb_region(env, address)) {
11663         hit = true;
11664     } else {
11665         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11666             hit = true;
11667         }
11668 
11669         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11670             /* region search */
11671             /* Note that the base address is bits [31:5] from the register
11672              * with bits [4:0] all zeroes, but the limit address is bits
11673              * [31:5] from the register with bits [4:0] all ones.
11674              */
11675             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
11676             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
11677 
11678             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
11679                 /* Region disabled */
11680                 continue;
11681             }
11682 
11683             if (address < base || address > limit) {
11684                 /*
11685                  * Address not in this region. We must check whether the
11686                  * region covers addresses in the same page as our address.
11687                  * In that case we must not report a size that covers the
11688                  * whole page for a subsequent hit against a different MPU
11689                  * region or the background region, because it would result in
11690                  * incorrect TLB hits for subsequent accesses to addresses that
11691                  * are in this MPU region.
11692                  */
11693                 if (limit >= base &&
11694                     ranges_overlap(base, limit - base + 1,
11695                                    addr_page_base,
11696                                    TARGET_PAGE_SIZE)) {
11697                     *is_subpage = true;
11698                 }
11699                 continue;
11700             }
11701 
11702             if (base > addr_page_base || limit < addr_page_limit) {
11703                 *is_subpage = true;
11704             }
11705 
11706             if (matchregion != -1) {
11707                 /* Multiple regions match -- always a failure (unlike
11708                  * PMSAv7 where highest-numbered-region wins)
11709                  */
11710                 fi->type = ARMFault_Permission;
11711                 fi->level = 1;
11712                 return true;
11713             }
11714 
11715             matchregion = n;
11716             hit = true;
11717         }
11718     }
11719 
11720     if (!hit) {
11721         /* background fault */
11722         fi->type = ARMFault_Background;
11723         return true;
11724     }
11725 
11726     if (matchregion == -1) {
11727         /* hit using the background region */
11728         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11729     } else {
11730         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
11731         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
11732 
11733         if (m_is_system_region(env, address)) {
11734             /* System space is always execute never */
11735             xn = 1;
11736         }
11737 
11738         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
11739         if (*prot && !xn) {
11740             *prot |= PAGE_EXEC;
11741         }
11742         /* We don't need to look the attribute up in the MAIR0/MAIR1
11743          * registers because that only tells us about cacheability.
11744          */
11745         if (mregion) {
11746             *mregion = matchregion;
11747         }
11748     }
11749 
11750     fi->type = ARMFault_Permission;
11751     fi->level = 1;
11752     return !(*prot & (1 << access_type));
11753 }
11754 
11755 
11756 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
11757                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11758                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
11759                                  int *prot, target_ulong *page_size,
11760                                  ARMMMUFaultInfo *fi)
11761 {
11762     uint32_t secure = regime_is_secure(env, mmu_idx);
11763     V8M_SAttributes sattrs = {};
11764     bool ret;
11765     bool mpu_is_subpage;
11766 
11767     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
11768         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
11769         if (access_type == MMU_INST_FETCH) {
11770             /* Instruction fetches always use the MMU bank and the
11771              * transaction attribute determined by the fetch address,
11772              * regardless of CPU state. This is painful for QEMU
11773              * to handle, because it would mean we need to encode
11774              * into the mmu_idx not just the (user, negpri) information
11775              * for the current security state but also that for the
11776              * other security state, which would balloon the number
11777              * of mmu_idx values needed alarmingly.
11778              * Fortunately we can avoid this because it's not actually
11779              * possible to arbitrarily execute code from memory with
11780              * the wrong security attribute: it will always generate
11781              * an exception of some kind or another, apart from the
11782              * special case of an NS CPU executing an SG instruction
11783              * in S&NSC memory. So we always just fail the translation
11784              * here and sort things out in the exception handler
11785              * (including possibly emulating an SG instruction).
11786              */
11787             if (sattrs.ns != !secure) {
11788                 if (sattrs.nsc) {
11789                     fi->type = ARMFault_QEMU_NSCExec;
11790                 } else {
11791                     fi->type = ARMFault_QEMU_SFault;
11792                 }
11793                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
11794                 *phys_ptr = address;
11795                 *prot = 0;
11796                 return true;
11797             }
11798         } else {
11799             /* For data accesses we always use the MMU bank indicated
11800              * by the current CPU state, but the security attributes
11801              * might downgrade a secure access to nonsecure.
11802              */
11803             if (sattrs.ns) {
11804                 txattrs->secure = false;
11805             } else if (!secure) {
11806                 /* NS access to S memory must fault.
11807                  * Architecturally we should first check whether the
11808                  * MPU information for this address indicates that we
11809                  * are doing an unaligned access to Device memory, which
11810                  * should generate a UsageFault instead. QEMU does not
11811                  * currently check for that kind of unaligned access though.
11812                  * If we added it we would need to do so as a special case
11813                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
11814                  */
11815                 fi->type = ARMFault_QEMU_SFault;
11816                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
11817                 *phys_ptr = address;
11818                 *prot = 0;
11819                 return true;
11820             }
11821         }
11822     }
11823 
11824     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
11825                             txattrs, prot, &mpu_is_subpage, fi, NULL);
11826     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
11827     return ret;
11828 }
11829 
11830 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
11831                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11832                                  hwaddr *phys_ptr, int *prot,
11833                                  ARMMMUFaultInfo *fi)
11834 {
11835     int n;
11836     uint32_t mask;
11837     uint32_t base;
11838     bool is_user = regime_is_user(env, mmu_idx);
11839 
11840     if (regime_translation_disabled(env, mmu_idx)) {
11841         /* MPU disabled.  */
11842         *phys_ptr = address;
11843         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11844         return false;
11845     }
11846 
11847     *phys_ptr = address;
11848     for (n = 7; n >= 0; n--) {
11849         base = env->cp15.c6_region[n];
11850         if ((base & 1) == 0) {
11851             continue;
11852         }
11853         mask = 1 << ((base >> 1) & 0x1f);
11854         /* Keep this shift separate from the above to avoid an
11855            (undefined) << 32.  */
11856         mask = (mask << 1) - 1;
11857         if (((base ^ address) & ~mask) == 0) {
11858             break;
11859         }
11860     }
11861     if (n < 0) {
11862         fi->type = ARMFault_Background;
11863         return true;
11864     }
11865 
11866     if (access_type == MMU_INST_FETCH) {
11867         mask = env->cp15.pmsav5_insn_ap;
11868     } else {
11869         mask = env->cp15.pmsav5_data_ap;
11870     }
11871     mask = (mask >> (n * 4)) & 0xf;
11872     switch (mask) {
11873     case 0:
11874         fi->type = ARMFault_Permission;
11875         fi->level = 1;
11876         return true;
11877     case 1:
11878         if (is_user) {
11879             fi->type = ARMFault_Permission;
11880             fi->level = 1;
11881             return true;
11882         }
11883         *prot = PAGE_READ | PAGE_WRITE;
11884         break;
11885     case 2:
11886         *prot = PAGE_READ;
11887         if (!is_user) {
11888             *prot |= PAGE_WRITE;
11889         }
11890         break;
11891     case 3:
11892         *prot = PAGE_READ | PAGE_WRITE;
11893         break;
11894     case 5:
11895         if (is_user) {
11896             fi->type = ARMFault_Permission;
11897             fi->level = 1;
11898             return true;
11899         }
11900         *prot = PAGE_READ;
11901         break;
11902     case 6:
11903         *prot = PAGE_READ;
11904         break;
11905     default:
11906         /* Bad permission.  */
11907         fi->type = ARMFault_Permission;
11908         fi->level = 1;
11909         return true;
11910     }
11911     *prot |= PAGE_EXEC;
11912     return false;
11913 }
11914 
11915 /* Combine either inner or outer cacheability attributes for normal
11916  * memory, according to table D4-42 and pseudocode procedure
11917  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
11918  *
11919  * NB: only stage 1 includes allocation hints (RW bits), leading to
11920  * some asymmetry.
11921  */
11922 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
11923 {
11924     if (s1 == 4 || s2 == 4) {
11925         /* non-cacheable has precedence */
11926         return 4;
11927     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
11928         /* stage 1 write-through takes precedence */
11929         return s1;
11930     } else if (extract32(s2, 2, 2) == 2) {
11931         /* stage 2 write-through takes precedence, but the allocation hint
11932          * is still taken from stage 1
11933          */
11934         return (2 << 2) | extract32(s1, 0, 2);
11935     } else { /* write-back */
11936         return s1;
11937     }
11938 }
11939 
11940 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
11941  * and CombineS1S2Desc()
11942  *
11943  * @s1:      Attributes from stage 1 walk
11944  * @s2:      Attributes from stage 2 walk
11945  */
11946 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
11947 {
11948     uint8_t s1lo, s2lo, s1hi, s2hi;
11949     ARMCacheAttrs ret;
11950     bool tagged = false;
11951 
11952     if (s1.attrs == 0xf0) {
11953         tagged = true;
11954         s1.attrs = 0xff;
11955     }
11956 
11957     s1lo = extract32(s1.attrs, 0, 4);
11958     s2lo = extract32(s2.attrs, 0, 4);
11959     s1hi = extract32(s1.attrs, 4, 4);
11960     s2hi = extract32(s2.attrs, 4, 4);
11961 
11962     /* Combine shareability attributes (table D4-43) */
11963     if (s1.shareability == 2 || s2.shareability == 2) {
11964         /* if either are outer-shareable, the result is outer-shareable */
11965         ret.shareability = 2;
11966     } else if (s1.shareability == 3 || s2.shareability == 3) {
11967         /* if either are inner-shareable, the result is inner-shareable */
11968         ret.shareability = 3;
11969     } else {
11970         /* both non-shareable */
11971         ret.shareability = 0;
11972     }
11973 
11974     /* Combine memory type and cacheability attributes */
11975     if (s1hi == 0 || s2hi == 0) {
11976         /* Device has precedence over normal */
11977         if (s1lo == 0 || s2lo == 0) {
11978             /* nGnRnE has precedence over anything */
11979             ret.attrs = 0;
11980         } else if (s1lo == 4 || s2lo == 4) {
11981             /* non-Reordering has precedence over Reordering */
11982             ret.attrs = 4;  /* nGnRE */
11983         } else if (s1lo == 8 || s2lo == 8) {
11984             /* non-Gathering has precedence over Gathering */
11985             ret.attrs = 8;  /* nGRE */
11986         } else {
11987             ret.attrs = 0xc; /* GRE */
11988         }
11989 
11990         /* Any location for which the resultant memory type is any
11991          * type of Device memory is always treated as Outer Shareable.
11992          */
11993         ret.shareability = 2;
11994     } else { /* Normal memory */
11995         /* Outer/inner cacheability combine independently */
11996         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
11997                   | combine_cacheattr_nibble(s1lo, s2lo);
11998 
11999         if (ret.attrs == 0x44) {
12000             /* Any location for which the resultant memory type is Normal
12001              * Inner Non-cacheable, Outer Non-cacheable is always treated
12002              * as Outer Shareable.
12003              */
12004             ret.shareability = 2;
12005         }
12006     }
12007 
12008     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
12009     if (tagged && ret.attrs == 0xff) {
12010         ret.attrs = 0xf0;
12011     }
12012 
12013     return ret;
12014 }
12015 
12016 
12017 /* get_phys_addr - get the physical address for this virtual address
12018  *
12019  * Find the physical address corresponding to the given virtual address,
12020  * by doing a translation table walk on MMU based systems or using the
12021  * MPU state on MPU based systems.
12022  *
12023  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12024  * prot and page_size may not be filled in, and the populated fsr value provides
12025  * information on why the translation aborted, in the format of a
12026  * DFSR/IFSR fault register, with the following caveats:
12027  *  * we honour the short vs long DFSR format differences.
12028  *  * the WnR bit is never set (the caller must do this).
12029  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12030  *    value.
12031  *
12032  * @env: CPUARMState
12033  * @address: virtual address to get physical address for
12034  * @access_type: 0 for read, 1 for write, 2 for execute
12035  * @mmu_idx: MMU index indicating required translation regime
12036  * @phys_ptr: set to the physical address corresponding to the virtual address
12037  * @attrs: set to the memory transaction attributes to use
12038  * @prot: set to the permissions for the page containing phys_ptr
12039  * @page_size: set to the size of the page containing phys_ptr
12040  * @fi: set to fault info if the translation fails
12041  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12042  */
12043 bool get_phys_addr(CPUARMState *env, target_ulong address,
12044                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12045                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12046                    target_ulong *page_size,
12047                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12048 {
12049     if (mmu_idx == ARMMMUIdx_E10_0 ||
12050         mmu_idx == ARMMMUIdx_E10_1 ||
12051         mmu_idx == ARMMMUIdx_E10_1_PAN) {
12052         /* Call ourselves recursively to do the stage 1 and then stage 2
12053          * translations.
12054          */
12055         if (arm_feature(env, ARM_FEATURE_EL2)) {
12056             hwaddr ipa;
12057             int s2_prot;
12058             int ret;
12059             ARMCacheAttrs cacheattrs2 = {};
12060 
12061             ret = get_phys_addr(env, address, access_type,
12062                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
12063                                 prot, page_size, fi, cacheattrs);
12064 
12065             /* If S1 fails or S2 is disabled, return early.  */
12066             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
12067                 *phys_ptr = ipa;
12068                 return ret;
12069             }
12070 
12071             /* S1 is done. Now do S2 translation.  */
12072             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_Stage2,
12073                                      mmu_idx == ARMMMUIdx_E10_0,
12074                                      phys_ptr, attrs, &s2_prot,
12075                                      page_size, fi, &cacheattrs2);
12076             fi->s2addr = ipa;
12077             /* Combine the S1 and S2 perms.  */
12078             *prot &= s2_prot;
12079 
12080             /* If S2 fails, return early.  */
12081             if (ret) {
12082                 return ret;
12083             }
12084 
12085             /* Combine the S1 and S2 cache attributes. */
12086             if (env->cp15.hcr_el2 & HCR_DC) {
12087                 /*
12088                  * HCR.DC forces the first stage attributes to
12089                  *  Normal Non-Shareable,
12090                  *  Inner Write-Back Read-Allocate Write-Allocate,
12091                  *  Outer Write-Back Read-Allocate Write-Allocate.
12092                  * Do not overwrite Tagged within attrs.
12093                  */
12094                 if (cacheattrs->attrs != 0xf0) {
12095                     cacheattrs->attrs = 0xff;
12096                 }
12097                 cacheattrs->shareability = 0;
12098             }
12099             *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12100             return 0;
12101         } else {
12102             /*
12103              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12104              */
12105             mmu_idx = stage_1_mmu_idx(mmu_idx);
12106         }
12107     }
12108 
12109     /* The page table entries may downgrade secure to non-secure, but
12110      * cannot upgrade an non-secure translation regime's attributes
12111      * to secure.
12112      */
12113     attrs->secure = regime_is_secure(env, mmu_idx);
12114     attrs->user = regime_is_user(env, mmu_idx);
12115 
12116     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12117      * In v7 and earlier it affects all stage 1 translations.
12118      */
12119     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
12120         && !arm_feature(env, ARM_FEATURE_V8)) {
12121         if (regime_el(env, mmu_idx) == 3) {
12122             address += env->cp15.fcseidr_s;
12123         } else {
12124             address += env->cp15.fcseidr_ns;
12125         }
12126     }
12127 
12128     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12129         bool ret;
12130         *page_size = TARGET_PAGE_SIZE;
12131 
12132         if (arm_feature(env, ARM_FEATURE_V8)) {
12133             /* PMSAv8 */
12134             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12135                                        phys_ptr, attrs, prot, page_size, fi);
12136         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12137             /* PMSAv7 */
12138             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12139                                        phys_ptr, prot, page_size, fi);
12140         } else {
12141             /* Pre-v7 MPU */
12142             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12143                                        phys_ptr, prot, fi);
12144         }
12145         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12146                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12147                       access_type == MMU_DATA_LOAD ? "reading" :
12148                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12149                       (uint32_t)address, mmu_idx,
12150                       ret ? "Miss" : "Hit",
12151                       *prot & PAGE_READ ? 'r' : '-',
12152                       *prot & PAGE_WRITE ? 'w' : '-',
12153                       *prot & PAGE_EXEC ? 'x' : '-');
12154 
12155         return ret;
12156     }
12157 
12158     /* Definitely a real MMU, not an MPU */
12159 
12160     if (regime_translation_disabled(env, mmu_idx)) {
12161         uint64_t hcr;
12162         uint8_t memattr;
12163 
12164         /*
12165          * MMU disabled.  S1 addresses within aa64 translation regimes are
12166          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
12167          */
12168         if (mmu_idx != ARMMMUIdx_Stage2) {
12169             int r_el = regime_el(env, mmu_idx);
12170             if (arm_el_is_aa64(env, r_el)) {
12171                 int pamax = arm_pamax(env_archcpu(env));
12172                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
12173                 int addrtop, tbi;
12174 
12175                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
12176                 if (access_type == MMU_INST_FETCH) {
12177                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
12178                 }
12179                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
12180                 addrtop = (tbi ? 55 : 63);
12181 
12182                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
12183                     fi->type = ARMFault_AddressSize;
12184                     fi->level = 0;
12185                     fi->stage2 = false;
12186                     return 1;
12187                 }
12188 
12189                 /*
12190                  * When TBI is disabled, we've just validated that all of the
12191                  * bits above PAMax are zero, so logically we only need to
12192                  * clear the top byte for TBI.  But it's clearer to follow
12193                  * the pseudocode set of addrdesc.paddress.
12194                  */
12195                 address = extract64(address, 0, 52);
12196             }
12197         }
12198         *phys_ptr = address;
12199         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12200         *page_size = TARGET_PAGE_SIZE;
12201 
12202         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
12203         hcr = arm_hcr_el2_eff(env);
12204         cacheattrs->shareability = 0;
12205         if (hcr & HCR_DC) {
12206             if (hcr & HCR_DCT) {
12207                 memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
12208             } else {
12209                 memattr = 0xff;  /* Normal, WB, RWA */
12210             }
12211         } else if (access_type == MMU_INST_FETCH) {
12212             if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
12213                 memattr = 0xee;  /* Normal, WT, RA, NT */
12214             } else {
12215                 memattr = 0x44;  /* Normal, NC, No */
12216             }
12217             cacheattrs->shareability = 2; /* outer sharable */
12218         } else {
12219             memattr = 0x00;      /* Device, nGnRnE */
12220         }
12221         cacheattrs->attrs = memattr;
12222         return 0;
12223     }
12224 
12225     if (regime_using_lpae_format(env, mmu_idx)) {
12226         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
12227                                   phys_ptr, attrs, prot, page_size,
12228                                   fi, cacheattrs);
12229     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12230         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12231                                 phys_ptr, attrs, prot, page_size, fi);
12232     } else {
12233         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12234                                     phys_ptr, prot, page_size, fi);
12235     }
12236 }
12237 
12238 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12239                                          MemTxAttrs *attrs)
12240 {
12241     ARMCPU *cpu = ARM_CPU(cs);
12242     CPUARMState *env = &cpu->env;
12243     hwaddr phys_addr;
12244     target_ulong page_size;
12245     int prot;
12246     bool ret;
12247     ARMMMUFaultInfo fi = {};
12248     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12249     ARMCacheAttrs cacheattrs = {};
12250 
12251     *attrs = (MemTxAttrs) {};
12252 
12253     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
12254                         attrs, &prot, &page_size, &fi, &cacheattrs);
12255 
12256     if (ret) {
12257         return -1;
12258     }
12259     return phys_addr;
12260 }
12261 
12262 #endif
12263 
12264 /* Note that signed overflow is undefined in C.  The following routines are
12265    careful to use unsigned types where modulo arithmetic is required.
12266    Failure to do so _will_ break on newer gcc.  */
12267 
12268 /* Signed saturating arithmetic.  */
12269 
12270 /* Perform 16-bit signed saturating addition.  */
12271 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
12272 {
12273     uint16_t res;
12274 
12275     res = a + b;
12276     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
12277         if (a & 0x8000)
12278             res = 0x8000;
12279         else
12280             res = 0x7fff;
12281     }
12282     return res;
12283 }
12284 
12285 /* Perform 8-bit signed saturating addition.  */
12286 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
12287 {
12288     uint8_t res;
12289 
12290     res = a + b;
12291     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
12292         if (a & 0x80)
12293             res = 0x80;
12294         else
12295             res = 0x7f;
12296     }
12297     return res;
12298 }
12299 
12300 /* Perform 16-bit signed saturating subtraction.  */
12301 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
12302 {
12303     uint16_t res;
12304 
12305     res = a - b;
12306     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
12307         if (a & 0x8000)
12308             res = 0x8000;
12309         else
12310             res = 0x7fff;
12311     }
12312     return res;
12313 }
12314 
12315 /* Perform 8-bit signed saturating subtraction.  */
12316 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
12317 {
12318     uint8_t res;
12319 
12320     res = a - b;
12321     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
12322         if (a & 0x80)
12323             res = 0x80;
12324         else
12325             res = 0x7f;
12326     }
12327     return res;
12328 }
12329 
12330 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
12331 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
12332 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
12333 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
12334 #define PFX q
12335 
12336 #include "op_addsub.h"
12337 
12338 /* Unsigned saturating arithmetic.  */
12339 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
12340 {
12341     uint16_t res;
12342     res = a + b;
12343     if (res < a)
12344         res = 0xffff;
12345     return res;
12346 }
12347 
12348 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
12349 {
12350     if (a > b)
12351         return a - b;
12352     else
12353         return 0;
12354 }
12355 
12356 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
12357 {
12358     uint8_t res;
12359     res = a + b;
12360     if (res < a)
12361         res = 0xff;
12362     return res;
12363 }
12364 
12365 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
12366 {
12367     if (a > b)
12368         return a - b;
12369     else
12370         return 0;
12371 }
12372 
12373 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
12374 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
12375 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
12376 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
12377 #define PFX uq
12378 
12379 #include "op_addsub.h"
12380 
12381 /* Signed modulo arithmetic.  */
12382 #define SARITH16(a, b, n, op) do { \
12383     int32_t sum; \
12384     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
12385     RESULT(sum, n, 16); \
12386     if (sum >= 0) \
12387         ge |= 3 << (n * 2); \
12388     } while(0)
12389 
12390 #define SARITH8(a, b, n, op) do { \
12391     int32_t sum; \
12392     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
12393     RESULT(sum, n, 8); \
12394     if (sum >= 0) \
12395         ge |= 1 << n; \
12396     } while(0)
12397 
12398 
12399 #define ADD16(a, b, n) SARITH16(a, b, n, +)
12400 #define SUB16(a, b, n) SARITH16(a, b, n, -)
12401 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
12402 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
12403 #define PFX s
12404 #define ARITH_GE
12405 
12406 #include "op_addsub.h"
12407 
12408 /* Unsigned modulo arithmetic.  */
12409 #define ADD16(a, b, n) do { \
12410     uint32_t sum; \
12411     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
12412     RESULT(sum, n, 16); \
12413     if ((sum >> 16) == 1) \
12414         ge |= 3 << (n * 2); \
12415     } while(0)
12416 
12417 #define ADD8(a, b, n) do { \
12418     uint32_t sum; \
12419     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
12420     RESULT(sum, n, 8); \
12421     if ((sum >> 8) == 1) \
12422         ge |= 1 << n; \
12423     } while(0)
12424 
12425 #define SUB16(a, b, n) do { \
12426     uint32_t sum; \
12427     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
12428     RESULT(sum, n, 16); \
12429     if ((sum >> 16) == 0) \
12430         ge |= 3 << (n * 2); \
12431     } while(0)
12432 
12433 #define SUB8(a, b, n) do { \
12434     uint32_t sum; \
12435     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
12436     RESULT(sum, n, 8); \
12437     if ((sum >> 8) == 0) \
12438         ge |= 1 << n; \
12439     } while(0)
12440 
12441 #define PFX u
12442 #define ARITH_GE
12443 
12444 #include "op_addsub.h"
12445 
12446 /* Halved signed arithmetic.  */
12447 #define ADD16(a, b, n) \
12448   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
12449 #define SUB16(a, b, n) \
12450   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
12451 #define ADD8(a, b, n) \
12452   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
12453 #define SUB8(a, b, n) \
12454   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
12455 #define PFX sh
12456 
12457 #include "op_addsub.h"
12458 
12459 /* Halved unsigned arithmetic.  */
12460 #define ADD16(a, b, n) \
12461   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12462 #define SUB16(a, b, n) \
12463   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12464 #define ADD8(a, b, n) \
12465   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12466 #define SUB8(a, b, n) \
12467   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12468 #define PFX uh
12469 
12470 #include "op_addsub.h"
12471 
12472 static inline uint8_t do_usad(uint8_t a, uint8_t b)
12473 {
12474     if (a > b)
12475         return a - b;
12476     else
12477         return b - a;
12478 }
12479 
12480 /* Unsigned sum of absolute byte differences.  */
12481 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
12482 {
12483     uint32_t sum;
12484     sum = do_usad(a, b);
12485     sum += do_usad(a >> 8, b >> 8);
12486     sum += do_usad(a >> 16, b >>16);
12487     sum += do_usad(a >> 24, b >> 24);
12488     return sum;
12489 }
12490 
12491 /* For ARMv6 SEL instruction.  */
12492 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
12493 {
12494     uint32_t mask;
12495 
12496     mask = 0;
12497     if (flags & 1)
12498         mask |= 0xff;
12499     if (flags & 2)
12500         mask |= 0xff00;
12501     if (flags & 4)
12502         mask |= 0xff0000;
12503     if (flags & 8)
12504         mask |= 0xff000000;
12505     return (a & mask) | (b & ~mask);
12506 }
12507 
12508 /* CRC helpers.
12509  * The upper bytes of val (above the number specified by 'bytes') must have
12510  * been zeroed out by the caller.
12511  */
12512 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12513 {
12514     uint8_t buf[4];
12515 
12516     stl_le_p(buf, val);
12517 
12518     /* zlib crc32 converts the accumulator and output to one's complement.  */
12519     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12520 }
12521 
12522 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12523 {
12524     uint8_t buf[4];
12525 
12526     stl_le_p(buf, val);
12527 
12528     /* Linux crc32c converts the output to one's complement.  */
12529     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12530 }
12531 
12532 /* Return the exception level to which FP-disabled exceptions should
12533  * be taken, or 0 if FP is enabled.
12534  */
12535 int fp_exception_el(CPUARMState *env, int cur_el)
12536 {
12537 #ifndef CONFIG_USER_ONLY
12538     /* CPACR and the CPTR registers don't exist before v6, so FP is
12539      * always accessible
12540      */
12541     if (!arm_feature(env, ARM_FEATURE_V6)) {
12542         return 0;
12543     }
12544 
12545     if (arm_feature(env, ARM_FEATURE_M)) {
12546         /* CPACR can cause a NOCP UsageFault taken to current security state */
12547         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
12548             return 1;
12549         }
12550 
12551         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
12552             if (!extract32(env->v7m.nsacr, 10, 1)) {
12553                 /* FP insns cause a NOCP UsageFault taken to Secure */
12554                 return 3;
12555             }
12556         }
12557 
12558         return 0;
12559     }
12560 
12561     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12562      * 0, 2 : trap EL0 and EL1/PL1 accesses
12563      * 1    : trap only EL0 accesses
12564      * 3    : trap no accesses
12565      * This register is ignored if E2H+TGE are both set.
12566      */
12567     if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
12568         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12569 
12570         switch (fpen) {
12571         case 0:
12572         case 2:
12573             if (cur_el == 0 || cur_el == 1) {
12574                 /* Trap to PL1, which might be EL1 or EL3 */
12575                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12576                     return 3;
12577                 }
12578                 return 1;
12579             }
12580             if (cur_el == 3 && !is_a64(env)) {
12581                 /* Secure PL1 running at EL3 */
12582                 return 3;
12583             }
12584             break;
12585         case 1:
12586             if (cur_el == 0) {
12587                 return 1;
12588             }
12589             break;
12590         case 3:
12591             break;
12592         }
12593     }
12594 
12595     /*
12596      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
12597      * to control non-secure access to the FPU. It doesn't have any
12598      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
12599      */
12600     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
12601          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
12602         if (!extract32(env->cp15.nsacr, 10, 1)) {
12603             /* FP insns act as UNDEF */
12604             return cur_el == 2 ? 2 : 1;
12605         }
12606     }
12607 
12608     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12609      * check because zero bits in the registers mean "don't trap".
12610      */
12611 
12612     /* CPTR_EL2 : present in v7VE or v8 */
12613     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12614         && !arm_is_secure_below_el3(env)) {
12615         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12616         return 2;
12617     }
12618 
12619     /* CPTR_EL3 : present in v8 */
12620     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12621         /* Trap all FP ops to EL3 */
12622         return 3;
12623     }
12624 #endif
12625     return 0;
12626 }
12627 
12628 /* Return the exception level we're running at if this is our mmu_idx */
12629 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
12630 {
12631     if (mmu_idx & ARM_MMU_IDX_M) {
12632         return mmu_idx & ARM_MMU_IDX_M_PRIV;
12633     }
12634 
12635     switch (mmu_idx) {
12636     case ARMMMUIdx_E10_0:
12637     case ARMMMUIdx_E20_0:
12638     case ARMMMUIdx_SE10_0:
12639         return 0;
12640     case ARMMMUIdx_E10_1:
12641     case ARMMMUIdx_E10_1_PAN:
12642     case ARMMMUIdx_SE10_1:
12643     case ARMMMUIdx_SE10_1_PAN:
12644         return 1;
12645     case ARMMMUIdx_E2:
12646     case ARMMMUIdx_E20_2:
12647     case ARMMMUIdx_E20_2_PAN:
12648         return 2;
12649     case ARMMMUIdx_SE3:
12650         return 3;
12651     default:
12652         g_assert_not_reached();
12653     }
12654 }
12655 
12656 #ifndef CONFIG_TCG
12657 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
12658 {
12659     g_assert_not_reached();
12660 }
12661 #endif
12662 
12663 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
12664 {
12665     if (arm_feature(env, ARM_FEATURE_M)) {
12666         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
12667     }
12668 
12669     /* See ARM pseudo-function ELIsInHost.  */
12670     switch (el) {
12671     case 0:
12672         if (arm_is_secure_below_el3(env)) {
12673             return ARMMMUIdx_SE10_0;
12674         }
12675         if ((env->cp15.hcr_el2 & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)
12676             && arm_el_is_aa64(env, 2)) {
12677             return ARMMMUIdx_E20_0;
12678         }
12679         return ARMMMUIdx_E10_0;
12680     case 1:
12681         if (arm_is_secure_below_el3(env)) {
12682             if (env->pstate & PSTATE_PAN) {
12683                 return ARMMMUIdx_SE10_1_PAN;
12684             }
12685             return ARMMMUIdx_SE10_1;
12686         }
12687         if (env->pstate & PSTATE_PAN) {
12688             return ARMMMUIdx_E10_1_PAN;
12689         }
12690         return ARMMMUIdx_E10_1;
12691     case 2:
12692         /* TODO: ARMv8.4-SecEL2 */
12693         /* Note that TGE does not apply at EL2.  */
12694         if ((env->cp15.hcr_el2 & HCR_E2H) && arm_el_is_aa64(env, 2)) {
12695             if (env->pstate & PSTATE_PAN) {
12696                 return ARMMMUIdx_E20_2_PAN;
12697             }
12698             return ARMMMUIdx_E20_2;
12699         }
12700         return ARMMMUIdx_E2;
12701     case 3:
12702         return ARMMMUIdx_SE3;
12703     default:
12704         g_assert_not_reached();
12705     }
12706 }
12707 
12708 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
12709 {
12710     return arm_mmu_idx_el(env, arm_current_el(env));
12711 }
12712 
12713 #ifndef CONFIG_USER_ONLY
12714 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
12715 {
12716     return stage_1_mmu_idx(arm_mmu_idx(env));
12717 }
12718 #endif
12719 
12720 static uint32_t rebuild_hflags_common(CPUARMState *env, int fp_el,
12721                                       ARMMMUIdx mmu_idx, uint32_t flags)
12722 {
12723     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
12724     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX,
12725                        arm_to_core_mmu_idx(mmu_idx));
12726 
12727     if (arm_singlestep_active(env)) {
12728         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
12729     }
12730     return flags;
12731 }
12732 
12733 static uint32_t rebuild_hflags_common_32(CPUARMState *env, int fp_el,
12734                                          ARMMMUIdx mmu_idx, uint32_t flags)
12735 {
12736     bool sctlr_b = arm_sctlr_b(env);
12737 
12738     if (sctlr_b) {
12739         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, 1);
12740     }
12741     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
12742         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
12743     }
12744     flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
12745 
12746     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
12747 }
12748 
12749 static uint32_t rebuild_hflags_m32(CPUARMState *env, int fp_el,
12750                                    ARMMMUIdx mmu_idx)
12751 {
12752     uint32_t flags = 0;
12753 
12754     if (arm_v7m_is_handler_mode(env)) {
12755         flags = FIELD_DP32(flags, TBFLAG_M32, HANDLER, 1);
12756     }
12757 
12758     /*
12759      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
12760      * is suppressing them because the requested execution priority
12761      * is less than 0.
12762      */
12763     if (arm_feature(env, ARM_FEATURE_V8) &&
12764         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
12765           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
12766         flags = FIELD_DP32(flags, TBFLAG_M32, STACKCHECK, 1);
12767     }
12768 
12769     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
12770 }
12771 
12772 static uint32_t rebuild_hflags_aprofile(CPUARMState *env)
12773 {
12774     int flags = 0;
12775 
12776     flags = FIELD_DP32(flags, TBFLAG_ANY, DEBUG_TARGET_EL,
12777                        arm_debug_target_el(env));
12778     return flags;
12779 }
12780 
12781 static uint32_t rebuild_hflags_a32(CPUARMState *env, int fp_el,
12782                                    ARMMMUIdx mmu_idx)
12783 {
12784     uint32_t flags = rebuild_hflags_aprofile(env);
12785 
12786     if (arm_el_is_aa64(env, 1)) {
12787         flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
12788     }
12789 
12790     if (arm_current_el(env) < 2 && env->cp15.hstr_el2 &&
12791         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
12792         flags = FIELD_DP32(flags, TBFLAG_A32, HSTR_ACTIVE, 1);
12793     }
12794 
12795     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
12796 }
12797 
12798 static uint32_t rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
12799                                    ARMMMUIdx mmu_idx)
12800 {
12801     uint32_t flags = rebuild_hflags_aprofile(env);
12802     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
12803     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
12804     uint64_t sctlr;
12805     int tbii, tbid;
12806 
12807     flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
12808 
12809     /* Get control bits for tagged addresses.  */
12810     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
12811     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
12812 
12813     flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
12814     flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
12815 
12816     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
12817         int sve_el = sve_exception_el(env, el);
12818         uint32_t zcr_len;
12819 
12820         /*
12821          * If SVE is disabled, but FP is enabled,
12822          * then the effective len is 0.
12823          */
12824         if (sve_el != 0 && fp_el == 0) {
12825             zcr_len = 0;
12826         } else {
12827             zcr_len = sve_zcr_len_for_el(env, el);
12828         }
12829         flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
12830         flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
12831     }
12832 
12833     sctlr = regime_sctlr(env, stage1);
12834 
12835     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
12836         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
12837     }
12838 
12839     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
12840         /*
12841          * In order to save space in flags, we record only whether
12842          * pauth is "inactive", meaning all insns are implemented as
12843          * a nop, or "active" when some action must be performed.
12844          * The decision of which action to take is left to a helper.
12845          */
12846         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
12847             flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
12848         }
12849     }
12850 
12851     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
12852         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
12853         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
12854             flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
12855         }
12856     }
12857 
12858     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
12859     if (!(env->pstate & PSTATE_UAO)) {
12860         switch (mmu_idx) {
12861         case ARMMMUIdx_E10_1:
12862         case ARMMMUIdx_E10_1_PAN:
12863         case ARMMMUIdx_SE10_1:
12864         case ARMMMUIdx_SE10_1_PAN:
12865             /* TODO: ARMv8.3-NV */
12866             flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
12867             break;
12868         case ARMMMUIdx_E20_2:
12869         case ARMMMUIdx_E20_2_PAN:
12870             /* TODO: ARMv8.4-SecEL2 */
12871             /*
12872              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
12873              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
12874              */
12875             if (env->cp15.hcr_el2 & HCR_TGE) {
12876                 flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
12877             }
12878             break;
12879         default:
12880             break;
12881         }
12882     }
12883 
12884     if (cpu_isar_feature(aa64_mte, env_archcpu(env))) {
12885         /*
12886          * Set MTE_ACTIVE if any access may be Checked, and leave clear
12887          * if all accesses must be Unchecked:
12888          * 1) If no TBI, then there are no tags in the address to check,
12889          * 2) If Tag Check Override, then all accesses are Unchecked,
12890          * 3) If Tag Check Fail == 0, then Checked access have no effect,
12891          * 4) If no Allocation Tag Access, then all accesses are Unchecked.
12892          */
12893         if (allocation_tag_access_enabled(env, el, sctlr)) {
12894             flags = FIELD_DP32(flags, TBFLAG_A64, ATA, 1);
12895             if (tbid
12896                 && !(env->pstate & PSTATE_TCO)
12897                 && (sctlr & (el == 0 ? SCTLR_TCF0 : SCTLR_TCF))) {
12898                 flags = FIELD_DP32(flags, TBFLAG_A64, MTE_ACTIVE, 1);
12899             }
12900         }
12901         /* And again for unprivileged accesses, if required.  */
12902         if (FIELD_EX32(flags, TBFLAG_A64, UNPRIV)
12903             && tbid
12904             && !(env->pstate & PSTATE_TCO)
12905             && (sctlr & SCTLR_TCF0)
12906             && allocation_tag_access_enabled(env, 0, sctlr)) {
12907             flags = FIELD_DP32(flags, TBFLAG_A64, MTE0_ACTIVE, 1);
12908         }
12909         /* Cache TCMA as well as TBI. */
12910         flags = FIELD_DP32(flags, TBFLAG_A64, TCMA,
12911                            aa64_va_parameter_tcma(tcr, mmu_idx));
12912     }
12913 
12914     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
12915 }
12916 
12917 static uint32_t rebuild_hflags_internal(CPUARMState *env)
12918 {
12919     int el = arm_current_el(env);
12920     int fp_el = fp_exception_el(env, el);
12921     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12922 
12923     if (is_a64(env)) {
12924         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
12925     } else if (arm_feature(env, ARM_FEATURE_M)) {
12926         return rebuild_hflags_m32(env, fp_el, mmu_idx);
12927     } else {
12928         return rebuild_hflags_a32(env, fp_el, mmu_idx);
12929     }
12930 }
12931 
12932 void arm_rebuild_hflags(CPUARMState *env)
12933 {
12934     env->hflags = rebuild_hflags_internal(env);
12935 }
12936 
12937 /*
12938  * If we have triggered a EL state change we can't rely on the
12939  * translator having passed it to us, we need to recompute.
12940  */
12941 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
12942 {
12943     int el = arm_current_el(env);
12944     int fp_el = fp_exception_el(env, el);
12945     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12946     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
12947 }
12948 
12949 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
12950 {
12951     int fp_el = fp_exception_el(env, el);
12952     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12953 
12954     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
12955 }
12956 
12957 /*
12958  * If we have triggered a EL state change we can't rely on the
12959  * translator having passed it to us, we need to recompute.
12960  */
12961 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
12962 {
12963     int el = arm_current_el(env);
12964     int fp_el = fp_exception_el(env, el);
12965     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12966     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
12967 }
12968 
12969 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
12970 {
12971     int fp_el = fp_exception_el(env, el);
12972     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12973 
12974     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
12975 }
12976 
12977 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
12978 {
12979     int fp_el = fp_exception_el(env, el);
12980     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12981 
12982     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
12983 }
12984 
12985 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
12986 {
12987 #ifdef CONFIG_DEBUG_TCG
12988     uint32_t env_flags_current = env->hflags;
12989     uint32_t env_flags_rebuilt = rebuild_hflags_internal(env);
12990 
12991     if (unlikely(env_flags_current != env_flags_rebuilt)) {
12992         fprintf(stderr, "TCG hflags mismatch (current:0x%08x rebuilt:0x%08x)\n",
12993                 env_flags_current, env_flags_rebuilt);
12994         abort();
12995     }
12996 #endif
12997 }
12998 
12999 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13000                           target_ulong *cs_base, uint32_t *pflags)
13001 {
13002     uint32_t flags = env->hflags;
13003     uint32_t pstate_for_ss;
13004 
13005     *cs_base = 0;
13006     assert_hflags_rebuild_correctly(env);
13007 
13008     if (FIELD_EX32(flags, TBFLAG_ANY, AARCH64_STATE)) {
13009         *pc = env->pc;
13010         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13011             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
13012         }
13013         pstate_for_ss = env->pstate;
13014     } else {
13015         *pc = env->regs[15];
13016 
13017         if (arm_feature(env, ARM_FEATURE_M)) {
13018             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13019                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
13020                 != env->v7m.secure) {
13021                 flags = FIELD_DP32(flags, TBFLAG_M32, FPCCR_S_WRONG, 1);
13022             }
13023 
13024             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13025                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13026                  (env->v7m.secure &&
13027                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13028                 /*
13029                  * ASPEN is set, but FPCA/SFPA indicate that there is no
13030                  * active FP context; we must create a new FP context before
13031                  * executing any FP insn.
13032                  */
13033                 flags = FIELD_DP32(flags, TBFLAG_M32, NEW_FP_CTXT_NEEDED, 1);
13034             }
13035 
13036             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13037             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13038                 flags = FIELD_DP32(flags, TBFLAG_M32, LSPACT, 1);
13039             }
13040         } else {
13041             /*
13042              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
13043              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
13044              */
13045             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13046                 flags = FIELD_DP32(flags, TBFLAG_A32,
13047                                    XSCALE_CPAR, env->cp15.c15_cpar);
13048             } else {
13049                 flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN,
13050                                    env->vfp.vec_len);
13051                 flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE,
13052                                    env->vfp.vec_stride);
13053             }
13054             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
13055                 flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
13056             }
13057         }
13058 
13059         flags = FIELD_DP32(flags, TBFLAG_AM32, THUMB, env->thumb);
13060         flags = FIELD_DP32(flags, TBFLAG_AM32, CONDEXEC, env->condexec_bits);
13061         pstate_for_ss = env->uncached_cpsr;
13062     }
13063 
13064     /*
13065      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13066      * states defined in the ARM ARM for software singlestep:
13067      *  SS_ACTIVE   PSTATE.SS   State
13068      *     0            x       Inactive (the TB flag for SS is always 0)
13069      *     1            0       Active-pending
13070      *     1            1       Active-not-pending
13071      * SS_ACTIVE is set in hflags; PSTATE_SS is computed every TB.
13072      */
13073     if (FIELD_EX32(flags, TBFLAG_ANY, SS_ACTIVE) &&
13074         (pstate_for_ss & PSTATE_SS)) {
13075         flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
13076     }
13077 
13078     *pflags = flags;
13079 }
13080 
13081 #ifdef TARGET_AARCH64
13082 /*
13083  * The manual says that when SVE is enabled and VQ is widened the
13084  * implementation is allowed to zero the previously inaccessible
13085  * portion of the registers.  The corollary to that is that when
13086  * SVE is enabled and VQ is narrowed we are also allowed to zero
13087  * the now inaccessible portion of the registers.
13088  *
13089  * The intent of this is that no predicate bit beyond VQ is ever set.
13090  * Which means that some operations on predicate registers themselves
13091  * may operate on full uint64_t or even unrolled across the maximum
13092  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13093  * may well be cheaper than conditionals to restrict the operation
13094  * to the relevant portion of a uint16_t[16].
13095  */
13096 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13097 {
13098     int i, j;
13099     uint64_t pmask;
13100 
13101     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13102     assert(vq <= env_archcpu(env)->sve_max_vq);
13103 
13104     /* Zap the high bits of the zregs.  */
13105     for (i = 0; i < 32; i++) {
13106         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13107     }
13108 
13109     /* Zap the high bits of the pregs and ffr.  */
13110     pmask = 0;
13111     if (vq & 3) {
13112         pmask = ~(-1ULL << (16 * (vq & 3)));
13113     }
13114     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13115         for (i = 0; i < 17; ++i) {
13116             env->vfp.pregs[i].p[j] &= pmask;
13117         }
13118         pmask = 0;
13119     }
13120 }
13121 
13122 /*
13123  * Notice a change in SVE vector size when changing EL.
13124  */
13125 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13126                            int new_el, bool el0_a64)
13127 {
13128     ARMCPU *cpu = env_archcpu(env);
13129     int old_len, new_len;
13130     bool old_a64, new_a64;
13131 
13132     /* Nothing to do if no SVE.  */
13133     if (!cpu_isar_feature(aa64_sve, cpu)) {
13134         return;
13135     }
13136 
13137     /* Nothing to do if FP is disabled in either EL.  */
13138     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13139         return;
13140     }
13141 
13142     /*
13143      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13144      * at ELx, or not available because the EL is in AArch32 state, then
13145      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13146      * has an effective value of 0".
13147      *
13148      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13149      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13150      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13151      * we already have the correct register contents when encountering the
13152      * vq0->vq0 transition between EL0->EL1.
13153      */
13154     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13155     old_len = (old_a64 && !sve_exception_el(env, old_el)
13156                ? sve_zcr_len_for_el(env, old_el) : 0);
13157     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13158     new_len = (new_a64 && !sve_exception_el(env, new_el)
13159                ? sve_zcr_len_for_el(env, new_el) : 0);
13160 
13161     /* When changing vector length, clear inaccessible state.  */
13162     if (new_len < old_len) {
13163         aarch64_sve_narrow_vq(env, new_len + 1);
13164     }
13165 }
13166 #endif
13167