xref: /qemu/target/arm/helper.c (revision c888f7e0)
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 #endif
49 
50 static void switch_mode(CPUARMState *env, int mode);
51 
52 static int vfp_gdb_get_reg(CPUARMState *env, GByteArray *buf, int reg)
53 {
54     ARMCPU *cpu = env_archcpu(env);
55     int nregs = cpu_isar_feature(aa32_simd_r32, cpu) ? 32 : 16;
56 
57     /* VFP data registers are always little-endian.  */
58     if (reg < nregs) {
59         return gdb_get_reg64(buf, *aa32_vfp_dreg(env, reg));
60     }
61     if (arm_feature(env, ARM_FEATURE_NEON)) {
62         /* Aliases for Q regs.  */
63         nregs += 16;
64         if (reg < nregs) {
65             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
66             return gdb_get_reg128(buf, q[0], q[1]);
67         }
68     }
69     switch (reg - nregs) {
70     case 0: return gdb_get_reg32(buf, env->vfp.xregs[ARM_VFP_FPSID]); break;
71     case 1: return gdb_get_reg32(buf, vfp_get_fpscr(env)); break;
72     case 2: return gdb_get_reg32(buf, env->vfp.xregs[ARM_VFP_FPEXC]); break;
73     }
74     return 0;
75 }
76 
77 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
78 {
79     ARMCPU *cpu = env_archcpu(env);
80     int nregs = cpu_isar_feature(aa32_simd_r32, cpu) ? 32 : 16;
81 
82     if (reg < nregs) {
83         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
84         return 8;
85     }
86     if (arm_feature(env, ARM_FEATURE_NEON)) {
87         nregs += 16;
88         if (reg < nregs) {
89             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
90             q[0] = ldq_le_p(buf);
91             q[1] = ldq_le_p(buf + 8);
92             return 16;
93         }
94     }
95     switch (reg - nregs) {
96     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
97     case 1: vfp_set_fpscr(env, ldl_p(buf)); return 4;
98     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
99     }
100     return 0;
101 }
102 
103 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, GByteArray *buf, int reg)
104 {
105     switch (reg) {
106     case 0 ... 31:
107     {
108         /* 128 bit FP register - quads are in LE order */
109         uint64_t *q = aa64_vfp_qreg(env, reg);
110         return gdb_get_reg128(buf, q[1], q[0]);
111     }
112     case 32:
113         /* FPSR */
114         return gdb_get_reg32(buf, vfp_get_fpsr(env));
115     case 33:
116         /* FPCR */
117         return gdb_get_reg32(buf,vfp_get_fpcr(env));
118     default:
119         return 0;
120     }
121 }
122 
123 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
124 {
125     switch (reg) {
126     case 0 ... 31:
127         /* 128 bit FP register */
128         {
129             uint64_t *q = aa64_vfp_qreg(env, reg);
130             q[0] = ldq_le_p(buf);
131             q[1] = ldq_le_p(buf + 8);
132             return 16;
133         }
134     case 32:
135         /* FPSR */
136         vfp_set_fpsr(env, ldl_p(buf));
137         return 4;
138     case 33:
139         /* FPCR */
140         vfp_set_fpcr(env, ldl_p(buf));
141         return 4;
142     default:
143         return 0;
144     }
145 }
146 
147 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
148 {
149     assert(ri->fieldoffset);
150     if (cpreg_field_is_64bit(ri)) {
151         return CPREG_FIELD64(env, ri);
152     } else {
153         return CPREG_FIELD32(env, ri);
154     }
155 }
156 
157 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
158                       uint64_t value)
159 {
160     assert(ri->fieldoffset);
161     if (cpreg_field_is_64bit(ri)) {
162         CPREG_FIELD64(env, ri) = value;
163     } else {
164         CPREG_FIELD32(env, ri) = value;
165     }
166 }
167 
168 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
169 {
170     return (char *)env + ri->fieldoffset;
171 }
172 
173 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
174 {
175     /* Raw read of a coprocessor register (as needed for migration, etc). */
176     if (ri->type & ARM_CP_CONST) {
177         return ri->resetvalue;
178     } else if (ri->raw_readfn) {
179         return ri->raw_readfn(env, ri);
180     } else if (ri->readfn) {
181         return ri->readfn(env, ri);
182     } else {
183         return raw_read(env, ri);
184     }
185 }
186 
187 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
188                              uint64_t v)
189 {
190     /* Raw write of a coprocessor register (as needed for migration, etc).
191      * Note that constant registers are treated as write-ignored; the
192      * caller should check for success by whether a readback gives the
193      * value written.
194      */
195     if (ri->type & ARM_CP_CONST) {
196         return;
197     } else if (ri->raw_writefn) {
198         ri->raw_writefn(env, ri, v);
199     } else if (ri->writefn) {
200         ri->writefn(env, ri, v);
201     } else {
202         raw_write(env, ri, v);
203     }
204 }
205 
206 /**
207  * arm_get/set_gdb_*: get/set a gdb register
208  * @env: the CPU state
209  * @buf: a buffer to copy to/from
210  * @reg: register number (offset from start of group)
211  *
212  * We return the number of bytes copied
213  */
214 
215 static int arm_gdb_get_sysreg(CPUARMState *env, GByteArray *buf, int reg)
216 {
217     ARMCPU *cpu = env_archcpu(env);
218     const ARMCPRegInfo *ri;
219     uint32_t key;
220 
221     key = cpu->dyn_sysreg_xml.data.cpregs.keys[reg];
222     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
223     if (ri) {
224         if (cpreg_field_is_64bit(ri)) {
225             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
226         } else {
227             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
228         }
229     }
230     return 0;
231 }
232 
233 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
234 {
235     return 0;
236 }
237 
238 #ifdef TARGET_AARCH64
239 static int arm_gdb_get_svereg(CPUARMState *env, GByteArray *buf, int reg)
240 {
241     ARMCPU *cpu = env_archcpu(env);
242 
243     switch (reg) {
244     /* The first 32 registers are the zregs */
245     case 0 ... 31:
246     {
247         int vq, len = 0;
248         for (vq = 0; vq < cpu->sve_max_vq; vq++) {
249             len += gdb_get_reg128(buf,
250                                   env->vfp.zregs[reg].d[vq * 2 + 1],
251                                   env->vfp.zregs[reg].d[vq * 2]);
252         }
253         return len;
254     }
255     case 32:
256         return gdb_get_reg32(buf, vfp_get_fpsr(env));
257     case 33:
258         return gdb_get_reg32(buf, vfp_get_fpcr(env));
259     /* then 16 predicates and the ffr */
260     case 34 ... 50:
261     {
262         int preg = reg - 34;
263         int vq, len = 0;
264         for (vq = 0; vq < cpu->sve_max_vq; vq = vq + 4) {
265             len += gdb_get_reg64(buf, env->vfp.pregs[preg].p[vq / 4]);
266         }
267         return len;
268     }
269     case 51:
270     {
271         /*
272          * We report in Vector Granules (VG) which is 64bit in a Z reg
273          * while the ZCR works in Vector Quads (VQ) which is 128bit chunks.
274          */
275         int vq = sve_zcr_len_for_el(env, arm_current_el(env)) + 1;
276         return gdb_get_reg32(buf, vq * 2);
277     }
278     default:
279         /* gdbstub asked for something out our range */
280         qemu_log_mask(LOG_UNIMP, "%s: out of range register %d", __func__, reg);
281         break;
282     }
283 
284     return 0;
285 }
286 
287 static int arm_gdb_set_svereg(CPUARMState *env, uint8_t *buf, int reg)
288 {
289     ARMCPU *cpu = env_archcpu(env);
290 
291     /* The first 32 registers are the zregs */
292     switch (reg) {
293     /* The first 32 registers are the zregs */
294     case 0 ... 31:
295     {
296         int vq, len = 0;
297         uint64_t *p = (uint64_t *) buf;
298         for (vq = 0; vq < cpu->sve_max_vq; vq++) {
299             env->vfp.zregs[reg].d[vq * 2 + 1] = *p++;
300             env->vfp.zregs[reg].d[vq * 2] = *p++;
301             len += 16;
302         }
303         return len;
304     }
305     case 32:
306         vfp_set_fpsr(env, *(uint32_t *)buf);
307         return 4;
308     case 33:
309         vfp_set_fpcr(env, *(uint32_t *)buf);
310         return 4;
311     case 34 ... 50:
312     {
313         int preg = reg - 34;
314         int vq, len = 0;
315         uint64_t *p = (uint64_t *) buf;
316         for (vq = 0; vq < cpu->sve_max_vq; vq = vq + 4) {
317             env->vfp.pregs[preg].p[vq / 4] = *p++;
318             len += 8;
319         }
320         return len;
321     }
322     case 51:
323         /* cannot set vg via gdbstub */
324         return 0;
325     default:
326         /* gdbstub asked for something out our range */
327         break;
328     }
329 
330     return 0;
331 }
332 #endif /* TARGET_AARCH64 */
333 
334 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
335 {
336    /* Return true if the regdef would cause an assertion if you called
337     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
338     * program bug for it not to have the NO_RAW flag).
339     * NB that returning false here doesn't necessarily mean that calling
340     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
341     * read/write access functions which are safe for raw use" from "has
342     * read/write access functions which have side effects but has forgotten
343     * to provide raw access functions".
344     * The tests here line up with the conditions in read/write_raw_cp_reg()
345     * and assertions in raw_read()/raw_write().
346     */
347     if ((ri->type & ARM_CP_CONST) ||
348         ri->fieldoffset ||
349         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
350         return false;
351     }
352     return true;
353 }
354 
355 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
356 {
357     /* Write the coprocessor state from cpu->env to the (index,value) list. */
358     int i;
359     bool ok = true;
360 
361     for (i = 0; i < cpu->cpreg_array_len; i++) {
362         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
363         const ARMCPRegInfo *ri;
364         uint64_t newval;
365 
366         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
367         if (!ri) {
368             ok = false;
369             continue;
370         }
371         if (ri->type & ARM_CP_NO_RAW) {
372             continue;
373         }
374 
375         newval = read_raw_cp_reg(&cpu->env, ri);
376         if (kvm_sync) {
377             /*
378              * Only sync if the previous list->cpustate sync succeeded.
379              * Rather than tracking the success/failure state for every
380              * item in the list, we just recheck "does the raw write we must
381              * have made in write_list_to_cpustate() read back OK" here.
382              */
383             uint64_t oldval = cpu->cpreg_values[i];
384 
385             if (oldval == newval) {
386                 continue;
387             }
388 
389             write_raw_cp_reg(&cpu->env, ri, oldval);
390             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
391                 continue;
392             }
393 
394             write_raw_cp_reg(&cpu->env, ri, newval);
395         }
396         cpu->cpreg_values[i] = newval;
397     }
398     return ok;
399 }
400 
401 bool write_list_to_cpustate(ARMCPU *cpu)
402 {
403     int i;
404     bool ok = true;
405 
406     for (i = 0; i < cpu->cpreg_array_len; i++) {
407         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
408         uint64_t v = cpu->cpreg_values[i];
409         const ARMCPRegInfo *ri;
410 
411         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
412         if (!ri) {
413             ok = false;
414             continue;
415         }
416         if (ri->type & ARM_CP_NO_RAW) {
417             continue;
418         }
419         /* Write value and confirm it reads back as written
420          * (to catch read-only registers and partially read-only
421          * registers where the incoming migration value doesn't match)
422          */
423         write_raw_cp_reg(&cpu->env, ri, v);
424         if (read_raw_cp_reg(&cpu->env, ri) != v) {
425             ok = false;
426         }
427     }
428     return ok;
429 }
430 
431 static void add_cpreg_to_list(gpointer key, gpointer opaque)
432 {
433     ARMCPU *cpu = opaque;
434     uint64_t regidx;
435     const ARMCPRegInfo *ri;
436 
437     regidx = *(uint32_t *)key;
438     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
439 
440     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
441         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
442         /* The value array need not be initialized at this point */
443         cpu->cpreg_array_len++;
444     }
445 }
446 
447 static void count_cpreg(gpointer key, gpointer opaque)
448 {
449     ARMCPU *cpu = opaque;
450     uint64_t regidx;
451     const ARMCPRegInfo *ri;
452 
453     regidx = *(uint32_t *)key;
454     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
455 
456     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
457         cpu->cpreg_array_len++;
458     }
459 }
460 
461 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
462 {
463     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
464     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
465 
466     if (aidx > bidx) {
467         return 1;
468     }
469     if (aidx < bidx) {
470         return -1;
471     }
472     return 0;
473 }
474 
475 void init_cpreg_list(ARMCPU *cpu)
476 {
477     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
478      * Note that we require cpreg_tuples[] to be sorted by key ID.
479      */
480     GList *keys;
481     int arraylen;
482 
483     keys = g_hash_table_get_keys(cpu->cp_regs);
484     keys = g_list_sort(keys, cpreg_key_compare);
485 
486     cpu->cpreg_array_len = 0;
487 
488     g_list_foreach(keys, count_cpreg, cpu);
489 
490     arraylen = cpu->cpreg_array_len;
491     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
492     cpu->cpreg_values = g_new(uint64_t, arraylen);
493     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
494     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
495     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
496     cpu->cpreg_array_len = 0;
497 
498     g_list_foreach(keys, add_cpreg_to_list, cpu);
499 
500     assert(cpu->cpreg_array_len == arraylen);
501 
502     g_list_free(keys);
503 }
504 
505 /*
506  * Some registers are not accessible from AArch32 EL3 if SCR.NS == 0.
507  */
508 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
509                                         const ARMCPRegInfo *ri,
510                                         bool isread)
511 {
512     if (!is_a64(env) && arm_current_el(env) == 3 &&
513         arm_is_secure_below_el3(env)) {
514         return CP_ACCESS_TRAP_UNCATEGORIZED;
515     }
516     return CP_ACCESS_OK;
517 }
518 
519 /* Some secure-only AArch32 registers trap to EL3 if used from
520  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
521  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
522  * We assume that the .access field is set to PL1_RW.
523  */
524 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
525                                             const ARMCPRegInfo *ri,
526                                             bool isread)
527 {
528     if (arm_current_el(env) == 3) {
529         return CP_ACCESS_OK;
530     }
531     if (arm_is_secure_below_el3(env)) {
532         return CP_ACCESS_TRAP_EL3;
533     }
534     /* This will be EL1 NS and EL2 NS, which just UNDEF */
535     return CP_ACCESS_TRAP_UNCATEGORIZED;
536 }
537 
538 /* Check for traps to "powerdown debug" registers, which are controlled
539  * by MDCR.TDOSA
540  */
541 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
542                                    bool isread)
543 {
544     int el = arm_current_el(env);
545     bool mdcr_el2_tdosa = (env->cp15.mdcr_el2 & MDCR_TDOSA) ||
546         (env->cp15.mdcr_el2 & MDCR_TDE) ||
547         (arm_hcr_el2_eff(env) & HCR_TGE);
548 
549     if (el < 2 && mdcr_el2_tdosa && !arm_is_secure_below_el3(env)) {
550         return CP_ACCESS_TRAP_EL2;
551     }
552     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
553         return CP_ACCESS_TRAP_EL3;
554     }
555     return CP_ACCESS_OK;
556 }
557 
558 /* Check for traps to "debug ROM" registers, which are controlled
559  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
560  */
561 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
562                                   bool isread)
563 {
564     int el = arm_current_el(env);
565     bool mdcr_el2_tdra = (env->cp15.mdcr_el2 & MDCR_TDRA) ||
566         (env->cp15.mdcr_el2 & MDCR_TDE) ||
567         (arm_hcr_el2_eff(env) & HCR_TGE);
568 
569     if (el < 2 && mdcr_el2_tdra && !arm_is_secure_below_el3(env)) {
570         return CP_ACCESS_TRAP_EL2;
571     }
572     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
573         return CP_ACCESS_TRAP_EL3;
574     }
575     return CP_ACCESS_OK;
576 }
577 
578 /* Check for traps to general debug registers, which are controlled
579  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
580  */
581 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
582                                   bool isread)
583 {
584     int el = arm_current_el(env);
585     bool mdcr_el2_tda = (env->cp15.mdcr_el2 & MDCR_TDA) ||
586         (env->cp15.mdcr_el2 & MDCR_TDE) ||
587         (arm_hcr_el2_eff(env) & HCR_TGE);
588 
589     if (el < 2 && mdcr_el2_tda && !arm_is_secure_below_el3(env)) {
590         return CP_ACCESS_TRAP_EL2;
591     }
592     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
593         return CP_ACCESS_TRAP_EL3;
594     }
595     return CP_ACCESS_OK;
596 }
597 
598 /* Check for traps to performance monitor registers, which are controlled
599  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
600  */
601 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
602                                  bool isread)
603 {
604     int el = arm_current_el(env);
605 
606     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
607         && !arm_is_secure_below_el3(env)) {
608         return CP_ACCESS_TRAP_EL2;
609     }
610     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
611         return CP_ACCESS_TRAP_EL3;
612     }
613     return CP_ACCESS_OK;
614 }
615 
616 /* Check for traps from EL1 due to HCR_EL2.TVM and HCR_EL2.TRVM.  */
617 static CPAccessResult access_tvm_trvm(CPUARMState *env, const ARMCPRegInfo *ri,
618                                       bool isread)
619 {
620     if (arm_current_el(env) == 1) {
621         uint64_t trap = isread ? HCR_TRVM : HCR_TVM;
622         if (arm_hcr_el2_eff(env) & trap) {
623             return CP_ACCESS_TRAP_EL2;
624         }
625     }
626     return CP_ACCESS_OK;
627 }
628 
629 /* Check for traps from EL1 due to HCR_EL2.TSW.  */
630 static CPAccessResult access_tsw(CPUARMState *env, const ARMCPRegInfo *ri,
631                                  bool isread)
632 {
633     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TSW)) {
634         return CP_ACCESS_TRAP_EL2;
635     }
636     return CP_ACCESS_OK;
637 }
638 
639 /* Check for traps from EL1 due to HCR_EL2.TACR.  */
640 static CPAccessResult access_tacr(CPUARMState *env, const ARMCPRegInfo *ri,
641                                   bool isread)
642 {
643     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TACR)) {
644         return CP_ACCESS_TRAP_EL2;
645     }
646     return CP_ACCESS_OK;
647 }
648 
649 /* Check for traps from EL1 due to HCR_EL2.TTLB. */
650 static CPAccessResult access_ttlb(CPUARMState *env, const ARMCPRegInfo *ri,
651                                   bool isread)
652 {
653     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TTLB)) {
654         return CP_ACCESS_TRAP_EL2;
655     }
656     return CP_ACCESS_OK;
657 }
658 
659 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
660 {
661     ARMCPU *cpu = env_archcpu(env);
662 
663     raw_write(env, ri, value);
664     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
665 }
666 
667 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
668 {
669     ARMCPU *cpu = env_archcpu(env);
670 
671     if (raw_read(env, ri) != value) {
672         /* Unlike real hardware the qemu TLB uses virtual addresses,
673          * not modified virtual addresses, so this causes a TLB flush.
674          */
675         tlb_flush(CPU(cpu));
676         raw_write(env, ri, value);
677     }
678 }
679 
680 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
681                              uint64_t value)
682 {
683     ARMCPU *cpu = env_archcpu(env);
684 
685     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
686         && !extended_addresses_enabled(env)) {
687         /* For VMSA (when not using the LPAE long descriptor page table
688          * format) this register includes the ASID, so do a TLB flush.
689          * For PMSA it is purely a process ID and no action is needed.
690          */
691         tlb_flush(CPU(cpu));
692     }
693     raw_write(env, ri, value);
694 }
695 
696 /* IS variants of TLB operations must affect all cores */
697 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
698                              uint64_t value)
699 {
700     CPUState *cs = env_cpu(env);
701 
702     tlb_flush_all_cpus_synced(cs);
703 }
704 
705 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
706                              uint64_t value)
707 {
708     CPUState *cs = env_cpu(env);
709 
710     tlb_flush_all_cpus_synced(cs);
711 }
712 
713 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
714                              uint64_t value)
715 {
716     CPUState *cs = env_cpu(env);
717 
718     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
719 }
720 
721 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
722                              uint64_t value)
723 {
724     CPUState *cs = env_cpu(env);
725 
726     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
727 }
728 
729 /*
730  * Non-IS variants of TLB operations are upgraded to
731  * IS versions if we are at NS EL1 and HCR_EL2.FB is set to
732  * force broadcast of these operations.
733  */
734 static bool tlb_force_broadcast(CPUARMState *env)
735 {
736     return (env->cp15.hcr_el2 & HCR_FB) &&
737         arm_current_el(env) == 1 && arm_is_secure_below_el3(env);
738 }
739 
740 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
741                           uint64_t value)
742 {
743     /* Invalidate all (TLBIALL) */
744     CPUState *cs = env_cpu(env);
745 
746     if (tlb_force_broadcast(env)) {
747         tlb_flush_all_cpus_synced(cs);
748     } else {
749         tlb_flush(cs);
750     }
751 }
752 
753 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
754                           uint64_t value)
755 {
756     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
757     CPUState *cs = env_cpu(env);
758 
759     value &= TARGET_PAGE_MASK;
760     if (tlb_force_broadcast(env)) {
761         tlb_flush_page_all_cpus_synced(cs, value);
762     } else {
763         tlb_flush_page(cs, value);
764     }
765 }
766 
767 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
768                            uint64_t value)
769 {
770     /* Invalidate by ASID (TLBIASID) */
771     CPUState *cs = env_cpu(env);
772 
773     if (tlb_force_broadcast(env)) {
774         tlb_flush_all_cpus_synced(cs);
775     } else {
776         tlb_flush(cs);
777     }
778 }
779 
780 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
781                            uint64_t value)
782 {
783     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
784     CPUState *cs = env_cpu(env);
785 
786     value &= TARGET_PAGE_MASK;
787     if (tlb_force_broadcast(env)) {
788         tlb_flush_page_all_cpus_synced(cs, value);
789     } else {
790         tlb_flush_page(cs, value);
791     }
792 }
793 
794 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
795                                uint64_t value)
796 {
797     CPUState *cs = env_cpu(env);
798 
799     tlb_flush_by_mmuidx(cs,
800                         ARMMMUIdxBit_E10_1 |
801                         ARMMMUIdxBit_E10_1_PAN |
802                         ARMMMUIdxBit_E10_0);
803 }
804 
805 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
806                                   uint64_t value)
807 {
808     CPUState *cs = env_cpu(env);
809 
810     tlb_flush_by_mmuidx_all_cpus_synced(cs,
811                                         ARMMMUIdxBit_E10_1 |
812                                         ARMMMUIdxBit_E10_1_PAN |
813                                         ARMMMUIdxBit_E10_0);
814 }
815 
816 
817 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
818                               uint64_t value)
819 {
820     CPUState *cs = env_cpu(env);
821 
822     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_E2);
823 }
824 
825 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
826                                  uint64_t value)
827 {
828     CPUState *cs = env_cpu(env);
829 
830     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_E2);
831 }
832 
833 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
834                               uint64_t value)
835 {
836     CPUState *cs = env_cpu(env);
837     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
838 
839     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_E2);
840 }
841 
842 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
843                                  uint64_t value)
844 {
845     CPUState *cs = env_cpu(env);
846     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
847 
848     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
849                                              ARMMMUIdxBit_E2);
850 }
851 
852 static const ARMCPRegInfo cp_reginfo[] = {
853     /* Define the secure and non-secure FCSE identifier CP registers
854      * separately because there is no secure bank in V8 (no _EL3).  This allows
855      * the secure register to be properly reset and migrated. There is also no
856      * v8 EL1 version of the register so the non-secure instance stands alone.
857      */
858     { .name = "FCSEIDR",
859       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
860       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
861       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
862       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
863     { .name = "FCSEIDR_S",
864       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
865       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
866       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
867       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
868     /* Define the secure and non-secure context identifier CP registers
869      * separately because there is no secure bank in V8 (no _EL3).  This allows
870      * the secure register to be properly reset and migrated.  In the
871      * non-secure case, the 32-bit register will have reset and migration
872      * disabled during registration as it is handled by the 64-bit instance.
873      */
874     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
875       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
876       .access = PL1_RW, .accessfn = access_tvm_trvm,
877       .secure = ARM_CP_SECSTATE_NS,
878       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
879       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
880     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
881       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
882       .access = PL1_RW, .accessfn = access_tvm_trvm,
883       .secure = ARM_CP_SECSTATE_S,
884       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
885       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
886     REGINFO_SENTINEL
887 };
888 
889 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
890     /* NB: Some of these registers exist in v8 but with more precise
891      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
892      */
893     /* MMU Domain access control / MPU write buffer control */
894     { .name = "DACR",
895       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
896       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
897       .writefn = dacr_write, .raw_writefn = raw_write,
898       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
899                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
900     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
901      * For v6 and v5, these mappings are overly broad.
902      */
903     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
904       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
905     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
906       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
907     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
908       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
909     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
910       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
911     /* Cache maintenance ops; some of this space may be overridden later. */
912     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
913       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
914       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
915     REGINFO_SENTINEL
916 };
917 
918 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
919     /* Not all pre-v6 cores implemented this WFI, so this is slightly
920      * over-broad.
921      */
922     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
923       .access = PL1_W, .type = ARM_CP_WFI },
924     REGINFO_SENTINEL
925 };
926 
927 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
928     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
929      * is UNPREDICTABLE; we choose to NOP as most implementations do).
930      */
931     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
932       .access = PL1_W, .type = ARM_CP_WFI },
933     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
934      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
935      * OMAPCP will override this space.
936      */
937     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
938       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
939       .resetvalue = 0 },
940     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
941       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
942       .resetvalue = 0 },
943     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
944     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
945       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
946       .resetvalue = 0 },
947     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
948      * implementing it as RAZ means the "debug architecture version" bits
949      * will read as a reserved value, which should cause Linux to not try
950      * to use the debug hardware.
951      */
952     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
953       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
954     /* MMU TLB control. Note that the wildcarding means we cover not just
955      * the unified TLB ops but also the dside/iside/inner-shareable variants.
956      */
957     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
958       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
959       .type = ARM_CP_NO_RAW },
960     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
961       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
962       .type = ARM_CP_NO_RAW },
963     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
964       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
965       .type = ARM_CP_NO_RAW },
966     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
967       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
968       .type = ARM_CP_NO_RAW },
969     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
970       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
971     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
972       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
973     REGINFO_SENTINEL
974 };
975 
976 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
977                         uint64_t value)
978 {
979     uint32_t mask = 0;
980 
981     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
982     if (!arm_feature(env, ARM_FEATURE_V8)) {
983         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
984          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
985          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
986          */
987         if (cpu_isar_feature(aa32_vfp_simd, env_archcpu(env))) {
988             /* VFP coprocessor: cp10 & cp11 [23:20] */
989             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
990 
991             if (!arm_feature(env, ARM_FEATURE_NEON)) {
992                 /* ASEDIS [31] bit is RAO/WI */
993                 value |= (1 << 31);
994             }
995 
996             /* VFPv3 and upwards with NEON implement 32 double precision
997              * registers (D0-D31).
998              */
999             if (!cpu_isar_feature(aa32_simd_r32, env_archcpu(env))) {
1000                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
1001                 value |= (1 << 30);
1002             }
1003         }
1004         value &= mask;
1005     }
1006 
1007     /*
1008      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
1009      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
1010      */
1011     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
1012         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
1013         value &= ~(0xf << 20);
1014         value |= env->cp15.cpacr_el1 & (0xf << 20);
1015     }
1016 
1017     env->cp15.cpacr_el1 = value;
1018 }
1019 
1020 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1021 {
1022     /*
1023      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
1024      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
1025      */
1026     uint64_t value = env->cp15.cpacr_el1;
1027 
1028     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
1029         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
1030         value &= ~(0xf << 20);
1031     }
1032     return value;
1033 }
1034 
1035 
1036 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1037 {
1038     /* Call cpacr_write() so that we reset with the correct RAO bits set
1039      * for our CPU features.
1040      */
1041     cpacr_write(env, ri, 0);
1042 }
1043 
1044 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1045                                    bool isread)
1046 {
1047     if (arm_feature(env, ARM_FEATURE_V8)) {
1048         /* Check if CPACR accesses are to be trapped to EL2 */
1049         if (arm_current_el(env) == 1 &&
1050             (env->cp15.cptr_el[2] & CPTR_TCPAC) && !arm_is_secure(env)) {
1051             return CP_ACCESS_TRAP_EL2;
1052         /* Check if CPACR accesses are to be trapped to EL3 */
1053         } else if (arm_current_el(env) < 3 &&
1054                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
1055             return CP_ACCESS_TRAP_EL3;
1056         }
1057     }
1058 
1059     return CP_ACCESS_OK;
1060 }
1061 
1062 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1063                                   bool isread)
1064 {
1065     /* Check if CPTR accesses are set to trap to EL3 */
1066     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
1067         return CP_ACCESS_TRAP_EL3;
1068     }
1069 
1070     return CP_ACCESS_OK;
1071 }
1072 
1073 static const ARMCPRegInfo v6_cp_reginfo[] = {
1074     /* prefetch by MVA in v6, NOP in v7 */
1075     { .name = "MVA_prefetch",
1076       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
1077       .access = PL1_W, .type = ARM_CP_NOP },
1078     /* We need to break the TB after ISB to execute self-modifying code
1079      * correctly and also to take any pending interrupts immediately.
1080      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
1081      */
1082     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
1083       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
1084     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
1085       .access = PL0_W, .type = ARM_CP_NOP },
1086     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
1087       .access = PL0_W, .type = ARM_CP_NOP },
1088     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
1089       .access = PL1_RW, .accessfn = access_tvm_trvm,
1090       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
1091                              offsetof(CPUARMState, cp15.ifar_ns) },
1092       .resetvalue = 0, },
1093     /* Watchpoint Fault Address Register : should actually only be present
1094      * for 1136, 1176, 11MPCore.
1095      */
1096     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
1097       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
1098     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
1099       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
1100       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
1101       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
1102     REGINFO_SENTINEL
1103 };
1104 
1105 /* Definitions for the PMU registers */
1106 #define PMCRN_MASK  0xf800
1107 #define PMCRN_SHIFT 11
1108 #define PMCRLC  0x40
1109 #define PMCRDP  0x20
1110 #define PMCRX   0x10
1111 #define PMCRD   0x8
1112 #define PMCRC   0x4
1113 #define PMCRP   0x2
1114 #define PMCRE   0x1
1115 /*
1116  * Mask of PMCR bits writeable by guest (not including WO bits like C, P,
1117  * which can be written as 1 to trigger behaviour but which stay RAZ).
1118  */
1119 #define PMCR_WRITEABLE_MASK (PMCRLC | PMCRDP | PMCRX | PMCRD | PMCRE)
1120 
1121 #define PMXEVTYPER_P          0x80000000
1122 #define PMXEVTYPER_U          0x40000000
1123 #define PMXEVTYPER_NSK        0x20000000
1124 #define PMXEVTYPER_NSU        0x10000000
1125 #define PMXEVTYPER_NSH        0x08000000
1126 #define PMXEVTYPER_M          0x04000000
1127 #define PMXEVTYPER_MT         0x02000000
1128 #define PMXEVTYPER_EVTCOUNT   0x0000ffff
1129 #define PMXEVTYPER_MASK       (PMXEVTYPER_P | PMXEVTYPER_U | PMXEVTYPER_NSK | \
1130                                PMXEVTYPER_NSU | PMXEVTYPER_NSH | \
1131                                PMXEVTYPER_M | PMXEVTYPER_MT | \
1132                                PMXEVTYPER_EVTCOUNT)
1133 
1134 #define PMCCFILTR             0xf8000000
1135 #define PMCCFILTR_M           PMXEVTYPER_M
1136 #define PMCCFILTR_EL0         (PMCCFILTR | PMCCFILTR_M)
1137 
1138 static inline uint32_t pmu_num_counters(CPUARMState *env)
1139 {
1140   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
1141 }
1142 
1143 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1144 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1145 {
1146   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1147 }
1148 
1149 typedef struct pm_event {
1150     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1151     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1152     bool (*supported)(CPUARMState *);
1153     /*
1154      * Retrieve the current count of the underlying event. The programmed
1155      * counters hold a difference from the return value from this function
1156      */
1157     uint64_t (*get_count)(CPUARMState *);
1158     /*
1159      * Return how many nanoseconds it will take (at a minimum) for count events
1160      * to occur. A negative value indicates the counter will never overflow, or
1161      * that the counter has otherwise arranged for the overflow bit to be set
1162      * and the PMU interrupt to be raised on overflow.
1163      */
1164     int64_t (*ns_per_count)(uint64_t);
1165 } pm_event;
1166 
1167 static bool event_always_supported(CPUARMState *env)
1168 {
1169     return true;
1170 }
1171 
1172 static uint64_t swinc_get_count(CPUARMState *env)
1173 {
1174     /*
1175      * SW_INCR events are written directly to the pmevcntr's by writes to
1176      * PMSWINC, so there is no underlying count maintained by the PMU itself
1177      */
1178     return 0;
1179 }
1180 
1181 static int64_t swinc_ns_per(uint64_t ignored)
1182 {
1183     return -1;
1184 }
1185 
1186 /*
1187  * Return the underlying cycle count for the PMU cycle counters. If we're in
1188  * usermode, simply return 0.
1189  */
1190 static uint64_t cycles_get_count(CPUARMState *env)
1191 {
1192 #ifndef CONFIG_USER_ONLY
1193     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1194                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1195 #else
1196     return cpu_get_host_ticks();
1197 #endif
1198 }
1199 
1200 #ifndef CONFIG_USER_ONLY
1201 static int64_t cycles_ns_per(uint64_t cycles)
1202 {
1203     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1204 }
1205 
1206 static bool instructions_supported(CPUARMState *env)
1207 {
1208     return use_icount == 1 /* Precise instruction counting */;
1209 }
1210 
1211 static uint64_t instructions_get_count(CPUARMState *env)
1212 {
1213     return (uint64_t)cpu_get_icount_raw();
1214 }
1215 
1216 static int64_t instructions_ns_per(uint64_t icount)
1217 {
1218     return cpu_icount_to_ns((int64_t)icount);
1219 }
1220 #endif
1221 
1222 static bool pmu_8_1_events_supported(CPUARMState *env)
1223 {
1224     /* For events which are supported in any v8.1 PMU */
1225     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
1226 }
1227 
1228 static bool pmu_8_4_events_supported(CPUARMState *env)
1229 {
1230     /* For events which are supported in any v8.1 PMU */
1231     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
1232 }
1233 
1234 static uint64_t zero_event_get_count(CPUARMState *env)
1235 {
1236     /* For events which on QEMU never fire, so their count is always zero */
1237     return 0;
1238 }
1239 
1240 static int64_t zero_event_ns_per(uint64_t cycles)
1241 {
1242     /* An event which never fires can never overflow */
1243     return -1;
1244 }
1245 
1246 static const pm_event pm_events[] = {
1247     { .number = 0x000, /* SW_INCR */
1248       .supported = event_always_supported,
1249       .get_count = swinc_get_count,
1250       .ns_per_count = swinc_ns_per,
1251     },
1252 #ifndef CONFIG_USER_ONLY
1253     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1254       .supported = instructions_supported,
1255       .get_count = instructions_get_count,
1256       .ns_per_count = instructions_ns_per,
1257     },
1258     { .number = 0x011, /* CPU_CYCLES, Cycle */
1259       .supported = event_always_supported,
1260       .get_count = cycles_get_count,
1261       .ns_per_count = cycles_ns_per,
1262     },
1263 #endif
1264     { .number = 0x023, /* STALL_FRONTEND */
1265       .supported = pmu_8_1_events_supported,
1266       .get_count = zero_event_get_count,
1267       .ns_per_count = zero_event_ns_per,
1268     },
1269     { .number = 0x024, /* STALL_BACKEND */
1270       .supported = pmu_8_1_events_supported,
1271       .get_count = zero_event_get_count,
1272       .ns_per_count = zero_event_ns_per,
1273     },
1274     { .number = 0x03c, /* STALL */
1275       .supported = pmu_8_4_events_supported,
1276       .get_count = zero_event_get_count,
1277       .ns_per_count = zero_event_ns_per,
1278     },
1279 };
1280 
1281 /*
1282  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1283  * events (i.e. the statistical profiling extension), this implementation
1284  * should first be updated to something sparse instead of the current
1285  * supported_event_map[] array.
1286  */
1287 #define MAX_EVENT_ID 0x3c
1288 #define UNSUPPORTED_EVENT UINT16_MAX
1289 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1290 
1291 /*
1292  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1293  * of ARM event numbers to indices in our pm_events array.
1294  *
1295  * Note: Events in the 0x40XX range are not currently supported.
1296  */
1297 void pmu_init(ARMCPU *cpu)
1298 {
1299     unsigned int i;
1300 
1301     /*
1302      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1303      * events to them
1304      */
1305     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1306         supported_event_map[i] = UNSUPPORTED_EVENT;
1307     }
1308     cpu->pmceid0 = 0;
1309     cpu->pmceid1 = 0;
1310 
1311     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1312         const pm_event *cnt = &pm_events[i];
1313         assert(cnt->number <= MAX_EVENT_ID);
1314         /* We do not currently support events in the 0x40xx range */
1315         assert(cnt->number <= 0x3f);
1316 
1317         if (cnt->supported(&cpu->env)) {
1318             supported_event_map[cnt->number] = i;
1319             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1320             if (cnt->number & 0x20) {
1321                 cpu->pmceid1 |= event_mask;
1322             } else {
1323                 cpu->pmceid0 |= event_mask;
1324             }
1325         }
1326     }
1327 }
1328 
1329 /*
1330  * Check at runtime whether a PMU event is supported for the current machine
1331  */
1332 static bool event_supported(uint16_t number)
1333 {
1334     if (number > MAX_EVENT_ID) {
1335         return false;
1336     }
1337     return supported_event_map[number] != UNSUPPORTED_EVENT;
1338 }
1339 
1340 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1341                                    bool isread)
1342 {
1343     /* Performance monitor registers user accessibility is controlled
1344      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1345      * trapping to EL2 or EL3 for other accesses.
1346      */
1347     int el = arm_current_el(env);
1348 
1349     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1350         return CP_ACCESS_TRAP;
1351     }
1352     if (el < 2 && (env->cp15.mdcr_el2 & MDCR_TPM)
1353         && !arm_is_secure_below_el3(env)) {
1354         return CP_ACCESS_TRAP_EL2;
1355     }
1356     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1357         return CP_ACCESS_TRAP_EL3;
1358     }
1359 
1360     return CP_ACCESS_OK;
1361 }
1362 
1363 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1364                                            const ARMCPRegInfo *ri,
1365                                            bool isread)
1366 {
1367     /* ER: event counter read trap control */
1368     if (arm_feature(env, ARM_FEATURE_V8)
1369         && arm_current_el(env) == 0
1370         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1371         && isread) {
1372         return CP_ACCESS_OK;
1373     }
1374 
1375     return pmreg_access(env, ri, isread);
1376 }
1377 
1378 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1379                                          const ARMCPRegInfo *ri,
1380                                          bool isread)
1381 {
1382     /* SW: software increment write trap control */
1383     if (arm_feature(env, ARM_FEATURE_V8)
1384         && arm_current_el(env) == 0
1385         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1386         && !isread) {
1387         return CP_ACCESS_OK;
1388     }
1389 
1390     return pmreg_access(env, ri, isread);
1391 }
1392 
1393 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1394                                         const ARMCPRegInfo *ri,
1395                                         bool isread)
1396 {
1397     /* ER: event counter read trap control */
1398     if (arm_feature(env, ARM_FEATURE_V8)
1399         && arm_current_el(env) == 0
1400         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1401         return CP_ACCESS_OK;
1402     }
1403 
1404     return pmreg_access(env, ri, isread);
1405 }
1406 
1407 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1408                                          const ARMCPRegInfo *ri,
1409                                          bool isread)
1410 {
1411     /* CR: cycle counter read trap control */
1412     if (arm_feature(env, ARM_FEATURE_V8)
1413         && arm_current_el(env) == 0
1414         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1415         && isread) {
1416         return CP_ACCESS_OK;
1417     }
1418 
1419     return pmreg_access(env, ri, isread);
1420 }
1421 
1422 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1423  * the current EL, security state, and register configuration.
1424  */
1425 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1426 {
1427     uint64_t filter;
1428     bool e, p, u, nsk, nsu, nsh, m;
1429     bool enabled, prohibited, filtered;
1430     bool secure = arm_is_secure(env);
1431     int el = arm_current_el(env);
1432     uint8_t hpmn = env->cp15.mdcr_el2 & MDCR_HPMN;
1433 
1434     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1435         return false;
1436     }
1437 
1438     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1439             (counter < hpmn || counter == 31)) {
1440         e = env->cp15.c9_pmcr & PMCRE;
1441     } else {
1442         e = env->cp15.mdcr_el2 & MDCR_HPME;
1443     }
1444     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1445 
1446     if (!secure) {
1447         if (el == 2 && (counter < hpmn || counter == 31)) {
1448             prohibited = env->cp15.mdcr_el2 & MDCR_HPMD;
1449         } else {
1450             prohibited = false;
1451         }
1452     } else {
1453         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1454            (env->cp15.mdcr_el3 & MDCR_SPME);
1455     }
1456 
1457     if (prohibited && counter == 31) {
1458         prohibited = env->cp15.c9_pmcr & PMCRDP;
1459     }
1460 
1461     if (counter == 31) {
1462         filter = env->cp15.pmccfiltr_el0;
1463     } else {
1464         filter = env->cp15.c14_pmevtyper[counter];
1465     }
1466 
1467     p   = filter & PMXEVTYPER_P;
1468     u   = filter & PMXEVTYPER_U;
1469     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1470     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1471     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1472     m   = arm_el_is_aa64(env, 1) &&
1473               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1474 
1475     if (el == 0) {
1476         filtered = secure ? u : u != nsu;
1477     } else if (el == 1) {
1478         filtered = secure ? p : p != nsk;
1479     } else if (el == 2) {
1480         filtered = !nsh;
1481     } else { /* EL3 */
1482         filtered = m != p;
1483     }
1484 
1485     if (counter != 31) {
1486         /*
1487          * If not checking PMCCNTR, ensure the counter is setup to an event we
1488          * support
1489          */
1490         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1491         if (!event_supported(event)) {
1492             return false;
1493         }
1494     }
1495 
1496     return enabled && !prohibited && !filtered;
1497 }
1498 
1499 static void pmu_update_irq(CPUARMState *env)
1500 {
1501     ARMCPU *cpu = env_archcpu(env);
1502     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1503             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1504 }
1505 
1506 /*
1507  * Ensure c15_ccnt is the guest-visible count so that operations such as
1508  * enabling/disabling the counter or filtering, modifying the count itself,
1509  * etc. can be done logically. This is essentially a no-op if the counter is
1510  * not enabled at the time of the call.
1511  */
1512 static void pmccntr_op_start(CPUARMState *env)
1513 {
1514     uint64_t cycles = cycles_get_count(env);
1515 
1516     if (pmu_counter_enabled(env, 31)) {
1517         uint64_t eff_cycles = cycles;
1518         if (env->cp15.c9_pmcr & PMCRD) {
1519             /* Increment once every 64 processor clock cycles */
1520             eff_cycles /= 64;
1521         }
1522 
1523         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1524 
1525         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1526                                  1ull << 63 : 1ull << 31;
1527         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1528             env->cp15.c9_pmovsr |= (1 << 31);
1529             pmu_update_irq(env);
1530         }
1531 
1532         env->cp15.c15_ccnt = new_pmccntr;
1533     }
1534     env->cp15.c15_ccnt_delta = cycles;
1535 }
1536 
1537 /*
1538  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1539  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1540  * pmccntr_op_start.
1541  */
1542 static void pmccntr_op_finish(CPUARMState *env)
1543 {
1544     if (pmu_counter_enabled(env, 31)) {
1545 #ifndef CONFIG_USER_ONLY
1546         /* Calculate when the counter will next overflow */
1547         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1548         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1549             remaining_cycles = (uint32_t)remaining_cycles;
1550         }
1551         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1552 
1553         if (overflow_in > 0) {
1554             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1555                 overflow_in;
1556             ARMCPU *cpu = env_archcpu(env);
1557             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1558         }
1559 #endif
1560 
1561         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1562         if (env->cp15.c9_pmcr & PMCRD) {
1563             /* Increment once every 64 processor clock cycles */
1564             prev_cycles /= 64;
1565         }
1566         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1567     }
1568 }
1569 
1570 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1571 {
1572 
1573     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1574     uint64_t count = 0;
1575     if (event_supported(event)) {
1576         uint16_t event_idx = supported_event_map[event];
1577         count = pm_events[event_idx].get_count(env);
1578     }
1579 
1580     if (pmu_counter_enabled(env, counter)) {
1581         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1582 
1583         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1584             env->cp15.c9_pmovsr |= (1 << counter);
1585             pmu_update_irq(env);
1586         }
1587         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1588     }
1589     env->cp15.c14_pmevcntr_delta[counter] = count;
1590 }
1591 
1592 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1593 {
1594     if (pmu_counter_enabled(env, counter)) {
1595 #ifndef CONFIG_USER_ONLY
1596         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1597         uint16_t event_idx = supported_event_map[event];
1598         uint64_t delta = UINT32_MAX -
1599             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1600         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1601 
1602         if (overflow_in > 0) {
1603             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1604                 overflow_in;
1605             ARMCPU *cpu = env_archcpu(env);
1606             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1607         }
1608 #endif
1609 
1610         env->cp15.c14_pmevcntr_delta[counter] -=
1611             env->cp15.c14_pmevcntr[counter];
1612     }
1613 }
1614 
1615 void pmu_op_start(CPUARMState *env)
1616 {
1617     unsigned int i;
1618     pmccntr_op_start(env);
1619     for (i = 0; i < pmu_num_counters(env); i++) {
1620         pmevcntr_op_start(env, i);
1621     }
1622 }
1623 
1624 void pmu_op_finish(CPUARMState *env)
1625 {
1626     unsigned int i;
1627     pmccntr_op_finish(env);
1628     for (i = 0; i < pmu_num_counters(env); i++) {
1629         pmevcntr_op_finish(env, i);
1630     }
1631 }
1632 
1633 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1634 {
1635     pmu_op_start(&cpu->env);
1636 }
1637 
1638 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1639 {
1640     pmu_op_finish(&cpu->env);
1641 }
1642 
1643 void arm_pmu_timer_cb(void *opaque)
1644 {
1645     ARMCPU *cpu = opaque;
1646 
1647     /*
1648      * Update all the counter values based on the current underlying counts,
1649      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1650      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1651      * counter may expire.
1652      */
1653     pmu_op_start(&cpu->env);
1654     pmu_op_finish(&cpu->env);
1655 }
1656 
1657 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1658                        uint64_t value)
1659 {
1660     pmu_op_start(env);
1661 
1662     if (value & PMCRC) {
1663         /* The counter has been reset */
1664         env->cp15.c15_ccnt = 0;
1665     }
1666 
1667     if (value & PMCRP) {
1668         unsigned int i;
1669         for (i = 0; i < pmu_num_counters(env); i++) {
1670             env->cp15.c14_pmevcntr[i] = 0;
1671         }
1672     }
1673 
1674     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1675     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1676 
1677     pmu_op_finish(env);
1678 }
1679 
1680 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1681                           uint64_t value)
1682 {
1683     unsigned int i;
1684     for (i = 0; i < pmu_num_counters(env); i++) {
1685         /* Increment a counter's count iff: */
1686         if ((value & (1 << i)) && /* counter's bit is set */
1687                 /* counter is enabled and not filtered */
1688                 pmu_counter_enabled(env, i) &&
1689                 /* counter is SW_INCR */
1690                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1691             pmevcntr_op_start(env, i);
1692 
1693             /*
1694              * Detect if this write causes an overflow since we can't predict
1695              * PMSWINC overflows like we can for other events
1696              */
1697             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1698 
1699             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1700                 env->cp15.c9_pmovsr |= (1 << i);
1701                 pmu_update_irq(env);
1702             }
1703 
1704             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1705 
1706             pmevcntr_op_finish(env, i);
1707         }
1708     }
1709 }
1710 
1711 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1712 {
1713     uint64_t ret;
1714     pmccntr_op_start(env);
1715     ret = env->cp15.c15_ccnt;
1716     pmccntr_op_finish(env);
1717     return ret;
1718 }
1719 
1720 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1721                          uint64_t value)
1722 {
1723     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1724      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1725      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1726      * accessed.
1727      */
1728     env->cp15.c9_pmselr = value & 0x1f;
1729 }
1730 
1731 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1732                         uint64_t value)
1733 {
1734     pmccntr_op_start(env);
1735     env->cp15.c15_ccnt = value;
1736     pmccntr_op_finish(env);
1737 }
1738 
1739 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1740                             uint64_t value)
1741 {
1742     uint64_t cur_val = pmccntr_read(env, NULL);
1743 
1744     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1745 }
1746 
1747 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1748                             uint64_t value)
1749 {
1750     pmccntr_op_start(env);
1751     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1752     pmccntr_op_finish(env);
1753 }
1754 
1755 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1756                             uint64_t value)
1757 {
1758     pmccntr_op_start(env);
1759     /* M is not accessible from AArch32 */
1760     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1761         (value & PMCCFILTR);
1762     pmccntr_op_finish(env);
1763 }
1764 
1765 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1766 {
1767     /* M is not visible in AArch32 */
1768     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1769 }
1770 
1771 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1772                             uint64_t value)
1773 {
1774     value &= pmu_counter_mask(env);
1775     env->cp15.c9_pmcnten |= value;
1776 }
1777 
1778 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1779                              uint64_t value)
1780 {
1781     value &= pmu_counter_mask(env);
1782     env->cp15.c9_pmcnten &= ~value;
1783 }
1784 
1785 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1786                          uint64_t value)
1787 {
1788     value &= pmu_counter_mask(env);
1789     env->cp15.c9_pmovsr &= ~value;
1790     pmu_update_irq(env);
1791 }
1792 
1793 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1794                          uint64_t value)
1795 {
1796     value &= pmu_counter_mask(env);
1797     env->cp15.c9_pmovsr |= value;
1798     pmu_update_irq(env);
1799 }
1800 
1801 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1802                              uint64_t value, const uint8_t counter)
1803 {
1804     if (counter == 31) {
1805         pmccfiltr_write(env, ri, value);
1806     } else if (counter < pmu_num_counters(env)) {
1807         pmevcntr_op_start(env, counter);
1808 
1809         /*
1810          * If this counter's event type is changing, store the current
1811          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1812          * pmevcntr_op_finish has the correct baseline when it converts back to
1813          * a delta.
1814          */
1815         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1816             PMXEVTYPER_EVTCOUNT;
1817         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1818         if (old_event != new_event) {
1819             uint64_t count = 0;
1820             if (event_supported(new_event)) {
1821                 uint16_t event_idx = supported_event_map[new_event];
1822                 count = pm_events[event_idx].get_count(env);
1823             }
1824             env->cp15.c14_pmevcntr_delta[counter] = count;
1825         }
1826 
1827         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1828         pmevcntr_op_finish(env, counter);
1829     }
1830     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1831      * PMSELR value is equal to or greater than the number of implemented
1832      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1833      */
1834 }
1835 
1836 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1837                                const uint8_t counter)
1838 {
1839     if (counter == 31) {
1840         return env->cp15.pmccfiltr_el0;
1841     } else if (counter < pmu_num_counters(env)) {
1842         return env->cp15.c14_pmevtyper[counter];
1843     } else {
1844       /*
1845        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1846        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1847        */
1848         return 0;
1849     }
1850 }
1851 
1852 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1853                               uint64_t value)
1854 {
1855     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1856     pmevtyper_write(env, ri, value, counter);
1857 }
1858 
1859 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1860                                uint64_t value)
1861 {
1862     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1863     env->cp15.c14_pmevtyper[counter] = value;
1864 
1865     /*
1866      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1867      * pmu_op_finish calls when loading saved state for a migration. Because
1868      * we're potentially updating the type of event here, the value written to
1869      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1870      * different counter type. Therefore, we need to set this value to the
1871      * current count for the counter type we're writing so that pmu_op_finish
1872      * has the correct count for its calculation.
1873      */
1874     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1875     if (event_supported(event)) {
1876         uint16_t event_idx = supported_event_map[event];
1877         env->cp15.c14_pmevcntr_delta[counter] =
1878             pm_events[event_idx].get_count(env);
1879     }
1880 }
1881 
1882 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1883 {
1884     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1885     return pmevtyper_read(env, ri, counter);
1886 }
1887 
1888 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1889                              uint64_t value)
1890 {
1891     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1892 }
1893 
1894 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1895 {
1896     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1897 }
1898 
1899 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1900                              uint64_t value, uint8_t counter)
1901 {
1902     if (counter < pmu_num_counters(env)) {
1903         pmevcntr_op_start(env, counter);
1904         env->cp15.c14_pmevcntr[counter] = value;
1905         pmevcntr_op_finish(env, counter);
1906     }
1907     /*
1908      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1909      * are CONSTRAINED UNPREDICTABLE.
1910      */
1911 }
1912 
1913 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1914                               uint8_t counter)
1915 {
1916     if (counter < pmu_num_counters(env)) {
1917         uint64_t ret;
1918         pmevcntr_op_start(env, counter);
1919         ret = env->cp15.c14_pmevcntr[counter];
1920         pmevcntr_op_finish(env, counter);
1921         return ret;
1922     } else {
1923       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1924        * are CONSTRAINED UNPREDICTABLE. */
1925         return 0;
1926     }
1927 }
1928 
1929 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1930                              uint64_t value)
1931 {
1932     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1933     pmevcntr_write(env, ri, value, counter);
1934 }
1935 
1936 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1937 {
1938     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1939     return pmevcntr_read(env, ri, counter);
1940 }
1941 
1942 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1943                              uint64_t value)
1944 {
1945     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1946     assert(counter < pmu_num_counters(env));
1947     env->cp15.c14_pmevcntr[counter] = value;
1948     pmevcntr_write(env, ri, value, counter);
1949 }
1950 
1951 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1952 {
1953     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1954     assert(counter < pmu_num_counters(env));
1955     return env->cp15.c14_pmevcntr[counter];
1956 }
1957 
1958 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1959                              uint64_t value)
1960 {
1961     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1962 }
1963 
1964 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1965 {
1966     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1967 }
1968 
1969 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1970                             uint64_t value)
1971 {
1972     if (arm_feature(env, ARM_FEATURE_V8)) {
1973         env->cp15.c9_pmuserenr = value & 0xf;
1974     } else {
1975         env->cp15.c9_pmuserenr = value & 1;
1976     }
1977 }
1978 
1979 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1980                              uint64_t value)
1981 {
1982     /* We have no event counters so only the C bit can be changed */
1983     value &= pmu_counter_mask(env);
1984     env->cp15.c9_pminten |= value;
1985     pmu_update_irq(env);
1986 }
1987 
1988 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1989                              uint64_t value)
1990 {
1991     value &= pmu_counter_mask(env);
1992     env->cp15.c9_pminten &= ~value;
1993     pmu_update_irq(env);
1994 }
1995 
1996 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1997                        uint64_t value)
1998 {
1999     /* Note that even though the AArch64 view of this register has bits
2000      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
2001      * architectural requirements for bits which are RES0 only in some
2002      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
2003      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
2004      */
2005     raw_write(env, ri, value & ~0x1FULL);
2006 }
2007 
2008 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2009 {
2010     /* Begin with base v8.0 state.  */
2011     uint32_t valid_mask = 0x3fff;
2012     ARMCPU *cpu = env_archcpu(env);
2013 
2014     if (arm_el_is_aa64(env, 3)) {
2015         value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
2016         valid_mask &= ~SCR_NET;
2017     } else {
2018         valid_mask &= ~(SCR_RW | SCR_ST);
2019     }
2020 
2021     if (!arm_feature(env, ARM_FEATURE_EL2)) {
2022         valid_mask &= ~SCR_HCE;
2023 
2024         /* On ARMv7, SMD (or SCD as it is called in v7) is only
2025          * supported if EL2 exists. The bit is UNK/SBZP when
2026          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
2027          * when EL2 is unavailable.
2028          * On ARMv8, this bit is always available.
2029          */
2030         if (arm_feature(env, ARM_FEATURE_V7) &&
2031             !arm_feature(env, ARM_FEATURE_V8)) {
2032             valid_mask &= ~SCR_SMD;
2033         }
2034     }
2035     if (cpu_isar_feature(aa64_lor, cpu)) {
2036         valid_mask |= SCR_TLOR;
2037     }
2038     if (cpu_isar_feature(aa64_pauth, cpu)) {
2039         valid_mask |= SCR_API | SCR_APK;
2040     }
2041 
2042     /* Clear all-context RES0 bits.  */
2043     value &= valid_mask;
2044     raw_write(env, ri, value);
2045 }
2046 
2047 static CPAccessResult access_aa64_tid2(CPUARMState *env,
2048                                        const ARMCPRegInfo *ri,
2049                                        bool isread)
2050 {
2051     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
2052         return CP_ACCESS_TRAP_EL2;
2053     }
2054 
2055     return CP_ACCESS_OK;
2056 }
2057 
2058 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2059 {
2060     ARMCPU *cpu = env_archcpu(env);
2061 
2062     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
2063      * bank
2064      */
2065     uint32_t index = A32_BANKED_REG_GET(env, csselr,
2066                                         ri->secure & ARM_CP_SECSTATE_S);
2067 
2068     return cpu->ccsidr[index];
2069 }
2070 
2071 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2072                          uint64_t value)
2073 {
2074     raw_write(env, ri, value & 0xf);
2075 }
2076 
2077 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2078 {
2079     CPUState *cs = env_cpu(env);
2080     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
2081     uint64_t ret = 0;
2082     bool allow_virt = (arm_current_el(env) == 1 &&
2083                        (!arm_is_secure_below_el3(env) ||
2084                         (env->cp15.scr_el3 & SCR_EEL2)));
2085 
2086     if (allow_virt && (hcr_el2 & HCR_IMO)) {
2087         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
2088             ret |= CPSR_I;
2089         }
2090     } else {
2091         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
2092             ret |= CPSR_I;
2093         }
2094     }
2095 
2096     if (allow_virt && (hcr_el2 & HCR_FMO)) {
2097         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
2098             ret |= CPSR_F;
2099         }
2100     } else {
2101         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
2102             ret |= CPSR_F;
2103         }
2104     }
2105 
2106     /* External aborts are not possible in QEMU so A bit is always clear */
2107     return ret;
2108 }
2109 
2110 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2111                                        bool isread)
2112 {
2113     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
2114         return CP_ACCESS_TRAP_EL2;
2115     }
2116 
2117     return CP_ACCESS_OK;
2118 }
2119 
2120 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2121                                        bool isread)
2122 {
2123     if (arm_feature(env, ARM_FEATURE_V8)) {
2124         return access_aa64_tid1(env, ri, isread);
2125     }
2126 
2127     return CP_ACCESS_OK;
2128 }
2129 
2130 static const ARMCPRegInfo v7_cp_reginfo[] = {
2131     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
2132     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
2133       .access = PL1_W, .type = ARM_CP_NOP },
2134     /* Performance monitors are implementation defined in v7,
2135      * but with an ARM recommended set of registers, which we
2136      * follow.
2137      *
2138      * Performance registers fall into three categories:
2139      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
2140      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
2141      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
2142      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
2143      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
2144      */
2145     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
2146       .access = PL0_RW, .type = ARM_CP_ALIAS,
2147       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2148       .writefn = pmcntenset_write,
2149       .accessfn = pmreg_access,
2150       .raw_writefn = raw_write },
2151     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
2152       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
2153       .access = PL0_RW, .accessfn = pmreg_access,
2154       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
2155       .writefn = pmcntenset_write, .raw_writefn = raw_write },
2156     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
2157       .access = PL0_RW,
2158       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2159       .accessfn = pmreg_access,
2160       .writefn = pmcntenclr_write,
2161       .type = ARM_CP_ALIAS },
2162     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
2163       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
2164       .access = PL0_RW, .accessfn = pmreg_access,
2165       .type = ARM_CP_ALIAS,
2166       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
2167       .writefn = pmcntenclr_write },
2168     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
2169       .access = PL0_RW, .type = ARM_CP_IO,
2170       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2171       .accessfn = pmreg_access,
2172       .writefn = pmovsr_write,
2173       .raw_writefn = raw_write },
2174     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2175       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2176       .access = PL0_RW, .accessfn = pmreg_access,
2177       .type = ARM_CP_ALIAS | ARM_CP_IO,
2178       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2179       .writefn = pmovsr_write,
2180       .raw_writefn = raw_write },
2181     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2182       .access = PL0_W, .accessfn = pmreg_access_swinc,
2183       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2184       .writefn = pmswinc_write },
2185     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2186       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .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 = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2191       .access = PL0_RW, .type = ARM_CP_ALIAS,
2192       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2193       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2194       .raw_writefn = raw_write},
2195     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2196       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2197       .access = PL0_RW, .accessfn = pmreg_access_selr,
2198       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2199       .writefn = pmselr_write, .raw_writefn = raw_write, },
2200     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2201       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2202       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2203       .accessfn = pmreg_access_ccntr },
2204     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2205       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2206       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2207       .type = ARM_CP_IO,
2208       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2209       .readfn = pmccntr_read, .writefn = pmccntr_write,
2210       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2211     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2212       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2213       .access = PL0_RW, .accessfn = pmreg_access,
2214       .type = ARM_CP_ALIAS | ARM_CP_IO,
2215       .resetvalue = 0, },
2216     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2217       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2218       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2219       .access = PL0_RW, .accessfn = pmreg_access,
2220       .type = ARM_CP_IO,
2221       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2222       .resetvalue = 0, },
2223     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2224       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2225       .accessfn = pmreg_access,
2226       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2227     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2228       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .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 = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2233       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2234       .accessfn = pmreg_access_xevcntr,
2235       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2236     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2237       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .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 = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2242       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2243       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2244       .resetvalue = 0,
2245       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2246     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2247       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2248       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2249       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2250       .resetvalue = 0,
2251       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2252     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2253       .access = PL1_RW, .accessfn = access_tpm,
2254       .type = ARM_CP_ALIAS | ARM_CP_IO,
2255       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2256       .resetvalue = 0,
2257       .writefn = pmintenset_write, .raw_writefn = raw_write },
2258     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2259       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2260       .access = PL1_RW, .accessfn = access_tpm,
2261       .type = ARM_CP_IO,
2262       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2263       .writefn = pmintenset_write, .raw_writefn = raw_write,
2264       .resetvalue = 0x0 },
2265     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2266       .access = PL1_RW, .accessfn = access_tpm,
2267       .type = ARM_CP_ALIAS | ARM_CP_IO,
2268       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2269       .writefn = pmintenclr_write, },
2270     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2271       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2272       .access = PL1_RW, .accessfn = access_tpm,
2273       .type = ARM_CP_ALIAS | ARM_CP_IO,
2274       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2275       .writefn = pmintenclr_write },
2276     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2277       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2278       .access = PL1_R,
2279       .accessfn = access_aa64_tid2,
2280       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2281     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2282       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2283       .access = PL1_RW,
2284       .accessfn = access_aa64_tid2,
2285       .writefn = csselr_write, .resetvalue = 0,
2286       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2287                              offsetof(CPUARMState, cp15.csselr_ns) } },
2288     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2289      * just RAZ for all cores:
2290      */
2291     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2292       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2293       .access = PL1_R, .type = ARM_CP_CONST,
2294       .accessfn = access_aa64_tid1,
2295       .resetvalue = 0 },
2296     /* Auxiliary fault status registers: these also are IMPDEF, and we
2297      * choose to RAZ/WI for all cores.
2298      */
2299     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2300       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2301       .access = PL1_RW, .accessfn = access_tvm_trvm,
2302       .type = ARM_CP_CONST, .resetvalue = 0 },
2303     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2304       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2305       .access = PL1_RW, .accessfn = access_tvm_trvm,
2306       .type = ARM_CP_CONST, .resetvalue = 0 },
2307     /* MAIR can just read-as-written because we don't implement caches
2308      * and so don't need to care about memory attributes.
2309      */
2310     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2311       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2312       .access = PL1_RW, .accessfn = access_tvm_trvm,
2313       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2314       .resetvalue = 0 },
2315     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2316       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2317       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2318       .resetvalue = 0 },
2319     /* For non-long-descriptor page tables these are PRRR and NMRR;
2320      * regardless they still act as reads-as-written for QEMU.
2321      */
2322      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2323       * allows them to assign the correct fieldoffset based on the endianness
2324       * handled in the field definitions.
2325       */
2326     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2327       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2328       .access = PL1_RW, .accessfn = access_tvm_trvm,
2329       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2330                              offsetof(CPUARMState, cp15.mair0_ns) },
2331       .resetfn = arm_cp_reset_ignore },
2332     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2333       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2334       .access = PL1_RW, .accessfn = access_tvm_trvm,
2335       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2336                              offsetof(CPUARMState, cp15.mair1_ns) },
2337       .resetfn = arm_cp_reset_ignore },
2338     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2339       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2340       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2341     /* 32 bit ITLB invalidates */
2342     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2343       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2344       .writefn = tlbiall_write },
2345     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2346       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2347       .writefn = tlbimva_write },
2348     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2349       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2350       .writefn = tlbiasid_write },
2351     /* 32 bit DTLB invalidates */
2352     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2353       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2354       .writefn = tlbiall_write },
2355     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2356       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2357       .writefn = tlbimva_write },
2358     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2359       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2360       .writefn = tlbiasid_write },
2361     /* 32 bit TLB invalidates */
2362     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2363       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2364       .writefn = tlbiall_write },
2365     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2366       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2367       .writefn = tlbimva_write },
2368     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2369       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2370       .writefn = tlbiasid_write },
2371     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2372       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2373       .writefn = tlbimvaa_write },
2374     REGINFO_SENTINEL
2375 };
2376 
2377 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2378     /* 32 bit TLB invalidates, Inner Shareable */
2379     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2380       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2381       .writefn = tlbiall_is_write },
2382     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2383       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2384       .writefn = tlbimva_is_write },
2385     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2386       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2387       .writefn = tlbiasid_is_write },
2388     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2389       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2390       .writefn = tlbimvaa_is_write },
2391     REGINFO_SENTINEL
2392 };
2393 
2394 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2395     /* PMOVSSET is not implemented in v7 before v7ve */
2396     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2397       .access = PL0_RW, .accessfn = pmreg_access,
2398       .type = ARM_CP_ALIAS | ARM_CP_IO,
2399       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2400       .writefn = pmovsset_write,
2401       .raw_writefn = raw_write },
2402     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2403       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2404       .access = PL0_RW, .accessfn = pmreg_access,
2405       .type = ARM_CP_ALIAS | ARM_CP_IO,
2406       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2407       .writefn = pmovsset_write,
2408       .raw_writefn = raw_write },
2409     REGINFO_SENTINEL
2410 };
2411 
2412 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2413                         uint64_t value)
2414 {
2415     value &= 1;
2416     env->teecr = value;
2417 }
2418 
2419 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2420                                     bool isread)
2421 {
2422     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2423         return CP_ACCESS_TRAP;
2424     }
2425     return CP_ACCESS_OK;
2426 }
2427 
2428 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2429     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2430       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2431       .resetvalue = 0,
2432       .writefn = teecr_write },
2433     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2434       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2435       .accessfn = teehbr_access, .resetvalue = 0 },
2436     REGINFO_SENTINEL
2437 };
2438 
2439 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2440     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2441       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2442       .access = PL0_RW,
2443       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2444     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2445       .access = PL0_RW,
2446       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2447                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2448       .resetfn = arm_cp_reset_ignore },
2449     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2450       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2451       .access = PL0_R|PL1_W,
2452       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2453       .resetvalue = 0},
2454     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2455       .access = PL0_R|PL1_W,
2456       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2457                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2458       .resetfn = arm_cp_reset_ignore },
2459     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2460       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2461       .access = PL1_RW,
2462       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2463     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2464       .access = PL1_RW,
2465       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2466                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2467       .resetvalue = 0 },
2468     REGINFO_SENTINEL
2469 };
2470 
2471 #ifndef CONFIG_USER_ONLY
2472 
2473 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2474                                        bool isread)
2475 {
2476     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2477      * Writable only at the highest implemented exception level.
2478      */
2479     int el = arm_current_el(env);
2480     uint64_t hcr;
2481     uint32_t cntkctl;
2482 
2483     switch (el) {
2484     case 0:
2485         hcr = arm_hcr_el2_eff(env);
2486         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2487             cntkctl = env->cp15.cnthctl_el2;
2488         } else {
2489             cntkctl = env->cp15.c14_cntkctl;
2490         }
2491         if (!extract32(cntkctl, 0, 2)) {
2492             return CP_ACCESS_TRAP;
2493         }
2494         break;
2495     case 1:
2496         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2497             arm_is_secure_below_el3(env)) {
2498             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2499             return CP_ACCESS_TRAP_UNCATEGORIZED;
2500         }
2501         break;
2502     case 2:
2503     case 3:
2504         break;
2505     }
2506 
2507     if (!isread && el < arm_highest_el(env)) {
2508         return CP_ACCESS_TRAP_UNCATEGORIZED;
2509     }
2510 
2511     return CP_ACCESS_OK;
2512 }
2513 
2514 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2515                                         bool isread)
2516 {
2517     unsigned int cur_el = arm_current_el(env);
2518     bool secure = arm_is_secure(env);
2519     uint64_t hcr = arm_hcr_el2_eff(env);
2520 
2521     switch (cur_el) {
2522     case 0:
2523         /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2524         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2525             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2526                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2527         }
2528 
2529         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2530         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2531             return CP_ACCESS_TRAP;
2532         }
2533 
2534         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2535         if (hcr & HCR_E2H) {
2536             if (timeridx == GTIMER_PHYS &&
2537                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2538                 return CP_ACCESS_TRAP_EL2;
2539             }
2540         } else {
2541             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2542             if (arm_feature(env, ARM_FEATURE_EL2) &&
2543                 timeridx == GTIMER_PHYS && !secure &&
2544                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2545                 return CP_ACCESS_TRAP_EL2;
2546             }
2547         }
2548         break;
2549 
2550     case 1:
2551         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2552         if (arm_feature(env, ARM_FEATURE_EL2) &&
2553             timeridx == GTIMER_PHYS && !secure &&
2554             (hcr & HCR_E2H
2555              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2556              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2557             return CP_ACCESS_TRAP_EL2;
2558         }
2559         break;
2560     }
2561     return CP_ACCESS_OK;
2562 }
2563 
2564 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2565                                       bool isread)
2566 {
2567     unsigned int cur_el = arm_current_el(env);
2568     bool secure = arm_is_secure(env);
2569     uint64_t hcr = arm_hcr_el2_eff(env);
2570 
2571     switch (cur_el) {
2572     case 0:
2573         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2574             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2575             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2576                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2577         }
2578 
2579         /*
2580          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2581          * EL0 if EL0[PV]TEN is zero.
2582          */
2583         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2584             return CP_ACCESS_TRAP;
2585         }
2586         /* fall through */
2587 
2588     case 1:
2589         if (arm_feature(env, ARM_FEATURE_EL2) &&
2590             timeridx == GTIMER_PHYS && !secure) {
2591             if (hcr & HCR_E2H) {
2592                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2593                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2594                     return CP_ACCESS_TRAP_EL2;
2595                 }
2596             } else {
2597                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2598                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2599                     return CP_ACCESS_TRAP_EL2;
2600                 }
2601             }
2602         }
2603         break;
2604     }
2605     return CP_ACCESS_OK;
2606 }
2607 
2608 static CPAccessResult gt_pct_access(CPUARMState *env,
2609                                     const ARMCPRegInfo *ri,
2610                                     bool isread)
2611 {
2612     return gt_counter_access(env, GTIMER_PHYS, isread);
2613 }
2614 
2615 static CPAccessResult gt_vct_access(CPUARMState *env,
2616                                     const ARMCPRegInfo *ri,
2617                                     bool isread)
2618 {
2619     return gt_counter_access(env, GTIMER_VIRT, isread);
2620 }
2621 
2622 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2623                                        bool isread)
2624 {
2625     return gt_timer_access(env, GTIMER_PHYS, isread);
2626 }
2627 
2628 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2629                                        bool isread)
2630 {
2631     return gt_timer_access(env, GTIMER_VIRT, isread);
2632 }
2633 
2634 static CPAccessResult gt_stimer_access(CPUARMState *env,
2635                                        const ARMCPRegInfo *ri,
2636                                        bool isread)
2637 {
2638     /* The AArch64 register view of the secure physical timer is
2639      * always accessible from EL3, and configurably accessible from
2640      * Secure EL1.
2641      */
2642     switch (arm_current_el(env)) {
2643     case 1:
2644         if (!arm_is_secure(env)) {
2645             return CP_ACCESS_TRAP;
2646         }
2647         if (!(env->cp15.scr_el3 & SCR_ST)) {
2648             return CP_ACCESS_TRAP_EL3;
2649         }
2650         return CP_ACCESS_OK;
2651     case 0:
2652     case 2:
2653         return CP_ACCESS_TRAP;
2654     case 3:
2655         return CP_ACCESS_OK;
2656     default:
2657         g_assert_not_reached();
2658     }
2659 }
2660 
2661 static uint64_t gt_get_countervalue(CPUARMState *env)
2662 {
2663     ARMCPU *cpu = env_archcpu(env);
2664 
2665     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2666 }
2667 
2668 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2669 {
2670     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2671 
2672     if (gt->ctl & 1) {
2673         /* Timer enabled: calculate and set current ISTATUS, irq, and
2674          * reset timer to when ISTATUS next has to change
2675          */
2676         uint64_t offset = timeridx == GTIMER_VIRT ?
2677                                       cpu->env.cp15.cntvoff_el2 : 0;
2678         uint64_t count = gt_get_countervalue(&cpu->env);
2679         /* Note that this must be unsigned 64 bit arithmetic: */
2680         int istatus = count - offset >= gt->cval;
2681         uint64_t nexttick;
2682         int irqstate;
2683 
2684         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2685 
2686         irqstate = (istatus && !(gt->ctl & 2));
2687         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2688 
2689         if (istatus) {
2690             /* Next transition is when count rolls back over to zero */
2691             nexttick = UINT64_MAX;
2692         } else {
2693             /* Next transition is when we hit cval */
2694             nexttick = gt->cval + offset;
2695         }
2696         /* Note that the desired next expiry time might be beyond the
2697          * signed-64-bit range of a QEMUTimer -- in this case we just
2698          * set the timer for as far in the future as possible. When the
2699          * timer expires we will reset the timer for any remaining period.
2700          */
2701         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2702             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2703         } else {
2704             timer_mod(cpu->gt_timer[timeridx], nexttick);
2705         }
2706         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2707     } else {
2708         /* Timer disabled: ISTATUS and timer output always clear */
2709         gt->ctl &= ~4;
2710         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2711         timer_del(cpu->gt_timer[timeridx]);
2712         trace_arm_gt_recalc_disabled(timeridx);
2713     }
2714 }
2715 
2716 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2717                            int timeridx)
2718 {
2719     ARMCPU *cpu = env_archcpu(env);
2720 
2721     timer_del(cpu->gt_timer[timeridx]);
2722 }
2723 
2724 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2725 {
2726     return gt_get_countervalue(env);
2727 }
2728 
2729 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2730 {
2731     uint64_t hcr;
2732 
2733     switch (arm_current_el(env)) {
2734     case 2:
2735         hcr = arm_hcr_el2_eff(env);
2736         if (hcr & HCR_E2H) {
2737             return 0;
2738         }
2739         break;
2740     case 0:
2741         hcr = arm_hcr_el2_eff(env);
2742         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2743             return 0;
2744         }
2745         break;
2746     }
2747 
2748     return env->cp15.cntvoff_el2;
2749 }
2750 
2751 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2752 {
2753     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2754 }
2755 
2756 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2757                           int timeridx,
2758                           uint64_t value)
2759 {
2760     trace_arm_gt_cval_write(timeridx, value);
2761     env->cp15.c14_timer[timeridx].cval = value;
2762     gt_recalc_timer(env_archcpu(env), timeridx);
2763 }
2764 
2765 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2766                              int timeridx)
2767 {
2768     uint64_t offset = 0;
2769 
2770     switch (timeridx) {
2771     case GTIMER_VIRT:
2772     case GTIMER_HYPVIRT:
2773         offset = gt_virt_cnt_offset(env);
2774         break;
2775     }
2776 
2777     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2778                       (gt_get_countervalue(env) - offset));
2779 }
2780 
2781 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2782                           int timeridx,
2783                           uint64_t value)
2784 {
2785     uint64_t offset = 0;
2786 
2787     switch (timeridx) {
2788     case GTIMER_VIRT:
2789     case GTIMER_HYPVIRT:
2790         offset = gt_virt_cnt_offset(env);
2791         break;
2792     }
2793 
2794     trace_arm_gt_tval_write(timeridx, value);
2795     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2796                                          sextract64(value, 0, 32);
2797     gt_recalc_timer(env_archcpu(env), timeridx);
2798 }
2799 
2800 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2801                          int timeridx,
2802                          uint64_t value)
2803 {
2804     ARMCPU *cpu = env_archcpu(env);
2805     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2806 
2807     trace_arm_gt_ctl_write(timeridx, value);
2808     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2809     if ((oldval ^ value) & 1) {
2810         /* Enable toggled */
2811         gt_recalc_timer(cpu, timeridx);
2812     } else if ((oldval ^ value) & 2) {
2813         /* IMASK toggled: don't need to recalculate,
2814          * just set the interrupt line based on ISTATUS
2815          */
2816         int irqstate = (oldval & 4) && !(value & 2);
2817 
2818         trace_arm_gt_imask_toggle(timeridx, irqstate);
2819         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2820     }
2821 }
2822 
2823 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2824 {
2825     gt_timer_reset(env, ri, GTIMER_PHYS);
2826 }
2827 
2828 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2829                                uint64_t value)
2830 {
2831     gt_cval_write(env, ri, GTIMER_PHYS, value);
2832 }
2833 
2834 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2835 {
2836     return gt_tval_read(env, ri, GTIMER_PHYS);
2837 }
2838 
2839 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2840                                uint64_t value)
2841 {
2842     gt_tval_write(env, ri, GTIMER_PHYS, value);
2843 }
2844 
2845 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2846                               uint64_t value)
2847 {
2848     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2849 }
2850 
2851 static int gt_phys_redir_timeridx(CPUARMState *env)
2852 {
2853     switch (arm_mmu_idx(env)) {
2854     case ARMMMUIdx_E20_0:
2855     case ARMMMUIdx_E20_2:
2856     case ARMMMUIdx_E20_2_PAN:
2857         return GTIMER_HYP;
2858     default:
2859         return GTIMER_PHYS;
2860     }
2861 }
2862 
2863 static int gt_virt_redir_timeridx(CPUARMState *env)
2864 {
2865     switch (arm_mmu_idx(env)) {
2866     case ARMMMUIdx_E20_0:
2867     case ARMMMUIdx_E20_2:
2868     case ARMMMUIdx_E20_2_PAN:
2869         return GTIMER_HYPVIRT;
2870     default:
2871         return GTIMER_VIRT;
2872     }
2873 }
2874 
2875 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2876                                         const ARMCPRegInfo *ri)
2877 {
2878     int timeridx = gt_phys_redir_timeridx(env);
2879     return env->cp15.c14_timer[timeridx].cval;
2880 }
2881 
2882 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2883                                      uint64_t value)
2884 {
2885     int timeridx = gt_phys_redir_timeridx(env);
2886     gt_cval_write(env, ri, timeridx, value);
2887 }
2888 
2889 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2890                                         const ARMCPRegInfo *ri)
2891 {
2892     int timeridx = gt_phys_redir_timeridx(env);
2893     return gt_tval_read(env, ri, timeridx);
2894 }
2895 
2896 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2897                                      uint64_t value)
2898 {
2899     int timeridx = gt_phys_redir_timeridx(env);
2900     gt_tval_write(env, ri, timeridx, value);
2901 }
2902 
2903 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2904                                        const ARMCPRegInfo *ri)
2905 {
2906     int timeridx = gt_phys_redir_timeridx(env);
2907     return env->cp15.c14_timer[timeridx].ctl;
2908 }
2909 
2910 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2911                                     uint64_t value)
2912 {
2913     int timeridx = gt_phys_redir_timeridx(env);
2914     gt_ctl_write(env, ri, timeridx, value);
2915 }
2916 
2917 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2918 {
2919     gt_timer_reset(env, ri, GTIMER_VIRT);
2920 }
2921 
2922 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2923                                uint64_t value)
2924 {
2925     gt_cval_write(env, ri, GTIMER_VIRT, value);
2926 }
2927 
2928 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2929 {
2930     return gt_tval_read(env, ri, GTIMER_VIRT);
2931 }
2932 
2933 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2934                                uint64_t value)
2935 {
2936     gt_tval_write(env, ri, GTIMER_VIRT, value);
2937 }
2938 
2939 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2940                               uint64_t value)
2941 {
2942     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2943 }
2944 
2945 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2946                               uint64_t value)
2947 {
2948     ARMCPU *cpu = env_archcpu(env);
2949 
2950     trace_arm_gt_cntvoff_write(value);
2951     raw_write(env, ri, value);
2952     gt_recalc_timer(cpu, GTIMER_VIRT);
2953 }
2954 
2955 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
2956                                         const ARMCPRegInfo *ri)
2957 {
2958     int timeridx = gt_virt_redir_timeridx(env);
2959     return env->cp15.c14_timer[timeridx].cval;
2960 }
2961 
2962 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2963                                      uint64_t value)
2964 {
2965     int timeridx = gt_virt_redir_timeridx(env);
2966     gt_cval_write(env, ri, timeridx, value);
2967 }
2968 
2969 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
2970                                         const ARMCPRegInfo *ri)
2971 {
2972     int timeridx = gt_virt_redir_timeridx(env);
2973     return gt_tval_read(env, ri, timeridx);
2974 }
2975 
2976 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2977                                      uint64_t value)
2978 {
2979     int timeridx = gt_virt_redir_timeridx(env);
2980     gt_tval_write(env, ri, timeridx, value);
2981 }
2982 
2983 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
2984                                        const ARMCPRegInfo *ri)
2985 {
2986     int timeridx = gt_virt_redir_timeridx(env);
2987     return env->cp15.c14_timer[timeridx].ctl;
2988 }
2989 
2990 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2991                                     uint64_t value)
2992 {
2993     int timeridx = gt_virt_redir_timeridx(env);
2994     gt_ctl_write(env, ri, timeridx, value);
2995 }
2996 
2997 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2998 {
2999     gt_timer_reset(env, ri, GTIMER_HYP);
3000 }
3001 
3002 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3003                               uint64_t value)
3004 {
3005     gt_cval_write(env, ri, GTIMER_HYP, value);
3006 }
3007 
3008 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3009 {
3010     return gt_tval_read(env, ri, GTIMER_HYP);
3011 }
3012 
3013 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3014                               uint64_t value)
3015 {
3016     gt_tval_write(env, ri, GTIMER_HYP, value);
3017 }
3018 
3019 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3020                               uint64_t value)
3021 {
3022     gt_ctl_write(env, ri, GTIMER_HYP, value);
3023 }
3024 
3025 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3026 {
3027     gt_timer_reset(env, ri, GTIMER_SEC);
3028 }
3029 
3030 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3031                               uint64_t value)
3032 {
3033     gt_cval_write(env, ri, GTIMER_SEC, value);
3034 }
3035 
3036 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3037 {
3038     return gt_tval_read(env, ri, GTIMER_SEC);
3039 }
3040 
3041 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3042                               uint64_t value)
3043 {
3044     gt_tval_write(env, ri, GTIMER_SEC, value);
3045 }
3046 
3047 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3048                               uint64_t value)
3049 {
3050     gt_ctl_write(env, ri, GTIMER_SEC, value);
3051 }
3052 
3053 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3054 {
3055     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
3056 }
3057 
3058 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3059                              uint64_t value)
3060 {
3061     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
3062 }
3063 
3064 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3065 {
3066     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
3067 }
3068 
3069 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3070                              uint64_t value)
3071 {
3072     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
3073 }
3074 
3075 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3076                             uint64_t value)
3077 {
3078     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
3079 }
3080 
3081 void arm_gt_ptimer_cb(void *opaque)
3082 {
3083     ARMCPU *cpu = opaque;
3084 
3085     gt_recalc_timer(cpu, GTIMER_PHYS);
3086 }
3087 
3088 void arm_gt_vtimer_cb(void *opaque)
3089 {
3090     ARMCPU *cpu = opaque;
3091 
3092     gt_recalc_timer(cpu, GTIMER_VIRT);
3093 }
3094 
3095 void arm_gt_htimer_cb(void *opaque)
3096 {
3097     ARMCPU *cpu = opaque;
3098 
3099     gt_recalc_timer(cpu, GTIMER_HYP);
3100 }
3101 
3102 void arm_gt_stimer_cb(void *opaque)
3103 {
3104     ARMCPU *cpu = opaque;
3105 
3106     gt_recalc_timer(cpu, GTIMER_SEC);
3107 }
3108 
3109 void arm_gt_hvtimer_cb(void *opaque)
3110 {
3111     ARMCPU *cpu = opaque;
3112 
3113     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
3114 }
3115 
3116 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
3117 {
3118     ARMCPU *cpu = env_archcpu(env);
3119 
3120     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
3121 }
3122 
3123 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3124     /* Note that CNTFRQ is purely reads-as-written for the benefit
3125      * of software; writing it doesn't actually change the timer frequency.
3126      * Our reset value matches the fixed frequency we implement the timer at.
3127      */
3128     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
3129       .type = ARM_CP_ALIAS,
3130       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3131       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
3132     },
3133     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3134       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3135       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3136       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3137       .resetfn = arm_gt_cntfrq_reset,
3138     },
3139     /* overall control: mostly access permissions */
3140     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
3141       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
3142       .access = PL1_RW,
3143       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
3144       .resetvalue = 0,
3145     },
3146     /* per-timer control */
3147     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3148       .secure = ARM_CP_SECSTATE_NS,
3149       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3150       .accessfn = gt_ptimer_access,
3151       .fieldoffset = offsetoflow32(CPUARMState,
3152                                    cp15.c14_timer[GTIMER_PHYS].ctl),
3153       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3154       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3155     },
3156     { .name = "CNTP_CTL_S",
3157       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3158       .secure = ARM_CP_SECSTATE_S,
3159       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3160       .accessfn = gt_ptimer_access,
3161       .fieldoffset = offsetoflow32(CPUARMState,
3162                                    cp15.c14_timer[GTIMER_SEC].ctl),
3163       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3164     },
3165     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
3166       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
3167       .type = ARM_CP_IO, .access = PL0_RW,
3168       .accessfn = gt_ptimer_access,
3169       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
3170       .resetvalue = 0,
3171       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3172       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3173     },
3174     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
3175       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3176       .accessfn = gt_vtimer_access,
3177       .fieldoffset = offsetoflow32(CPUARMState,
3178                                    cp15.c14_timer[GTIMER_VIRT].ctl),
3179       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3180       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3181     },
3182     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
3183       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
3184       .type = ARM_CP_IO, .access = PL0_RW,
3185       .accessfn = gt_vtimer_access,
3186       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
3187       .resetvalue = 0,
3188       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3189       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3190     },
3191     /* TimerValue views: a 32 bit downcounting view of the underlying state */
3192     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3193       .secure = ARM_CP_SECSTATE_NS,
3194       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3195       .accessfn = gt_ptimer_access,
3196       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3197     },
3198     { .name = "CNTP_TVAL_S",
3199       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3200       .secure = ARM_CP_SECSTATE_S,
3201       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3202       .accessfn = gt_ptimer_access,
3203       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
3204     },
3205     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3206       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
3207       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3208       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
3209       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3210     },
3211     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
3212       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3213       .accessfn = gt_vtimer_access,
3214       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3215     },
3216     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3217       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
3218       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3219       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
3220       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3221     },
3222     /* The counter itself */
3223     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
3224       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3225       .accessfn = gt_pct_access,
3226       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
3227     },
3228     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
3229       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
3230       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3231       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
3232     },
3233     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3234       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3235       .accessfn = gt_vct_access,
3236       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3237     },
3238     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3239       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3240       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3241       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3242     },
3243     /* Comparison value, indicating when the timer goes off */
3244     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3245       .secure = ARM_CP_SECSTATE_NS,
3246       .access = PL0_RW,
3247       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3248       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3249       .accessfn = gt_ptimer_access,
3250       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3251       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3252     },
3253     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3254       .secure = ARM_CP_SECSTATE_S,
3255       .access = PL0_RW,
3256       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3257       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3258       .accessfn = gt_ptimer_access,
3259       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3260     },
3261     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3262       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3263       .access = PL0_RW,
3264       .type = ARM_CP_IO,
3265       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3266       .resetvalue = 0, .accessfn = gt_ptimer_access,
3267       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3268       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3269     },
3270     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3271       .access = PL0_RW,
3272       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3273       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3274       .accessfn = gt_vtimer_access,
3275       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3276       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3277     },
3278     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3279       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3280       .access = PL0_RW,
3281       .type = ARM_CP_IO,
3282       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3283       .resetvalue = 0, .accessfn = gt_vtimer_access,
3284       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3285       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3286     },
3287     /* Secure timer -- this is actually restricted to only EL3
3288      * and configurably Secure-EL1 via the accessfn.
3289      */
3290     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3291       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3292       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3293       .accessfn = gt_stimer_access,
3294       .readfn = gt_sec_tval_read,
3295       .writefn = gt_sec_tval_write,
3296       .resetfn = gt_sec_timer_reset,
3297     },
3298     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3299       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3300       .type = ARM_CP_IO, .access = PL1_RW,
3301       .accessfn = gt_stimer_access,
3302       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3303       .resetvalue = 0,
3304       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3305     },
3306     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3307       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3308       .type = ARM_CP_IO, .access = PL1_RW,
3309       .accessfn = gt_stimer_access,
3310       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3311       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3312     },
3313     REGINFO_SENTINEL
3314 };
3315 
3316 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3317                                  bool isread)
3318 {
3319     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3320         return CP_ACCESS_TRAP;
3321     }
3322     return CP_ACCESS_OK;
3323 }
3324 
3325 #else
3326 
3327 /* In user-mode most of the generic timer registers are inaccessible
3328  * however modern kernels (4.12+) allow access to cntvct_el0
3329  */
3330 
3331 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3332 {
3333     ARMCPU *cpu = env_archcpu(env);
3334 
3335     /* Currently we have no support for QEMUTimer in linux-user so we
3336      * can't call gt_get_countervalue(env), instead we directly
3337      * call the lower level functions.
3338      */
3339     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3340 }
3341 
3342 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3343     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3344       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3345       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3346       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3347       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3348     },
3349     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3350       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3351       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3352       .readfn = gt_virt_cnt_read,
3353     },
3354     REGINFO_SENTINEL
3355 };
3356 
3357 #endif
3358 
3359 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3360 {
3361     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3362         raw_write(env, ri, value);
3363     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3364         raw_write(env, ri, value & 0xfffff6ff);
3365     } else {
3366         raw_write(env, ri, value & 0xfffff1ff);
3367     }
3368 }
3369 
3370 #ifndef CONFIG_USER_ONLY
3371 /* get_phys_addr() isn't present for user-mode-only targets */
3372 
3373 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3374                                  bool isread)
3375 {
3376     if (ri->opc2 & 4) {
3377         /* The ATS12NSO* operations must trap to EL3 if executed in
3378          * Secure EL1 (which can only happen if EL3 is AArch64).
3379          * They are simply UNDEF if executed from NS EL1.
3380          * They function normally from EL2 or EL3.
3381          */
3382         if (arm_current_el(env) == 1) {
3383             if (arm_is_secure_below_el3(env)) {
3384                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3385             }
3386             return CP_ACCESS_TRAP_UNCATEGORIZED;
3387         }
3388     }
3389     return CP_ACCESS_OK;
3390 }
3391 
3392 #ifdef CONFIG_TCG
3393 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3394                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3395 {
3396     hwaddr phys_addr;
3397     target_ulong page_size;
3398     int prot;
3399     bool ret;
3400     uint64_t par64;
3401     bool format64 = false;
3402     MemTxAttrs attrs = {};
3403     ARMMMUFaultInfo fi = {};
3404     ARMCacheAttrs cacheattrs = {};
3405 
3406     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3407                         &prot, &page_size, &fi, &cacheattrs);
3408 
3409     if (ret) {
3410         /*
3411          * Some kinds of translation fault must cause exceptions rather
3412          * than being reported in the PAR.
3413          */
3414         int current_el = arm_current_el(env);
3415         int target_el;
3416         uint32_t syn, fsr, fsc;
3417         bool take_exc = false;
3418 
3419         if (fi.s1ptw && current_el == 1 && !arm_is_secure(env)
3420             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3421             /*
3422              * Synchronous stage 2 fault on an access made as part of the
3423              * translation table walk for AT S1E0* or AT S1E1* insn
3424              * executed from NS EL1. If this is a synchronous external abort
3425              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3426              * to EL3. Otherwise the fault is taken as an exception to EL2,
3427              * and HPFAR_EL2 holds the faulting IPA.
3428              */
3429             if (fi.type == ARMFault_SyncExternalOnWalk &&
3430                 (env->cp15.scr_el3 & SCR_EA)) {
3431                 target_el = 3;
3432             } else {
3433                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3434                 target_el = 2;
3435             }
3436             take_exc = true;
3437         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3438             /*
3439              * Synchronous external aborts during a translation table walk
3440              * are taken as Data Abort exceptions.
3441              */
3442             if (fi.stage2) {
3443                 if (current_el == 3) {
3444                     target_el = 3;
3445                 } else {
3446                     target_el = 2;
3447                 }
3448             } else {
3449                 target_el = exception_target_el(env);
3450             }
3451             take_exc = true;
3452         }
3453 
3454         if (take_exc) {
3455             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3456             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3457                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3458                 fsr = arm_fi_to_lfsc(&fi);
3459                 fsc = extract32(fsr, 0, 6);
3460             } else {
3461                 fsr = arm_fi_to_sfsc(&fi);
3462                 fsc = 0x3f;
3463             }
3464             /*
3465              * Report exception with ESR indicating a fault due to a
3466              * translation table walk for a cache maintenance instruction.
3467              */
3468             syn = syn_data_abort_no_iss(current_el == target_el,
3469                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3470             env->exception.vaddress = value;
3471             env->exception.fsr = fsr;
3472             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3473         }
3474     }
3475 
3476     if (is_a64(env)) {
3477         format64 = true;
3478     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3479         /*
3480          * ATS1Cxx:
3481          * * TTBCR.EAE determines whether the result is returned using the
3482          *   32-bit or the 64-bit PAR format
3483          * * Instructions executed in Hyp mode always use the 64bit format
3484          *
3485          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3486          * * The Non-secure TTBCR.EAE bit is set to 1
3487          * * The implementation includes EL2, and the value of HCR.VM is 1
3488          *
3489          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3490          *
3491          * ATS1Hx always uses the 64bit format.
3492          */
3493         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3494 
3495         if (arm_feature(env, ARM_FEATURE_EL2)) {
3496             if (mmu_idx == ARMMMUIdx_E10_0 ||
3497                 mmu_idx == ARMMMUIdx_E10_1 ||
3498                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3499                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3500             } else {
3501                 format64 |= arm_current_el(env) == 2;
3502             }
3503         }
3504     }
3505 
3506     if (format64) {
3507         /* Create a 64-bit PAR */
3508         par64 = (1 << 11); /* LPAE bit always set */
3509         if (!ret) {
3510             par64 |= phys_addr & ~0xfffULL;
3511             if (!attrs.secure) {
3512                 par64 |= (1 << 9); /* NS */
3513             }
3514             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3515             par64 |= cacheattrs.shareability << 7; /* SH */
3516         } else {
3517             uint32_t fsr = arm_fi_to_lfsc(&fi);
3518 
3519             par64 |= 1; /* F */
3520             par64 |= (fsr & 0x3f) << 1; /* FS */
3521             if (fi.stage2) {
3522                 par64 |= (1 << 9); /* S */
3523             }
3524             if (fi.s1ptw) {
3525                 par64 |= (1 << 8); /* PTW */
3526             }
3527         }
3528     } else {
3529         /* fsr is a DFSR/IFSR value for the short descriptor
3530          * translation table format (with WnR always clear).
3531          * Convert it to a 32-bit PAR.
3532          */
3533         if (!ret) {
3534             /* We do not set any attribute bits in the PAR */
3535             if (page_size == (1 << 24)
3536                 && arm_feature(env, ARM_FEATURE_V7)) {
3537                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3538             } else {
3539                 par64 = phys_addr & 0xfffff000;
3540             }
3541             if (!attrs.secure) {
3542                 par64 |= (1 << 9); /* NS */
3543             }
3544         } else {
3545             uint32_t fsr = arm_fi_to_sfsc(&fi);
3546 
3547             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3548                     ((fsr & 0xf) << 1) | 1;
3549         }
3550     }
3551     return par64;
3552 }
3553 #endif /* CONFIG_TCG */
3554 
3555 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3556 {
3557 #ifdef CONFIG_TCG
3558     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3559     uint64_t par64;
3560     ARMMMUIdx mmu_idx;
3561     int el = arm_current_el(env);
3562     bool secure = arm_is_secure_below_el3(env);
3563 
3564     switch (ri->opc2 & 6) {
3565     case 0:
3566         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3567         switch (el) {
3568         case 3:
3569             mmu_idx = ARMMMUIdx_SE3;
3570             break;
3571         case 2:
3572             g_assert(!secure);  /* TODO: ARMv8.4-SecEL2 */
3573             /* fall through */
3574         case 1:
3575             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3576                 mmu_idx = (secure ? ARMMMUIdx_SE10_1_PAN
3577                            : ARMMMUIdx_Stage1_E1_PAN);
3578             } else {
3579                 mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_Stage1_E1;
3580             }
3581             break;
3582         default:
3583             g_assert_not_reached();
3584         }
3585         break;
3586     case 2:
3587         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3588         switch (el) {
3589         case 3:
3590             mmu_idx = ARMMMUIdx_SE10_0;
3591             break;
3592         case 2:
3593             mmu_idx = ARMMMUIdx_Stage1_E0;
3594             break;
3595         case 1:
3596             mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_Stage1_E0;
3597             break;
3598         default:
3599             g_assert_not_reached();
3600         }
3601         break;
3602     case 4:
3603         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3604         mmu_idx = ARMMMUIdx_E10_1;
3605         break;
3606     case 6:
3607         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3608         mmu_idx = ARMMMUIdx_E10_0;
3609         break;
3610     default:
3611         g_assert_not_reached();
3612     }
3613 
3614     par64 = do_ats_write(env, value, access_type, mmu_idx);
3615 
3616     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3617 #else
3618     /* Handled by hardware accelerator. */
3619     g_assert_not_reached();
3620 #endif /* CONFIG_TCG */
3621 }
3622 
3623 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3624                         uint64_t value)
3625 {
3626 #ifdef CONFIG_TCG
3627     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3628     uint64_t par64;
3629 
3630     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3631 
3632     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3633 #else
3634     /* Handled by hardware accelerator. */
3635     g_assert_not_reached();
3636 #endif /* CONFIG_TCG */
3637 }
3638 
3639 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3640                                      bool isread)
3641 {
3642     if (arm_current_el(env) == 3 && !(env->cp15.scr_el3 & SCR_NS)) {
3643         return CP_ACCESS_TRAP;
3644     }
3645     return CP_ACCESS_OK;
3646 }
3647 
3648 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3649                         uint64_t value)
3650 {
3651 #ifdef CONFIG_TCG
3652     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3653     ARMMMUIdx mmu_idx;
3654     int secure = arm_is_secure_below_el3(env);
3655 
3656     switch (ri->opc2 & 6) {
3657     case 0:
3658         switch (ri->opc1) {
3659         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3660             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3661                 mmu_idx = (secure ? ARMMMUIdx_SE10_1_PAN
3662                            : ARMMMUIdx_Stage1_E1_PAN);
3663             } else {
3664                 mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_Stage1_E1;
3665             }
3666             break;
3667         case 4: /* AT S1E2R, AT S1E2W */
3668             mmu_idx = ARMMMUIdx_E2;
3669             break;
3670         case 6: /* AT S1E3R, AT S1E3W */
3671             mmu_idx = ARMMMUIdx_SE3;
3672             break;
3673         default:
3674             g_assert_not_reached();
3675         }
3676         break;
3677     case 2: /* AT S1E0R, AT S1E0W */
3678         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_Stage1_E0;
3679         break;
3680     case 4: /* AT S12E1R, AT S12E1W */
3681         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3682         break;
3683     case 6: /* AT S12E0R, AT S12E0W */
3684         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3685         break;
3686     default:
3687         g_assert_not_reached();
3688     }
3689 
3690     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3691 #else
3692     /* Handled by hardware accelerator. */
3693     g_assert_not_reached();
3694 #endif /* CONFIG_TCG */
3695 }
3696 #endif
3697 
3698 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3699     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3700       .access = PL1_RW, .resetvalue = 0,
3701       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3702                              offsetoflow32(CPUARMState, cp15.par_ns) },
3703       .writefn = par_write },
3704 #ifndef CONFIG_USER_ONLY
3705     /* This underdecoding is safe because the reginfo is NO_RAW. */
3706     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3707       .access = PL1_W, .accessfn = ats_access,
3708       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3709 #endif
3710     REGINFO_SENTINEL
3711 };
3712 
3713 /* Return basic MPU access permission bits.  */
3714 static uint32_t simple_mpu_ap_bits(uint32_t val)
3715 {
3716     uint32_t ret;
3717     uint32_t mask;
3718     int i;
3719     ret = 0;
3720     mask = 3;
3721     for (i = 0; i < 16; i += 2) {
3722         ret |= (val >> i) & mask;
3723         mask <<= 2;
3724     }
3725     return ret;
3726 }
3727 
3728 /* Pad basic MPU access permission bits to extended format.  */
3729 static uint32_t extended_mpu_ap_bits(uint32_t val)
3730 {
3731     uint32_t ret;
3732     uint32_t mask;
3733     int i;
3734     ret = 0;
3735     mask = 3;
3736     for (i = 0; i < 16; i += 2) {
3737         ret |= (val & mask) << i;
3738         mask <<= 2;
3739     }
3740     return ret;
3741 }
3742 
3743 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3744                                  uint64_t value)
3745 {
3746     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3747 }
3748 
3749 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3750 {
3751     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3752 }
3753 
3754 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3755                                  uint64_t value)
3756 {
3757     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3758 }
3759 
3760 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3761 {
3762     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3763 }
3764 
3765 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3766 {
3767     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3768 
3769     if (!u32p) {
3770         return 0;
3771     }
3772 
3773     u32p += env->pmsav7.rnr[M_REG_NS];
3774     return *u32p;
3775 }
3776 
3777 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3778                          uint64_t value)
3779 {
3780     ARMCPU *cpu = env_archcpu(env);
3781     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3782 
3783     if (!u32p) {
3784         return;
3785     }
3786 
3787     u32p += env->pmsav7.rnr[M_REG_NS];
3788     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3789     *u32p = value;
3790 }
3791 
3792 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3793                               uint64_t value)
3794 {
3795     ARMCPU *cpu = env_archcpu(env);
3796     uint32_t nrgs = cpu->pmsav7_dregion;
3797 
3798     if (value >= nrgs) {
3799         qemu_log_mask(LOG_GUEST_ERROR,
3800                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3801                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3802         return;
3803     }
3804 
3805     raw_write(env, ri, value);
3806 }
3807 
3808 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3809     /* Reset for all these registers is handled in arm_cpu_reset(),
3810      * because the PMSAv7 is also used by M-profile CPUs, which do
3811      * not register cpregs but still need the state to be reset.
3812      */
3813     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3814       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3815       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3816       .readfn = pmsav7_read, .writefn = pmsav7_write,
3817       .resetfn = arm_cp_reset_ignore },
3818     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3819       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3820       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3821       .readfn = pmsav7_read, .writefn = pmsav7_write,
3822       .resetfn = arm_cp_reset_ignore },
3823     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3824       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3825       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3826       .readfn = pmsav7_read, .writefn = pmsav7_write,
3827       .resetfn = arm_cp_reset_ignore },
3828     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3829       .access = PL1_RW,
3830       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3831       .writefn = pmsav7_rgnr_write,
3832       .resetfn = arm_cp_reset_ignore },
3833     REGINFO_SENTINEL
3834 };
3835 
3836 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3837     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3838       .access = PL1_RW, .type = ARM_CP_ALIAS,
3839       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3840       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3841     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3842       .access = PL1_RW, .type = ARM_CP_ALIAS,
3843       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3844       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3845     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3846       .access = PL1_RW,
3847       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3848       .resetvalue = 0, },
3849     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3850       .access = PL1_RW,
3851       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3852       .resetvalue = 0, },
3853     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3854       .access = PL1_RW,
3855       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3856     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3857       .access = PL1_RW,
3858       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3859     /* Protection region base and size registers */
3860     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3861       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3862       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3863     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3864       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3865       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3866     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3867       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3868       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3869     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3870       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3871       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3872     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3873       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3874       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3875     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3876       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3877       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3878     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3879       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3880       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3881     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3882       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3883       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3884     REGINFO_SENTINEL
3885 };
3886 
3887 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3888                                  uint64_t value)
3889 {
3890     TCR *tcr = raw_ptr(env, ri);
3891     int maskshift = extract32(value, 0, 3);
3892 
3893     if (!arm_feature(env, ARM_FEATURE_V8)) {
3894         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3895             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3896              * using Long-desciptor translation table format */
3897             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3898         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3899             /* In an implementation that includes the Security Extensions
3900              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3901              * Short-descriptor translation table format.
3902              */
3903             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3904         } else {
3905             value &= TTBCR_N;
3906         }
3907     }
3908 
3909     /* Update the masks corresponding to the TCR bank being written
3910      * Note that we always calculate mask and base_mask, but
3911      * they are only used for short-descriptor tables (ie if EAE is 0);
3912      * for long-descriptor tables the TCR fields are used differently
3913      * and the mask and base_mask values are meaningless.
3914      */
3915     tcr->raw_tcr = value;
3916     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3917     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3918 }
3919 
3920 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3921                              uint64_t value)
3922 {
3923     ARMCPU *cpu = env_archcpu(env);
3924     TCR *tcr = raw_ptr(env, ri);
3925 
3926     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3927         /* With LPAE the TTBCR could result in a change of ASID
3928          * via the TTBCR.A1 bit, so do a TLB flush.
3929          */
3930         tlb_flush(CPU(cpu));
3931     }
3932     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3933     value = deposit64(tcr->raw_tcr, 0, 32, value);
3934     vmsa_ttbcr_raw_write(env, ri, value);
3935 }
3936 
3937 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3938 {
3939     TCR *tcr = raw_ptr(env, ri);
3940 
3941     /* Reset both the TCR as well as the masks corresponding to the bank of
3942      * the TCR being reset.
3943      */
3944     tcr->raw_tcr = 0;
3945     tcr->mask = 0;
3946     tcr->base_mask = 0xffffc000u;
3947 }
3948 
3949 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3950                                uint64_t value)
3951 {
3952     ARMCPU *cpu = env_archcpu(env);
3953     TCR *tcr = raw_ptr(env, ri);
3954 
3955     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3956     tlb_flush(CPU(cpu));
3957     tcr->raw_tcr = value;
3958 }
3959 
3960 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3961                             uint64_t value)
3962 {
3963     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3964     if (cpreg_field_is_64bit(ri) &&
3965         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3966         ARMCPU *cpu = env_archcpu(env);
3967         tlb_flush(CPU(cpu));
3968     }
3969     raw_write(env, ri, value);
3970 }
3971 
3972 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3973                                     uint64_t value)
3974 {
3975     /*
3976      * If we are running with E2&0 regime, then an ASID is active.
3977      * Flush if that might be changing.  Note we're not checking
3978      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
3979      * holds the active ASID, only checking the field that might.
3980      */
3981     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
3982         (arm_hcr_el2_eff(env) & HCR_E2H)) {
3983         tlb_flush_by_mmuidx(env_cpu(env),
3984                             ARMMMUIdxBit_E20_2 |
3985                             ARMMMUIdxBit_E20_2_PAN |
3986                             ARMMMUIdxBit_E20_0);
3987     }
3988     raw_write(env, ri, value);
3989 }
3990 
3991 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3992                         uint64_t value)
3993 {
3994     ARMCPU *cpu = env_archcpu(env);
3995     CPUState *cs = CPU(cpu);
3996 
3997     /*
3998      * A change in VMID to the stage2 page table (Stage2) invalidates
3999      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
4000      */
4001     if (raw_read(env, ri) != value) {
4002         tlb_flush_by_mmuidx(cs,
4003                             ARMMMUIdxBit_E10_1 |
4004                             ARMMMUIdxBit_E10_1_PAN |
4005                             ARMMMUIdxBit_E10_0);
4006         raw_write(env, ri, value);
4007     }
4008 }
4009 
4010 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
4011     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
4012       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
4013       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
4014                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
4015     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
4016       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4017       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
4018                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
4019     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
4020       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4021       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
4022                              offsetof(CPUARMState, cp15.dfar_ns) } },
4023     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
4024       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
4025       .access = PL1_RW, .accessfn = access_tvm_trvm,
4026       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
4027       .resetvalue = 0, },
4028     REGINFO_SENTINEL
4029 };
4030 
4031 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
4032     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
4033       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
4034       .access = PL1_RW, .accessfn = access_tvm_trvm,
4035       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
4036     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
4037       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
4038       .access = PL1_RW, .accessfn = access_tvm_trvm,
4039       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4040       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4041                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
4042     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
4043       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
4044       .access = PL1_RW, .accessfn = access_tvm_trvm,
4045       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4046       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4047                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
4048     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
4049       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4050       .access = PL1_RW, .accessfn = access_tvm_trvm,
4051       .writefn = vmsa_tcr_el12_write,
4052       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
4053       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
4054     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4055       .access = PL1_RW, .accessfn = access_tvm_trvm,
4056       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
4057       .raw_writefn = vmsa_ttbcr_raw_write,
4058       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
4059                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
4060     REGINFO_SENTINEL
4061 };
4062 
4063 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
4064  * qemu tlbs nor adjusting cached masks.
4065  */
4066 static const ARMCPRegInfo ttbcr2_reginfo = {
4067     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
4068     .access = PL1_RW, .accessfn = access_tvm_trvm,
4069     .type = ARM_CP_ALIAS,
4070     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
4071                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
4072 };
4073 
4074 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
4075                                 uint64_t value)
4076 {
4077     env->cp15.c15_ticonfig = value & 0xe7;
4078     /* The OS_TYPE bit in this register changes the reported CPUID! */
4079     env->cp15.c0_cpuid = (value & (1 << 5)) ?
4080         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
4081 }
4082 
4083 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
4084                                 uint64_t value)
4085 {
4086     env->cp15.c15_threadid = value & 0xffff;
4087 }
4088 
4089 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
4090                            uint64_t value)
4091 {
4092     /* Wait-for-interrupt (deprecated) */
4093     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
4094 }
4095 
4096 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
4097                                   uint64_t value)
4098 {
4099     /* On OMAP there are registers indicating the max/min index of dcache lines
4100      * containing a dirty line; cache flush operations have to reset these.
4101      */
4102     env->cp15.c15_i_max = 0x000;
4103     env->cp15.c15_i_min = 0xff0;
4104 }
4105 
4106 static const ARMCPRegInfo omap_cp_reginfo[] = {
4107     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
4108       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
4109       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
4110       .resetvalue = 0, },
4111     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
4112       .access = PL1_RW, .type = ARM_CP_NOP },
4113     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
4114       .access = PL1_RW,
4115       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
4116       .writefn = omap_ticonfig_write },
4117     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
4118       .access = PL1_RW,
4119       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
4120     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
4121       .access = PL1_RW, .resetvalue = 0xff0,
4122       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
4123     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
4124       .access = PL1_RW,
4125       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
4126       .writefn = omap_threadid_write },
4127     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
4128       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4129       .type = ARM_CP_NO_RAW,
4130       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
4131     /* TODO: Peripheral port remap register:
4132      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
4133      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
4134      * when MMU is off.
4135      */
4136     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
4137       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
4138       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
4139       .writefn = omap_cachemaint_write },
4140     { .name = "C9", .cp = 15, .crn = 9,
4141       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
4142       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
4143     REGINFO_SENTINEL
4144 };
4145 
4146 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4147                               uint64_t value)
4148 {
4149     env->cp15.c15_cpar = value & 0x3fff;
4150 }
4151 
4152 static const ARMCPRegInfo xscale_cp_reginfo[] = {
4153     { .name = "XSCALE_CPAR",
4154       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4155       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
4156       .writefn = xscale_cpar_write, },
4157     { .name = "XSCALE_AUXCR",
4158       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
4159       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
4160       .resetvalue = 0, },
4161     /* XScale specific cache-lockdown: since we have no cache we NOP these
4162      * and hope the guest does not really rely on cache behaviour.
4163      */
4164     { .name = "XSCALE_LOCK_ICACHE_LINE",
4165       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
4166       .access = PL1_W, .type = ARM_CP_NOP },
4167     { .name = "XSCALE_UNLOCK_ICACHE",
4168       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
4169       .access = PL1_W, .type = ARM_CP_NOP },
4170     { .name = "XSCALE_DCACHE_LOCK",
4171       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
4172       .access = PL1_RW, .type = ARM_CP_NOP },
4173     { .name = "XSCALE_UNLOCK_DCACHE",
4174       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
4175       .access = PL1_W, .type = ARM_CP_NOP },
4176     REGINFO_SENTINEL
4177 };
4178 
4179 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
4180     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
4181      * implementation of this implementation-defined space.
4182      * Ideally this should eventually disappear in favour of actually
4183      * implementing the correct behaviour for all cores.
4184      */
4185     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
4186       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4187       .access = PL1_RW,
4188       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
4189       .resetvalue = 0 },
4190     REGINFO_SENTINEL
4191 };
4192 
4193 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
4194     /* Cache status: RAZ because we have no cache so it's always clean */
4195     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
4196       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4197       .resetvalue = 0 },
4198     REGINFO_SENTINEL
4199 };
4200 
4201 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
4202     /* We never have a a block transfer operation in progress */
4203     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
4204       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4205       .resetvalue = 0 },
4206     /* The cache ops themselves: these all NOP for QEMU */
4207     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
4208       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4209     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
4210       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4211     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
4212       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4213     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4214       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4215     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4216       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4217     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4218       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4219     REGINFO_SENTINEL
4220 };
4221 
4222 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4223     /* The cache test-and-clean instructions always return (1 << 30)
4224      * to indicate that there are no dirty cache lines.
4225      */
4226     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4227       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4228       .resetvalue = (1 << 30) },
4229     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4230       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4231       .resetvalue = (1 << 30) },
4232     REGINFO_SENTINEL
4233 };
4234 
4235 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4236     /* Ignore ReadBuffer accesses */
4237     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4238       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4239       .access = PL1_RW, .resetvalue = 0,
4240       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4241     REGINFO_SENTINEL
4242 };
4243 
4244 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4245 {
4246     ARMCPU *cpu = env_archcpu(env);
4247     unsigned int cur_el = arm_current_el(env);
4248     bool secure = arm_is_secure(env);
4249 
4250     if (arm_feature(&cpu->env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
4251         return env->cp15.vpidr_el2;
4252     }
4253     return raw_read(env, ri);
4254 }
4255 
4256 static uint64_t mpidr_read_val(CPUARMState *env)
4257 {
4258     ARMCPU *cpu = env_archcpu(env);
4259     uint64_t mpidr = cpu->mp_affinity;
4260 
4261     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4262         mpidr |= (1U << 31);
4263         /* Cores which are uniprocessor (non-coherent)
4264          * but still implement the MP extensions set
4265          * bit 30. (For instance, Cortex-R5).
4266          */
4267         if (cpu->mp_is_up) {
4268             mpidr |= (1u << 30);
4269         }
4270     }
4271     return mpidr;
4272 }
4273 
4274 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4275 {
4276     unsigned int cur_el = arm_current_el(env);
4277     bool secure = arm_is_secure(env);
4278 
4279     if (arm_feature(env, ARM_FEATURE_EL2) && !secure && cur_el == 1) {
4280         return env->cp15.vmpidr_el2;
4281     }
4282     return mpidr_read_val(env);
4283 }
4284 
4285 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4286     /* NOP AMAIR0/1 */
4287     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4288       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4289       .access = PL1_RW, .accessfn = access_tvm_trvm,
4290       .type = ARM_CP_CONST, .resetvalue = 0 },
4291     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4292     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4293       .access = PL1_RW, .accessfn = access_tvm_trvm,
4294       .type = ARM_CP_CONST, .resetvalue = 0 },
4295     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4296       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4297       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4298                              offsetof(CPUARMState, cp15.par_ns)} },
4299     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4300       .access = PL1_RW, .accessfn = access_tvm_trvm,
4301       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4302       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4303                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4304       .writefn = vmsa_ttbr_write, },
4305     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4306       .access = PL1_RW, .accessfn = access_tvm_trvm,
4307       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4308       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4309                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4310       .writefn = vmsa_ttbr_write, },
4311     REGINFO_SENTINEL
4312 };
4313 
4314 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4315 {
4316     return vfp_get_fpcr(env);
4317 }
4318 
4319 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4320                             uint64_t value)
4321 {
4322     vfp_set_fpcr(env, value);
4323 }
4324 
4325 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4326 {
4327     return vfp_get_fpsr(env);
4328 }
4329 
4330 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4331                             uint64_t value)
4332 {
4333     vfp_set_fpsr(env, value);
4334 }
4335 
4336 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4337                                        bool isread)
4338 {
4339     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4340         return CP_ACCESS_TRAP;
4341     }
4342     return CP_ACCESS_OK;
4343 }
4344 
4345 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4346                             uint64_t value)
4347 {
4348     env->daif = value & PSTATE_DAIF;
4349 }
4350 
4351 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4352 {
4353     return env->pstate & PSTATE_PAN;
4354 }
4355 
4356 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4357                            uint64_t value)
4358 {
4359     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4360 }
4361 
4362 static const ARMCPRegInfo pan_reginfo = {
4363     .name = "PAN", .state = ARM_CP_STATE_AA64,
4364     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4365     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4366     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4367 };
4368 
4369 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4370 {
4371     return env->pstate & PSTATE_UAO;
4372 }
4373 
4374 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4375                            uint64_t value)
4376 {
4377     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4378 }
4379 
4380 static const ARMCPRegInfo uao_reginfo = {
4381     .name = "UAO", .state = ARM_CP_STATE_AA64,
4382     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4383     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4384     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4385 };
4386 
4387 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4388                                               const ARMCPRegInfo *ri,
4389                                               bool isread)
4390 {
4391     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4392     switch (arm_current_el(env)) {
4393     case 0:
4394         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4395         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4396             return CP_ACCESS_TRAP;
4397         }
4398         /* fall through */
4399     case 1:
4400         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4401         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4402             return CP_ACCESS_TRAP_EL2;
4403         }
4404         break;
4405     }
4406     return CP_ACCESS_OK;
4407 }
4408 
4409 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4410                                               const ARMCPRegInfo *ri,
4411                                               bool isread)
4412 {
4413     /* Cache invalidate/clean to Point of Unification... */
4414     switch (arm_current_el(env)) {
4415     case 0:
4416         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4417         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4418             return CP_ACCESS_TRAP;
4419         }
4420         /* fall through */
4421     case 1:
4422         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4423         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4424             return CP_ACCESS_TRAP_EL2;
4425         }
4426         break;
4427     }
4428     return CP_ACCESS_OK;
4429 }
4430 
4431 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4432  * Page D4-1736 (DDI0487A.b)
4433  */
4434 
4435 static int vae1_tlbmask(CPUARMState *env)
4436 {
4437     /* Since we exclude secure first, we may read HCR_EL2 directly. */
4438     if (arm_is_secure_below_el3(env)) {
4439         return ARMMMUIdxBit_SE10_1 |
4440                ARMMMUIdxBit_SE10_1_PAN |
4441                ARMMMUIdxBit_SE10_0;
4442     } else if ((env->cp15.hcr_el2 & (HCR_E2H | HCR_TGE))
4443                == (HCR_E2H | HCR_TGE)) {
4444         return ARMMMUIdxBit_E20_2 |
4445                ARMMMUIdxBit_E20_2_PAN |
4446                ARMMMUIdxBit_E20_0;
4447     } else {
4448         return ARMMMUIdxBit_E10_1 |
4449                ARMMMUIdxBit_E10_1_PAN |
4450                ARMMMUIdxBit_E10_0;
4451     }
4452 }
4453 
4454 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4455                                       uint64_t value)
4456 {
4457     CPUState *cs = env_cpu(env);
4458     int mask = vae1_tlbmask(env);
4459 
4460     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4461 }
4462 
4463 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4464                                     uint64_t value)
4465 {
4466     CPUState *cs = env_cpu(env);
4467     int mask = vae1_tlbmask(env);
4468 
4469     if (tlb_force_broadcast(env)) {
4470         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4471     } else {
4472         tlb_flush_by_mmuidx(cs, mask);
4473     }
4474 }
4475 
4476 static int alle1_tlbmask(CPUARMState *env)
4477 {
4478     /*
4479      * Note that the 'ALL' scope must invalidate both stage 1 and
4480      * stage 2 translations, whereas most other scopes only invalidate
4481      * stage 1 translations.
4482      */
4483     if (arm_is_secure_below_el3(env)) {
4484         return ARMMMUIdxBit_SE10_1 |
4485                ARMMMUIdxBit_SE10_1_PAN |
4486                ARMMMUIdxBit_SE10_0;
4487     } else {
4488         return ARMMMUIdxBit_E10_1 |
4489                ARMMMUIdxBit_E10_1_PAN |
4490                ARMMMUIdxBit_E10_0;
4491     }
4492 }
4493 
4494 static int e2_tlbmask(CPUARMState *env)
4495 {
4496     /* TODO: ARMv8.4-SecEL2 */
4497     return ARMMMUIdxBit_E20_0 |
4498            ARMMMUIdxBit_E20_2 |
4499            ARMMMUIdxBit_E20_2_PAN |
4500            ARMMMUIdxBit_E2;
4501 }
4502 
4503 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4504                                   uint64_t value)
4505 {
4506     CPUState *cs = env_cpu(env);
4507     int mask = alle1_tlbmask(env);
4508 
4509     tlb_flush_by_mmuidx(cs, mask);
4510 }
4511 
4512 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4513                                   uint64_t value)
4514 {
4515     CPUState *cs = env_cpu(env);
4516     int mask = e2_tlbmask(env);
4517 
4518     tlb_flush_by_mmuidx(cs, mask);
4519 }
4520 
4521 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4522                                   uint64_t value)
4523 {
4524     ARMCPU *cpu = env_archcpu(env);
4525     CPUState *cs = CPU(cpu);
4526 
4527     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4528 }
4529 
4530 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4531                                     uint64_t value)
4532 {
4533     CPUState *cs = env_cpu(env);
4534     int mask = alle1_tlbmask(env);
4535 
4536     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4537 }
4538 
4539 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4540                                     uint64_t value)
4541 {
4542     CPUState *cs = env_cpu(env);
4543     int mask = e2_tlbmask(env);
4544 
4545     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4546 }
4547 
4548 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4549                                     uint64_t value)
4550 {
4551     CPUState *cs = env_cpu(env);
4552 
4553     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4554 }
4555 
4556 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4557                                  uint64_t value)
4558 {
4559     /* Invalidate by VA, EL2
4560      * Currently handles both VAE2 and VALE2, since we don't support
4561      * flush-last-level-only.
4562      */
4563     CPUState *cs = env_cpu(env);
4564     int mask = e2_tlbmask(env);
4565     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4566 
4567     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4568 }
4569 
4570 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4571                                  uint64_t value)
4572 {
4573     /* Invalidate by VA, EL3
4574      * Currently handles both VAE3 and VALE3, since we don't support
4575      * flush-last-level-only.
4576      */
4577     ARMCPU *cpu = env_archcpu(env);
4578     CPUState *cs = CPU(cpu);
4579     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4580 
4581     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4582 }
4583 
4584 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4585                                    uint64_t value)
4586 {
4587     CPUState *cs = env_cpu(env);
4588     int mask = vae1_tlbmask(env);
4589     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4590 
4591     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr, mask);
4592 }
4593 
4594 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4595                                  uint64_t value)
4596 {
4597     /* Invalidate by VA, EL1&0 (AArch64 version).
4598      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4599      * since we don't support flush-for-specific-ASID-only or
4600      * flush-last-level-only.
4601      */
4602     CPUState *cs = env_cpu(env);
4603     int mask = vae1_tlbmask(env);
4604     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4605 
4606     if (tlb_force_broadcast(env)) {
4607         tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr, mask);
4608     } else {
4609         tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4610     }
4611 }
4612 
4613 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4614                                    uint64_t value)
4615 {
4616     CPUState *cs = env_cpu(env);
4617     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4618 
4619     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4620                                              ARMMMUIdxBit_E2);
4621 }
4622 
4623 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4624                                    uint64_t value)
4625 {
4626     CPUState *cs = env_cpu(env);
4627     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4628 
4629     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
4630                                              ARMMMUIdxBit_SE3);
4631 }
4632 
4633 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4634                                       bool isread)
4635 {
4636     int cur_el = arm_current_el(env);
4637 
4638     if (cur_el < 2) {
4639         uint64_t hcr = arm_hcr_el2_eff(env);
4640 
4641         if (cur_el == 0) {
4642             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4643                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4644                     return CP_ACCESS_TRAP_EL2;
4645                 }
4646             } else {
4647                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4648                     return CP_ACCESS_TRAP;
4649                 }
4650                 if (hcr & HCR_TDZ) {
4651                     return CP_ACCESS_TRAP_EL2;
4652                 }
4653             }
4654         } else if (hcr & HCR_TDZ) {
4655             return CP_ACCESS_TRAP_EL2;
4656         }
4657     }
4658     return CP_ACCESS_OK;
4659 }
4660 
4661 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4662 {
4663     ARMCPU *cpu = env_archcpu(env);
4664     int dzp_bit = 1 << 4;
4665 
4666     /* DZP indicates whether DC ZVA access is allowed */
4667     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4668         dzp_bit = 0;
4669     }
4670     return cpu->dcz_blocksize | dzp_bit;
4671 }
4672 
4673 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4674                                     bool isread)
4675 {
4676     if (!(env->pstate & PSTATE_SP)) {
4677         /* Access to SP_EL0 is undefined if it's being used as
4678          * the stack pointer.
4679          */
4680         return CP_ACCESS_TRAP_UNCATEGORIZED;
4681     }
4682     return CP_ACCESS_OK;
4683 }
4684 
4685 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4686 {
4687     return env->pstate & PSTATE_SP;
4688 }
4689 
4690 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4691 {
4692     update_spsel(env, val);
4693 }
4694 
4695 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4696                         uint64_t value)
4697 {
4698     ARMCPU *cpu = env_archcpu(env);
4699 
4700     if (raw_read(env, ri) == value) {
4701         /* Skip the TLB flush if nothing actually changed; Linux likes
4702          * to do a lot of pointless SCTLR writes.
4703          */
4704         return;
4705     }
4706 
4707     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4708         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4709         value &= ~SCTLR_M;
4710     }
4711 
4712     raw_write(env, ri, value);
4713     /* ??? Lots of these bits are not implemented.  */
4714     /* This may enable/disable the MMU, so do a TLB flush.  */
4715     tlb_flush(CPU(cpu));
4716 
4717     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4718         /*
4719          * Normally we would always end the TB on an SCTLR write; see the
4720          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4721          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4722          * of hflags from the translator, so do it here.
4723          */
4724         arm_rebuild_hflags(env);
4725     }
4726 }
4727 
4728 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4729                                      bool isread)
4730 {
4731     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4732         return CP_ACCESS_TRAP_FP_EL2;
4733     }
4734     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4735         return CP_ACCESS_TRAP_FP_EL3;
4736     }
4737     return CP_ACCESS_OK;
4738 }
4739 
4740 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4741                        uint64_t value)
4742 {
4743     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4744 }
4745 
4746 static const ARMCPRegInfo v8_cp_reginfo[] = {
4747     /* Minimal set of EL0-visible registers. This will need to be expanded
4748      * significantly for system emulation of AArch64 CPUs.
4749      */
4750     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4751       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4752       .access = PL0_RW, .type = ARM_CP_NZCV },
4753     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4754       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4755       .type = ARM_CP_NO_RAW,
4756       .access = PL0_RW, .accessfn = aa64_daif_access,
4757       .fieldoffset = offsetof(CPUARMState, daif),
4758       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4759     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4760       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4761       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4762       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4763     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4764       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4765       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4766       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4767     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4768       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4769       .access = PL0_R, .type = ARM_CP_NO_RAW,
4770       .readfn = aa64_dczid_read },
4771     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4772       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4773       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4774 #ifndef CONFIG_USER_ONLY
4775       /* Avoid overhead of an access check that always passes in user-mode */
4776       .accessfn = aa64_zva_access,
4777 #endif
4778     },
4779     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4780       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4781       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4782     /* Cache ops: all NOPs since we don't emulate caches */
4783     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4784       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4785       .access = PL1_W, .type = ARM_CP_NOP,
4786       .accessfn = aa64_cacheop_pou_access },
4787     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4788       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4789       .access = PL1_W, .type = ARM_CP_NOP,
4790       .accessfn = aa64_cacheop_pou_access },
4791     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4792       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4793       .access = PL0_W, .type = ARM_CP_NOP,
4794       .accessfn = aa64_cacheop_pou_access },
4795     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4796       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4797       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4798       .type = ARM_CP_NOP },
4799     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4800       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4801       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4802     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4803       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4804       .access = PL0_W, .type = ARM_CP_NOP,
4805       .accessfn = aa64_cacheop_poc_access },
4806     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4807       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4808       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4809     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4810       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4811       .access = PL0_W, .type = ARM_CP_NOP,
4812       .accessfn = aa64_cacheop_pou_access },
4813     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4814       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4815       .access = PL0_W, .type = ARM_CP_NOP,
4816       .accessfn = aa64_cacheop_poc_access },
4817     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4818       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4819       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4820     /* TLBI operations */
4821     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4822       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4823       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4824       .writefn = tlbi_aa64_vmalle1is_write },
4825     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4826       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4827       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4828       .writefn = tlbi_aa64_vae1is_write },
4829     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4830       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4831       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4832       .writefn = tlbi_aa64_vmalle1is_write },
4833     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4834       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4835       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4836       .writefn = tlbi_aa64_vae1is_write },
4837     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4838       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4839       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4840       .writefn = tlbi_aa64_vae1is_write },
4841     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4842       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4843       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4844       .writefn = tlbi_aa64_vae1is_write },
4845     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4846       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4847       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4848       .writefn = tlbi_aa64_vmalle1_write },
4849     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4850       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4851       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4852       .writefn = tlbi_aa64_vae1_write },
4853     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4854       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4855       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4856       .writefn = tlbi_aa64_vmalle1_write },
4857     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4858       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4859       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4860       .writefn = tlbi_aa64_vae1_write },
4861     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4862       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4863       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4864       .writefn = tlbi_aa64_vae1_write },
4865     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4866       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4867       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4868       .writefn = tlbi_aa64_vae1_write },
4869     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4870       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4871       .access = PL2_W, .type = ARM_CP_NOP },
4872     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4873       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4874       .access = PL2_W, .type = ARM_CP_NOP },
4875     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4876       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4877       .access = PL2_W, .type = ARM_CP_NO_RAW,
4878       .writefn = tlbi_aa64_alle1is_write },
4879     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4880       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4881       .access = PL2_W, .type = ARM_CP_NO_RAW,
4882       .writefn = tlbi_aa64_alle1is_write },
4883     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4884       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4885       .access = PL2_W, .type = ARM_CP_NOP },
4886     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4887       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4888       .access = PL2_W, .type = ARM_CP_NOP },
4889     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4890       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4891       .access = PL2_W, .type = ARM_CP_NO_RAW,
4892       .writefn = tlbi_aa64_alle1_write },
4893     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4894       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4895       .access = PL2_W, .type = ARM_CP_NO_RAW,
4896       .writefn = tlbi_aa64_alle1is_write },
4897 #ifndef CONFIG_USER_ONLY
4898     /* 64 bit address translation operations */
4899     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4900       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4901       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4902       .writefn = ats_write64 },
4903     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4904       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4905       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4906       .writefn = ats_write64 },
4907     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4908       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
4909       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4910       .writefn = ats_write64 },
4911     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
4912       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
4913       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4914       .writefn = ats_write64 },
4915     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
4916       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
4917       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4918       .writefn = ats_write64 },
4919     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
4920       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
4921       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4922       .writefn = ats_write64 },
4923     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
4924       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
4925       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4926       .writefn = ats_write64 },
4927     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
4928       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
4929       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4930       .writefn = ats_write64 },
4931     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
4932     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
4933       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
4934       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4935       .writefn = ats_write64 },
4936     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
4937       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
4938       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4939       .writefn = ats_write64 },
4940     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
4941       .type = ARM_CP_ALIAS,
4942       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
4943       .access = PL1_RW, .resetvalue = 0,
4944       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
4945       .writefn = par_write },
4946 #endif
4947     /* TLB invalidate last level of translation table walk */
4948     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4949       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4950       .writefn = tlbimva_is_write },
4951     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4952       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4953       .writefn = tlbimvaa_is_write },
4954     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4955       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4956       .writefn = tlbimva_write },
4957     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4958       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
4959       .writefn = tlbimvaa_write },
4960     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
4961       .type = ARM_CP_NO_RAW, .access = PL2_W,
4962       .writefn = tlbimva_hyp_write },
4963     { .name = "TLBIMVALHIS",
4964       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
4965       .type = ARM_CP_NO_RAW, .access = PL2_W,
4966       .writefn = tlbimva_hyp_is_write },
4967     { .name = "TLBIIPAS2",
4968       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4969       .type = ARM_CP_NOP, .access = PL2_W },
4970     { .name = "TLBIIPAS2IS",
4971       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4972       .type = ARM_CP_NOP, .access = PL2_W },
4973     { .name = "TLBIIPAS2L",
4974       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4975       .type = ARM_CP_NOP, .access = PL2_W },
4976     { .name = "TLBIIPAS2LIS",
4977       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4978       .type = ARM_CP_NOP, .access = PL2_W },
4979     /* 32 bit cache operations */
4980     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4981       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
4982     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
4983       .type = ARM_CP_NOP, .access = PL1_W },
4984     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4985       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
4986     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
4987       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
4988     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
4989       .type = ARM_CP_NOP, .access = PL1_W },
4990     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
4991       .type = ARM_CP_NOP, .access = PL1_W },
4992     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4993       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
4994     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4995       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
4996     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
4997       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
4998     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4999       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5000     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5001       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5002     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5003       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5004     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5005       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5006     /* MMU Domain access control / MPU write buffer control */
5007     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5008       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5009       .writefn = dacr_write, .raw_writefn = raw_write,
5010       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5011                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5012     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5013       .type = ARM_CP_ALIAS,
5014       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5015       .access = PL1_RW,
5016       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5017     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5018       .type = ARM_CP_ALIAS,
5019       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5020       .access = PL1_RW,
5021       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5022     /* We rely on the access checks not allowing the guest to write to the
5023      * state field when SPSel indicates that it's being used as the stack
5024      * pointer.
5025      */
5026     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5027       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5028       .access = PL1_RW, .accessfn = sp_el0_access,
5029       .type = ARM_CP_ALIAS,
5030       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5031     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5032       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5033       .access = PL2_RW, .type = ARM_CP_ALIAS,
5034       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5035     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5036       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5037       .type = ARM_CP_NO_RAW,
5038       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5039     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5040       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5041       .type = ARM_CP_ALIAS,
5042       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
5043       .access = PL2_RW, .accessfn = fpexc32_access },
5044     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5045       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5046       .access = PL2_RW, .resetvalue = 0,
5047       .writefn = dacr_write, .raw_writefn = raw_write,
5048       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5049     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5050       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5051       .access = PL2_RW, .resetvalue = 0,
5052       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5053     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5054       .type = ARM_CP_ALIAS,
5055       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5056       .access = PL2_RW,
5057       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5058     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5059       .type = ARM_CP_ALIAS,
5060       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5061       .access = PL2_RW,
5062       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5063     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5064       .type = ARM_CP_ALIAS,
5065       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5066       .access = PL2_RW,
5067       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5068     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5069       .type = ARM_CP_ALIAS,
5070       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5071       .access = PL2_RW,
5072       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5073     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5074       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5075       .resetvalue = 0,
5076       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5077     { .name = "SDCR", .type = ARM_CP_ALIAS,
5078       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5079       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5080       .writefn = sdcr_write,
5081       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5082     REGINFO_SENTINEL
5083 };
5084 
5085 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
5086 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
5087     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5088       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5089       .access = PL2_RW,
5090       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
5091     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
5092       .type = ARM_CP_NO_RAW,
5093       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5094       .access = PL2_RW,
5095       .type = ARM_CP_CONST, .resetvalue = 0 },
5096     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5097       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5098       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5099     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5100       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5101       .access = PL2_RW,
5102       .type = ARM_CP_CONST, .resetvalue = 0 },
5103     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5104       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5105       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5106     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5107       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5108       .access = PL2_RW, .type = ARM_CP_CONST,
5109       .resetvalue = 0 },
5110     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5111       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5112       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5113     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5114       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5115       .access = PL2_RW, .type = ARM_CP_CONST,
5116       .resetvalue = 0 },
5117     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5118       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5119       .access = PL2_RW, .type = ARM_CP_CONST,
5120       .resetvalue = 0 },
5121     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5122       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5123       .access = PL2_RW, .type = ARM_CP_CONST,
5124       .resetvalue = 0 },
5125     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5126       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5127       .access = PL2_RW, .type = ARM_CP_CONST,
5128       .resetvalue = 0 },
5129     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5130       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5131       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5132     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
5133       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5134       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5135       .type = ARM_CP_CONST, .resetvalue = 0 },
5136     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5137       .cp = 15, .opc1 = 6, .crm = 2,
5138       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5139       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
5140     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5141       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5142       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5143     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5144       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5145       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5146     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5147       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5148       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5149     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5150       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5151       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5152     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5153       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5154       .resetvalue = 0 },
5155     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5156       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5157       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5158     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5159       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5160       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5161     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5162       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5163       .resetvalue = 0 },
5164     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5165       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5166       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5167     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5168       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5169       .resetvalue = 0 },
5170     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5171       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5172       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5173     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5174       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5175       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5176     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5177       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5178       .access = PL2_RW, .accessfn = access_tda,
5179       .type = ARM_CP_CONST, .resetvalue = 0 },
5180     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
5181       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5182       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5183       .type = ARM_CP_CONST, .resetvalue = 0 },
5184     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5185       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5186       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5187     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5188       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5189       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5190     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5191       .type = ARM_CP_CONST,
5192       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5193       .access = PL2_RW, .resetvalue = 0 },
5194     REGINFO_SENTINEL
5195 };
5196 
5197 /* Ditto, but for registers which exist in ARMv8 but not v7 */
5198 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
5199     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5200       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5201       .access = PL2_RW,
5202       .type = ARM_CP_CONST, .resetvalue = 0 },
5203     REGINFO_SENTINEL
5204 };
5205 
5206 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5207 {
5208     ARMCPU *cpu = env_archcpu(env);
5209 
5210     if (arm_feature(env, ARM_FEATURE_V8)) {
5211         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5212     } else {
5213         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5214     }
5215 
5216     if (arm_feature(env, ARM_FEATURE_EL3)) {
5217         valid_mask &= ~HCR_HCD;
5218     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5219         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5220          * However, if we're using the SMC PSCI conduit then QEMU is
5221          * effectively acting like EL3 firmware and so the guest at
5222          * EL2 should retain the ability to prevent EL1 from being
5223          * able to make SMC calls into the ersatz firmware, so in
5224          * that case HCR.TSC should be read/write.
5225          */
5226         valid_mask &= ~HCR_TSC;
5227     }
5228 
5229     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5230         if (cpu_isar_feature(aa64_vh, cpu)) {
5231             valid_mask |= HCR_E2H;
5232         }
5233         if (cpu_isar_feature(aa64_lor, cpu)) {
5234             valid_mask |= HCR_TLOR;
5235         }
5236         if (cpu_isar_feature(aa64_pauth, cpu)) {
5237             valid_mask |= HCR_API | HCR_APK;
5238         }
5239     }
5240 
5241     /* Clear RES0 bits.  */
5242     value &= valid_mask;
5243 
5244     /* These bits change the MMU setup:
5245      * HCR_VM enables stage 2 translation
5246      * HCR_PTW forbids certain page-table setups
5247      * HCR_DC Disables stage1 and enables stage2 translation
5248      */
5249     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC)) {
5250         tlb_flush(CPU(cpu));
5251     }
5252     env->cp15.hcr_el2 = value;
5253 
5254     /*
5255      * Updates to VI and VF require us to update the status of
5256      * virtual interrupts, which are the logical OR of these bits
5257      * and the state of the input lines from the GIC. (This requires
5258      * that we have the iothread lock, which is done by marking the
5259      * reginfo structs as ARM_CP_IO.)
5260      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5261      * possible for it to be taken immediately, because VIRQ and
5262      * VFIQ are masked unless running at EL0 or EL1, and HCR
5263      * can only be written at EL2.
5264      */
5265     g_assert(qemu_mutex_iothread_locked());
5266     arm_cpu_update_virq(cpu);
5267     arm_cpu_update_vfiq(cpu);
5268 }
5269 
5270 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5271 {
5272     do_hcr_write(env, value, 0);
5273 }
5274 
5275 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5276                           uint64_t value)
5277 {
5278     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5279     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5280     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5281 }
5282 
5283 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5284                          uint64_t value)
5285 {
5286     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5287     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5288     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5289 }
5290 
5291 /*
5292  * Return the effective value of HCR_EL2.
5293  * Bits that are not included here:
5294  * RW       (read from SCR_EL3.RW as needed)
5295  */
5296 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5297 {
5298     uint64_t ret = env->cp15.hcr_el2;
5299 
5300     if (arm_is_secure_below_el3(env)) {
5301         /*
5302          * "This register has no effect if EL2 is not enabled in the
5303          * current Security state".  This is ARMv8.4-SecEL2 speak for
5304          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5305          *
5306          * Prior to that, the language was "In an implementation that
5307          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5308          * as if this field is 0 for all purposes other than a direct
5309          * read or write access of HCR_EL2".  With lots of enumeration
5310          * on a per-field basis.  In current QEMU, this is condition
5311          * is arm_is_secure_below_el3.
5312          *
5313          * Since the v8.4 language applies to the entire register, and
5314          * appears to be backward compatible, use that.
5315          */
5316         return 0;
5317     }
5318 
5319     /*
5320      * For a cpu that supports both aarch64 and aarch32, we can set bits
5321      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5322      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5323      */
5324     if (!arm_el_is_aa64(env, 2)) {
5325         uint64_t aa32_valid;
5326 
5327         /*
5328          * These bits are up-to-date as of ARMv8.6.
5329          * For HCR, it's easiest to list just the 2 bits that are invalid.
5330          * For HCR2, list those that are valid.
5331          */
5332         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5333         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5334                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5335         ret &= aa32_valid;
5336     }
5337 
5338     if (ret & HCR_TGE) {
5339         /* These bits are up-to-date as of ARMv8.6.  */
5340         if (ret & HCR_E2H) {
5341             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5342                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5343                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5344                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5345                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5346                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5347         } else {
5348             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5349         }
5350         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5351                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5352                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5353                  HCR_TLOR);
5354     }
5355 
5356     return ret;
5357 }
5358 
5359 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5360                            uint64_t value)
5361 {
5362     /*
5363      * For A-profile AArch32 EL3, if NSACR.CP10
5364      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5365      */
5366     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5367         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5368         value &= ~(0x3 << 10);
5369         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5370     }
5371     env->cp15.cptr_el[2] = value;
5372 }
5373 
5374 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5375 {
5376     /*
5377      * For A-profile AArch32 EL3, if NSACR.CP10
5378      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5379      */
5380     uint64_t value = env->cp15.cptr_el[2];
5381 
5382     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5383         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5384         value |= 0x3 << 10;
5385     }
5386     return value;
5387 }
5388 
5389 static const ARMCPRegInfo el2_cp_reginfo[] = {
5390     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5391       .type = ARM_CP_IO,
5392       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5393       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5394       .writefn = hcr_write },
5395     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5396       .type = ARM_CP_ALIAS | ARM_CP_IO,
5397       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5398       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5399       .writefn = hcr_writelow },
5400     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5401       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5402       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5403     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5404       .type = ARM_CP_ALIAS,
5405       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5406       .access = PL2_RW,
5407       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5408     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5409       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5410       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5411     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5412       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5413       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5414     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5415       .type = ARM_CP_ALIAS,
5416       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5417       .access = PL2_RW,
5418       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5419     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5420       .type = ARM_CP_ALIAS,
5421       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5422       .access = PL2_RW,
5423       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5424     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5425       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5426       .access = PL2_RW, .writefn = vbar_write,
5427       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5428       .resetvalue = 0 },
5429     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5430       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5431       .access = PL3_RW, .type = ARM_CP_ALIAS,
5432       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5433     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5434       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5435       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5436       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5437       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5438     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5439       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5440       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5441       .resetvalue = 0 },
5442     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5443       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5444       .access = PL2_RW, .type = ARM_CP_ALIAS,
5445       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5446     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5447       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5448       .access = PL2_RW, .type = ARM_CP_CONST,
5449       .resetvalue = 0 },
5450     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5451     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5452       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5453       .access = PL2_RW, .type = ARM_CP_CONST,
5454       .resetvalue = 0 },
5455     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5456       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5457       .access = PL2_RW, .type = ARM_CP_CONST,
5458       .resetvalue = 0 },
5459     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5460       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5461       .access = PL2_RW, .type = ARM_CP_CONST,
5462       .resetvalue = 0 },
5463     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5464       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5465       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5466       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5467       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5468     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5469       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5470       .type = ARM_CP_ALIAS,
5471       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5472       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5473     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5474       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5475       .access = PL2_RW,
5476       /* no .writefn needed as this can't cause an ASID change;
5477        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5478        */
5479       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5480     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5481       .cp = 15, .opc1 = 6, .crm = 2,
5482       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5483       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5484       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5485       .writefn = vttbr_write },
5486     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5487       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5488       .access = PL2_RW, .writefn = vttbr_write,
5489       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5490     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5491       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5492       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5493       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5494     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5495       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5496       .access = PL2_RW, .resetvalue = 0,
5497       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5498     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5499       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5500       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5501       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5502     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5503       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5504       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5505     { .name = "TLBIALLNSNH",
5506       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5507       .type = ARM_CP_NO_RAW, .access = PL2_W,
5508       .writefn = tlbiall_nsnh_write },
5509     { .name = "TLBIALLNSNHIS",
5510       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5511       .type = ARM_CP_NO_RAW, .access = PL2_W,
5512       .writefn = tlbiall_nsnh_is_write },
5513     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5514       .type = ARM_CP_NO_RAW, .access = PL2_W,
5515       .writefn = tlbiall_hyp_write },
5516     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5517       .type = ARM_CP_NO_RAW, .access = PL2_W,
5518       .writefn = tlbiall_hyp_is_write },
5519     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5520       .type = ARM_CP_NO_RAW, .access = PL2_W,
5521       .writefn = tlbimva_hyp_write },
5522     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5523       .type = ARM_CP_NO_RAW, .access = PL2_W,
5524       .writefn = tlbimva_hyp_is_write },
5525     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5526       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5527       .type = ARM_CP_NO_RAW, .access = PL2_W,
5528       .writefn = tlbi_aa64_alle2_write },
5529     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5530       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5531       .type = ARM_CP_NO_RAW, .access = PL2_W,
5532       .writefn = tlbi_aa64_vae2_write },
5533     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5534       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5535       .access = PL2_W, .type = ARM_CP_NO_RAW,
5536       .writefn = tlbi_aa64_vae2_write },
5537     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5538       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5539       .access = PL2_W, .type = ARM_CP_NO_RAW,
5540       .writefn = tlbi_aa64_alle2is_write },
5541     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5542       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5543       .type = ARM_CP_NO_RAW, .access = PL2_W,
5544       .writefn = tlbi_aa64_vae2is_write },
5545     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5546       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5547       .access = PL2_W, .type = ARM_CP_NO_RAW,
5548       .writefn = tlbi_aa64_vae2is_write },
5549 #ifndef CONFIG_USER_ONLY
5550     /* Unlike the other EL2-related AT operations, these must
5551      * UNDEF from EL3 if EL2 is not implemented, which is why we
5552      * define them here rather than with the rest of the AT ops.
5553      */
5554     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5555       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5556       .access = PL2_W, .accessfn = at_s1e2_access,
5557       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5558     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5559       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5560       .access = PL2_W, .accessfn = at_s1e2_access,
5561       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5562     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5563      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5564      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5565      * to behave as if SCR.NS was 1.
5566      */
5567     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5568       .access = PL2_W,
5569       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5570     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5571       .access = PL2_W,
5572       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5573     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5574       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5575       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5576        * reset values as IMPDEF. We choose to reset to 3 to comply with
5577        * both ARMv7 and ARMv8.
5578        */
5579       .access = PL2_RW, .resetvalue = 3,
5580       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5581     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5582       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5583       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5584       .writefn = gt_cntvoff_write,
5585       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5586     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5587       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5588       .writefn = gt_cntvoff_write,
5589       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5590     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5591       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5592       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5593       .type = ARM_CP_IO, .access = PL2_RW,
5594       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5595     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5596       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5597       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5598       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5599     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5600       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5601       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5602       .resetfn = gt_hyp_timer_reset,
5603       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5604     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5605       .type = ARM_CP_IO,
5606       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5607       .access = PL2_RW,
5608       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5609       .resetvalue = 0,
5610       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5611 #endif
5612     /* The only field of MDCR_EL2 that has a defined architectural reset value
5613      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
5614      * don't implement any PMU event counters, so using zero as a reset
5615      * value for MDCR_EL2 is okay
5616      */
5617     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5618       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5619       .access = PL2_RW, .resetvalue = 0,
5620       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5621     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5622       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5623       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5624       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5625     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5626       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5627       .access = PL2_RW,
5628       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5629     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5630       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5631       .access = PL2_RW,
5632       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5633     REGINFO_SENTINEL
5634 };
5635 
5636 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5637     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5638       .type = ARM_CP_ALIAS | ARM_CP_IO,
5639       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5640       .access = PL2_RW,
5641       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5642       .writefn = hcr_writehigh },
5643     REGINFO_SENTINEL
5644 };
5645 
5646 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5647                                    bool isread)
5648 {
5649     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5650      * At Secure EL1 it traps to EL3.
5651      */
5652     if (arm_current_el(env) == 3) {
5653         return CP_ACCESS_OK;
5654     }
5655     if (arm_is_secure_below_el3(env)) {
5656         return CP_ACCESS_TRAP_EL3;
5657     }
5658     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5659     if (isread) {
5660         return CP_ACCESS_OK;
5661     }
5662     return CP_ACCESS_TRAP_UNCATEGORIZED;
5663 }
5664 
5665 static const ARMCPRegInfo el3_cp_reginfo[] = {
5666     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5667       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5668       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5669       .resetvalue = 0, .writefn = scr_write },
5670     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5671       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5672       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5673       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5674       .writefn = scr_write },
5675     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5676       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5677       .access = PL3_RW, .resetvalue = 0,
5678       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5679     { .name = "SDER",
5680       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5681       .access = PL3_RW, .resetvalue = 0,
5682       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5683     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5684       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5685       .writefn = vbar_write, .resetvalue = 0,
5686       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5687     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5688       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5689       .access = PL3_RW, .resetvalue = 0,
5690       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5691     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5692       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5693       .access = PL3_RW,
5694       /* no .writefn needed as this can't cause an ASID change;
5695        * we must provide a .raw_writefn and .resetfn because we handle
5696        * reset and migration for the AArch32 TTBCR(S), which might be
5697        * using mask and base_mask.
5698        */
5699       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5700       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5701     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5702       .type = ARM_CP_ALIAS,
5703       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5704       .access = PL3_RW,
5705       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5706     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5707       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5708       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5709     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5710       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5711       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5712     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5713       .type = ARM_CP_ALIAS,
5714       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5715       .access = PL3_RW,
5716       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5717     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5718       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5719       .access = PL3_RW, .writefn = vbar_write,
5720       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5721       .resetvalue = 0 },
5722     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5723       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5724       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5725       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5726     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5727       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5728       .access = PL3_RW, .resetvalue = 0,
5729       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5730     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5731       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5732       .access = PL3_RW, .type = ARM_CP_CONST,
5733       .resetvalue = 0 },
5734     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5735       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5736       .access = PL3_RW, .type = ARM_CP_CONST,
5737       .resetvalue = 0 },
5738     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5739       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5740       .access = PL3_RW, .type = ARM_CP_CONST,
5741       .resetvalue = 0 },
5742     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5743       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5744       .access = PL3_W, .type = ARM_CP_NO_RAW,
5745       .writefn = tlbi_aa64_alle3is_write },
5746     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5747       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5748       .access = PL3_W, .type = ARM_CP_NO_RAW,
5749       .writefn = tlbi_aa64_vae3is_write },
5750     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5751       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5752       .access = PL3_W, .type = ARM_CP_NO_RAW,
5753       .writefn = tlbi_aa64_vae3is_write },
5754     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5755       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5756       .access = PL3_W, .type = ARM_CP_NO_RAW,
5757       .writefn = tlbi_aa64_alle3_write },
5758     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5759       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5760       .access = PL3_W, .type = ARM_CP_NO_RAW,
5761       .writefn = tlbi_aa64_vae3_write },
5762     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5763       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5764       .access = PL3_W, .type = ARM_CP_NO_RAW,
5765       .writefn = tlbi_aa64_vae3_write },
5766     REGINFO_SENTINEL
5767 };
5768 
5769 #ifndef CONFIG_USER_ONLY
5770 /* Test if system register redirection is to occur in the current state.  */
5771 static bool redirect_for_e2h(CPUARMState *env)
5772 {
5773     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5774 }
5775 
5776 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5777 {
5778     CPReadFn *readfn;
5779 
5780     if (redirect_for_e2h(env)) {
5781         /* Switch to the saved EL2 version of the register.  */
5782         ri = ri->opaque;
5783         readfn = ri->readfn;
5784     } else {
5785         readfn = ri->orig_readfn;
5786     }
5787     if (readfn == NULL) {
5788         readfn = raw_read;
5789     }
5790     return readfn(env, ri);
5791 }
5792 
5793 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5794                           uint64_t value)
5795 {
5796     CPWriteFn *writefn;
5797 
5798     if (redirect_for_e2h(env)) {
5799         /* Switch to the saved EL2 version of the register.  */
5800         ri = ri->opaque;
5801         writefn = ri->writefn;
5802     } else {
5803         writefn = ri->orig_writefn;
5804     }
5805     if (writefn == NULL) {
5806         writefn = raw_write;
5807     }
5808     writefn(env, ri, value);
5809 }
5810 
5811 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5812 {
5813     struct E2HAlias {
5814         uint32_t src_key, dst_key, new_key;
5815         const char *src_name, *dst_name, *new_name;
5816         bool (*feature)(const ARMISARegisters *id);
5817     };
5818 
5819 #define K(op0, op1, crn, crm, op2) \
5820     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5821 
5822     static const struct E2HAlias aliases[] = {
5823         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5824           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5825         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5826           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5827         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5828           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5829         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5830           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5831         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5832           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5833         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5834           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5835         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5836           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5837         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5838           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5839         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5840           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5841         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5842           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5843         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5844           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5845         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5846           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5847         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5848           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5849         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5850           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5851         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
5852           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
5853         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
5854           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
5855 
5856         /*
5857          * Note that redirection of ZCR is mentioned in the description
5858          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
5859          * not in the summary table.
5860          */
5861         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
5862           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
5863 
5864         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
5865         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
5866     };
5867 #undef K
5868 
5869     size_t i;
5870 
5871     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
5872         const struct E2HAlias *a = &aliases[i];
5873         ARMCPRegInfo *src_reg, *dst_reg;
5874 
5875         if (a->feature && !a->feature(&cpu->isar)) {
5876             continue;
5877         }
5878 
5879         src_reg = g_hash_table_lookup(cpu->cp_regs, &a->src_key);
5880         dst_reg = g_hash_table_lookup(cpu->cp_regs, &a->dst_key);
5881         g_assert(src_reg != NULL);
5882         g_assert(dst_reg != NULL);
5883 
5884         /* Cross-compare names to detect typos in the keys.  */
5885         g_assert(strcmp(src_reg->name, a->src_name) == 0);
5886         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
5887 
5888         /* None of the core system registers use opaque; we will.  */
5889         g_assert(src_reg->opaque == NULL);
5890 
5891         /* Create alias before redirection so we dup the right data. */
5892         if (a->new_key) {
5893             ARMCPRegInfo *new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
5894             uint32_t *new_key = g_memdup(&a->new_key, sizeof(uint32_t));
5895             bool ok;
5896 
5897             new_reg->name = a->new_name;
5898             new_reg->type |= ARM_CP_ALIAS;
5899             /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
5900             new_reg->access &= PL2_RW | PL3_RW;
5901 
5902             ok = g_hash_table_insert(cpu->cp_regs, new_key, new_reg);
5903             g_assert(ok);
5904         }
5905 
5906         src_reg->opaque = dst_reg;
5907         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
5908         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
5909         if (!src_reg->raw_readfn) {
5910             src_reg->raw_readfn = raw_read;
5911         }
5912         if (!src_reg->raw_writefn) {
5913             src_reg->raw_writefn = raw_write;
5914         }
5915         src_reg->readfn = el2_e2h_read;
5916         src_reg->writefn = el2_e2h_write;
5917     }
5918 }
5919 #endif
5920 
5921 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
5922                                      bool isread)
5923 {
5924     int cur_el = arm_current_el(env);
5925 
5926     if (cur_el < 2) {
5927         uint64_t hcr = arm_hcr_el2_eff(env);
5928 
5929         if (cur_el == 0) {
5930             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
5931                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
5932                     return CP_ACCESS_TRAP_EL2;
5933                 }
5934             } else {
5935                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
5936                     return CP_ACCESS_TRAP;
5937                 }
5938                 if (hcr & HCR_TID2) {
5939                     return CP_ACCESS_TRAP_EL2;
5940                 }
5941             }
5942         } else if (hcr & HCR_TID2) {
5943             return CP_ACCESS_TRAP_EL2;
5944         }
5945     }
5946 
5947     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
5948         return CP_ACCESS_TRAP_EL2;
5949     }
5950 
5951     return CP_ACCESS_OK;
5952 }
5953 
5954 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
5955                         uint64_t value)
5956 {
5957     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
5958      * read via a bit in OSLSR_EL1.
5959      */
5960     int oslock;
5961 
5962     if (ri->state == ARM_CP_STATE_AA32) {
5963         oslock = (value == 0xC5ACCE55);
5964     } else {
5965         oslock = value & 1;
5966     }
5967 
5968     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
5969 }
5970 
5971 static const ARMCPRegInfo debug_cp_reginfo[] = {
5972     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
5973      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
5974      * unlike DBGDRAR it is never accessible from EL0.
5975      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
5976      * accessor.
5977      */
5978     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
5979       .access = PL0_R, .accessfn = access_tdra,
5980       .type = ARM_CP_CONST, .resetvalue = 0 },
5981     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
5982       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
5983       .access = PL1_R, .accessfn = access_tdra,
5984       .type = ARM_CP_CONST, .resetvalue = 0 },
5985     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
5986       .access = PL0_R, .accessfn = access_tdra,
5987       .type = ARM_CP_CONST, .resetvalue = 0 },
5988     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
5989     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
5990       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
5991       .access = PL1_RW, .accessfn = access_tda,
5992       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
5993       .resetvalue = 0 },
5994     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
5995      * We don't implement the configurable EL0 access.
5996      */
5997     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
5998       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
5999       .type = ARM_CP_ALIAS,
6000       .access = PL1_R, .accessfn = access_tda,
6001       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
6002     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
6003       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
6004       .access = PL1_W, .type = ARM_CP_NO_RAW,
6005       .accessfn = access_tdosa,
6006       .writefn = oslar_write },
6007     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
6008       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
6009       .access = PL1_R, .resetvalue = 10,
6010       .accessfn = access_tdosa,
6011       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
6012     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
6013     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
6014       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
6015       .access = PL1_RW, .accessfn = access_tdosa,
6016       .type = ARM_CP_NOP },
6017     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
6018      * implement vector catch debug events yet.
6019      */
6020     { .name = "DBGVCR",
6021       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6022       .access = PL1_RW, .accessfn = access_tda,
6023       .type = ARM_CP_NOP },
6024     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
6025      * to save and restore a 32-bit guest's DBGVCR)
6026      */
6027     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
6028       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
6029       .access = PL2_RW, .accessfn = access_tda,
6030       .type = ARM_CP_NOP },
6031     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6032      * Channel but Linux may try to access this register. The 32-bit
6033      * alias is DBGDCCINT.
6034      */
6035     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6036       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6037       .access = PL1_RW, .accessfn = access_tda,
6038       .type = ARM_CP_NOP },
6039     REGINFO_SENTINEL
6040 };
6041 
6042 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6043     /* 64 bit access versions of the (dummy) debug registers */
6044     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6045       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6046     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6047       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6048     REGINFO_SENTINEL
6049 };
6050 
6051 /* Return the exception level to which exceptions should be taken
6052  * via SVEAccessTrap.  If an exception should be routed through
6053  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6054  * take care of raising that exception.
6055  * C.f. the ARM pseudocode function CheckSVEEnabled.
6056  */
6057 int sve_exception_el(CPUARMState *env, int el)
6058 {
6059 #ifndef CONFIG_USER_ONLY
6060     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6061 
6062     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6063         bool disabled = false;
6064 
6065         /* The CPACR.ZEN controls traps to EL1:
6066          * 0, 2 : trap EL0 and EL1 accesses
6067          * 1    : trap only EL0 accesses
6068          * 3    : trap no accesses
6069          */
6070         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
6071             disabled = true;
6072         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
6073             disabled = el == 0;
6074         }
6075         if (disabled) {
6076             /* route_to_el2 */
6077             return hcr_el2 & HCR_TGE ? 2 : 1;
6078         }
6079 
6080         /* Check CPACR.FPEN.  */
6081         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
6082             disabled = true;
6083         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
6084             disabled = el == 0;
6085         }
6086         if (disabled) {
6087             return 0;
6088         }
6089     }
6090 
6091     /* CPTR_EL2.  Since TZ and TFP are positive,
6092      * they will be zero when EL2 is not present.
6093      */
6094     if (el <= 2 && !arm_is_secure_below_el3(env)) {
6095         if (env->cp15.cptr_el[2] & CPTR_TZ) {
6096             return 2;
6097         }
6098         if (env->cp15.cptr_el[2] & CPTR_TFP) {
6099             return 0;
6100         }
6101     }
6102 
6103     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6104     if (arm_feature(env, ARM_FEATURE_EL3)
6105         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6106         return 3;
6107     }
6108 #endif
6109     return 0;
6110 }
6111 
6112 static uint32_t sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6113 {
6114     uint32_t end_len;
6115 
6116     end_len = start_len &= 0xf;
6117     if (!test_bit(start_len, cpu->sve_vq_map)) {
6118         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6119         assert(end_len < start_len);
6120     }
6121     return end_len;
6122 }
6123 
6124 /*
6125  * Given that SVE is enabled, return the vector length for EL.
6126  */
6127 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6128 {
6129     ARMCPU *cpu = env_archcpu(env);
6130     uint32_t zcr_len = cpu->sve_max_vq - 1;
6131 
6132     if (el <= 1) {
6133         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6134     }
6135     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6136         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6137     }
6138     if (arm_feature(env, ARM_FEATURE_EL3)) {
6139         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6140     }
6141 
6142     return sve_zcr_get_valid_len(cpu, zcr_len);
6143 }
6144 
6145 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6146                       uint64_t value)
6147 {
6148     int cur_el = arm_current_el(env);
6149     int old_len = sve_zcr_len_for_el(env, cur_el);
6150     int new_len;
6151 
6152     /* Bits other than [3:0] are RAZ/WI.  */
6153     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6154     raw_write(env, ri, value & 0xf);
6155 
6156     /*
6157      * Because we arrived here, we know both FP and SVE are enabled;
6158      * otherwise we would have trapped access to the ZCR_ELn register.
6159      */
6160     new_len = sve_zcr_len_for_el(env, cur_el);
6161     if (new_len < old_len) {
6162         aarch64_sve_narrow_vq(env, new_len + 1);
6163     }
6164 }
6165 
6166 static const ARMCPRegInfo zcr_el1_reginfo = {
6167     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6168     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6169     .access = PL1_RW, .type = ARM_CP_SVE,
6170     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6171     .writefn = zcr_write, .raw_writefn = raw_write
6172 };
6173 
6174 static const ARMCPRegInfo zcr_el2_reginfo = {
6175     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6176     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6177     .access = PL2_RW, .type = ARM_CP_SVE,
6178     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6179     .writefn = zcr_write, .raw_writefn = raw_write
6180 };
6181 
6182 static const ARMCPRegInfo zcr_no_el2_reginfo = {
6183     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6184     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6185     .access = PL2_RW, .type = ARM_CP_SVE,
6186     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
6187 };
6188 
6189 static const ARMCPRegInfo zcr_el3_reginfo = {
6190     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6191     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6192     .access = PL3_RW, .type = ARM_CP_SVE,
6193     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6194     .writefn = zcr_write, .raw_writefn = raw_write
6195 };
6196 
6197 void hw_watchpoint_update(ARMCPU *cpu, int n)
6198 {
6199     CPUARMState *env = &cpu->env;
6200     vaddr len = 0;
6201     vaddr wvr = env->cp15.dbgwvr[n];
6202     uint64_t wcr = env->cp15.dbgwcr[n];
6203     int mask;
6204     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6205 
6206     if (env->cpu_watchpoint[n]) {
6207         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6208         env->cpu_watchpoint[n] = NULL;
6209     }
6210 
6211     if (!extract64(wcr, 0, 1)) {
6212         /* E bit clear : watchpoint disabled */
6213         return;
6214     }
6215 
6216     switch (extract64(wcr, 3, 2)) {
6217     case 0:
6218         /* LSC 00 is reserved and must behave as if the wp is disabled */
6219         return;
6220     case 1:
6221         flags |= BP_MEM_READ;
6222         break;
6223     case 2:
6224         flags |= BP_MEM_WRITE;
6225         break;
6226     case 3:
6227         flags |= BP_MEM_ACCESS;
6228         break;
6229     }
6230 
6231     /* Attempts to use both MASK and BAS fields simultaneously are
6232      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6233      * thus generating a watchpoint for every byte in the masked region.
6234      */
6235     mask = extract64(wcr, 24, 4);
6236     if (mask == 1 || mask == 2) {
6237         /* Reserved values of MASK; we must act as if the mask value was
6238          * some non-reserved value, or as if the watchpoint were disabled.
6239          * We choose the latter.
6240          */
6241         return;
6242     } else if (mask) {
6243         /* Watchpoint covers an aligned area up to 2GB in size */
6244         len = 1ULL << mask;
6245         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6246          * whether the watchpoint fires when the unmasked bits match; we opt
6247          * to generate the exceptions.
6248          */
6249         wvr &= ~(len - 1);
6250     } else {
6251         /* Watchpoint covers bytes defined by the byte address select bits */
6252         int bas = extract64(wcr, 5, 8);
6253         int basstart;
6254 
6255         if (extract64(wvr, 2, 1)) {
6256             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6257              * ignored, and BAS[3:0] define which bytes to watch.
6258              */
6259             bas &= 0xf;
6260         }
6261 
6262         if (bas == 0) {
6263             /* This must act as if the watchpoint is disabled */
6264             return;
6265         }
6266 
6267         /* The BAS bits are supposed to be programmed to indicate a contiguous
6268          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6269          * we fire for each byte in the word/doubleword addressed by the WVR.
6270          * We choose to ignore any non-zero bits after the first range of 1s.
6271          */
6272         basstart = ctz32(bas);
6273         len = cto32(bas >> basstart);
6274         wvr += basstart;
6275     }
6276 
6277     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6278                           &env->cpu_watchpoint[n]);
6279 }
6280 
6281 void hw_watchpoint_update_all(ARMCPU *cpu)
6282 {
6283     int i;
6284     CPUARMState *env = &cpu->env;
6285 
6286     /* Completely clear out existing QEMU watchpoints and our array, to
6287      * avoid possible stale entries following migration load.
6288      */
6289     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6290     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6291 
6292     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6293         hw_watchpoint_update(cpu, i);
6294     }
6295 }
6296 
6297 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6298                          uint64_t value)
6299 {
6300     ARMCPU *cpu = env_archcpu(env);
6301     int i = ri->crm;
6302 
6303     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
6304      * register reads and behaves as if values written are sign extended.
6305      * Bits [1:0] are RES0.
6306      */
6307     value = sextract64(value, 0, 49) & ~3ULL;
6308 
6309     raw_write(env, ri, value);
6310     hw_watchpoint_update(cpu, i);
6311 }
6312 
6313 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6314                          uint64_t value)
6315 {
6316     ARMCPU *cpu = env_archcpu(env);
6317     int i = ri->crm;
6318 
6319     raw_write(env, ri, value);
6320     hw_watchpoint_update(cpu, i);
6321 }
6322 
6323 void hw_breakpoint_update(ARMCPU *cpu, int n)
6324 {
6325     CPUARMState *env = &cpu->env;
6326     uint64_t bvr = env->cp15.dbgbvr[n];
6327     uint64_t bcr = env->cp15.dbgbcr[n];
6328     vaddr addr;
6329     int bt;
6330     int flags = BP_CPU;
6331 
6332     if (env->cpu_breakpoint[n]) {
6333         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6334         env->cpu_breakpoint[n] = NULL;
6335     }
6336 
6337     if (!extract64(bcr, 0, 1)) {
6338         /* E bit clear : watchpoint disabled */
6339         return;
6340     }
6341 
6342     bt = extract64(bcr, 20, 4);
6343 
6344     switch (bt) {
6345     case 4: /* unlinked address mismatch (reserved if AArch64) */
6346     case 5: /* linked address mismatch (reserved if AArch64) */
6347         qemu_log_mask(LOG_UNIMP,
6348                       "arm: address mismatch breakpoint types not implemented\n");
6349         return;
6350     case 0: /* unlinked address match */
6351     case 1: /* linked address match */
6352     {
6353         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
6354          * we behave as if the register was sign extended. Bits [1:0] are
6355          * RES0. The BAS field is used to allow setting breakpoints on 16
6356          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6357          * a bp will fire if the addresses covered by the bp and the addresses
6358          * covered by the insn overlap but the insn doesn't start at the
6359          * start of the bp address range. We choose to require the insn and
6360          * the bp to have the same address. The constraints on writing to
6361          * BAS enforced in dbgbcr_write mean we have only four cases:
6362          *  0b0000  => no breakpoint
6363          *  0b0011  => breakpoint on addr
6364          *  0b1100  => breakpoint on addr + 2
6365          *  0b1111  => breakpoint on addr
6366          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6367          */
6368         int bas = extract64(bcr, 5, 4);
6369         addr = sextract64(bvr, 0, 49) & ~3ULL;
6370         if (bas == 0) {
6371             return;
6372         }
6373         if (bas == 0xc) {
6374             addr += 2;
6375         }
6376         break;
6377     }
6378     case 2: /* unlinked context ID match */
6379     case 8: /* unlinked VMID match (reserved if no EL2) */
6380     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6381         qemu_log_mask(LOG_UNIMP,
6382                       "arm: unlinked context breakpoint types not implemented\n");
6383         return;
6384     case 9: /* linked VMID match (reserved if no EL2) */
6385     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6386     case 3: /* linked context ID match */
6387     default:
6388         /* We must generate no events for Linked context matches (unless
6389          * they are linked to by some other bp/wp, which is handled in
6390          * updates for the linking bp/wp). We choose to also generate no events
6391          * for reserved values.
6392          */
6393         return;
6394     }
6395 
6396     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6397 }
6398 
6399 void hw_breakpoint_update_all(ARMCPU *cpu)
6400 {
6401     int i;
6402     CPUARMState *env = &cpu->env;
6403 
6404     /* Completely clear out existing QEMU breakpoints and our array, to
6405      * avoid possible stale entries following migration load.
6406      */
6407     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6408     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6409 
6410     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6411         hw_breakpoint_update(cpu, i);
6412     }
6413 }
6414 
6415 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6416                          uint64_t value)
6417 {
6418     ARMCPU *cpu = env_archcpu(env);
6419     int i = ri->crm;
6420 
6421     raw_write(env, ri, value);
6422     hw_breakpoint_update(cpu, i);
6423 }
6424 
6425 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6426                          uint64_t value)
6427 {
6428     ARMCPU *cpu = env_archcpu(env);
6429     int i = ri->crm;
6430 
6431     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6432      * copy of BAS[0].
6433      */
6434     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6435     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6436 
6437     raw_write(env, ri, value);
6438     hw_breakpoint_update(cpu, i);
6439 }
6440 
6441 static void define_debug_regs(ARMCPU *cpu)
6442 {
6443     /* Define v7 and v8 architectural debug registers.
6444      * These are just dummy implementations for now.
6445      */
6446     int i;
6447     int wrps, brps, ctx_cmps;
6448     ARMCPRegInfo dbgdidr = {
6449         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
6450         .access = PL0_R, .accessfn = access_tda,
6451         .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6452     };
6453 
6454     /* Note that all these register fields hold "number of Xs minus 1". */
6455     brps = arm_num_brps(cpu);
6456     wrps = arm_num_wrps(cpu);
6457     ctx_cmps = arm_num_ctx_cmps(cpu);
6458 
6459     assert(ctx_cmps <= brps);
6460 
6461     define_one_arm_cp_reg(cpu, &dbgdidr);
6462     define_arm_cp_regs(cpu, debug_cp_reginfo);
6463 
6464     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6465         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6466     }
6467 
6468     for (i = 0; i < brps; i++) {
6469         ARMCPRegInfo dbgregs[] = {
6470             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6471               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6472               .access = PL1_RW, .accessfn = access_tda,
6473               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6474               .writefn = dbgbvr_write, .raw_writefn = raw_write
6475             },
6476             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6477               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6478               .access = PL1_RW, .accessfn = access_tda,
6479               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6480               .writefn = dbgbcr_write, .raw_writefn = raw_write
6481             },
6482             REGINFO_SENTINEL
6483         };
6484         define_arm_cp_regs(cpu, dbgregs);
6485     }
6486 
6487     for (i = 0; i < wrps; i++) {
6488         ARMCPRegInfo dbgregs[] = {
6489             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6490               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6491               .access = PL1_RW, .accessfn = access_tda,
6492               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6493               .writefn = dbgwvr_write, .raw_writefn = raw_write
6494             },
6495             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6496               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6497               .access = PL1_RW, .accessfn = access_tda,
6498               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6499               .writefn = dbgwcr_write, .raw_writefn = raw_write
6500             },
6501             REGINFO_SENTINEL
6502         };
6503         define_arm_cp_regs(cpu, dbgregs);
6504     }
6505 }
6506 
6507 static void define_pmu_regs(ARMCPU *cpu)
6508 {
6509     /*
6510      * v7 performance monitor control register: same implementor
6511      * field as main ID register, and we implement four counters in
6512      * addition to the cycle count register.
6513      */
6514     unsigned int i, pmcrn = 4;
6515     ARMCPRegInfo pmcr = {
6516         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6517         .access = PL0_RW,
6518         .type = ARM_CP_IO | ARM_CP_ALIAS,
6519         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6520         .accessfn = pmreg_access, .writefn = pmcr_write,
6521         .raw_writefn = raw_write,
6522     };
6523     ARMCPRegInfo pmcr64 = {
6524         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6525         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6526         .access = PL0_RW, .accessfn = pmreg_access,
6527         .type = ARM_CP_IO,
6528         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6529         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6530                       PMCRLC,
6531         .writefn = pmcr_write, .raw_writefn = raw_write,
6532     };
6533     define_one_arm_cp_reg(cpu, &pmcr);
6534     define_one_arm_cp_reg(cpu, &pmcr64);
6535     for (i = 0; i < pmcrn; i++) {
6536         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6537         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6538         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6539         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6540         ARMCPRegInfo pmev_regs[] = {
6541             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6542               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6543               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6544               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6545               .accessfn = pmreg_access },
6546             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6547               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6548               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6549               .type = ARM_CP_IO,
6550               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6551               .raw_readfn = pmevcntr_rawread,
6552               .raw_writefn = pmevcntr_rawwrite },
6553             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6554               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6555               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6556               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6557               .accessfn = pmreg_access },
6558             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6559               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6560               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6561               .type = ARM_CP_IO,
6562               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6563               .raw_writefn = pmevtyper_rawwrite },
6564             REGINFO_SENTINEL
6565         };
6566         define_arm_cp_regs(cpu, pmev_regs);
6567         g_free(pmevcntr_name);
6568         g_free(pmevcntr_el0_name);
6569         g_free(pmevtyper_name);
6570         g_free(pmevtyper_el0_name);
6571     }
6572     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6573         ARMCPRegInfo v81_pmu_regs[] = {
6574             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6575               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6576               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6577               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6578             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6579               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6580               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6581               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6582             REGINFO_SENTINEL
6583         };
6584         define_arm_cp_regs(cpu, v81_pmu_regs);
6585     }
6586     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6587         static const ARMCPRegInfo v84_pmmir = {
6588             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6589             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6590             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6591             .resetvalue = 0
6592         };
6593         define_one_arm_cp_reg(cpu, &v84_pmmir);
6594     }
6595 }
6596 
6597 /* We don't know until after realize whether there's a GICv3
6598  * attached, and that is what registers the gicv3 sysregs.
6599  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6600  * at runtime.
6601  */
6602 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6603 {
6604     ARMCPU *cpu = env_archcpu(env);
6605     uint64_t pfr1 = cpu->id_pfr1;
6606 
6607     if (env->gicv3state) {
6608         pfr1 |= 1 << 28;
6609     }
6610     return pfr1;
6611 }
6612 
6613 #ifndef CONFIG_USER_ONLY
6614 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6615 {
6616     ARMCPU *cpu = env_archcpu(env);
6617     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6618 
6619     if (env->gicv3state) {
6620         pfr0 |= 1 << 24;
6621     }
6622     return pfr0;
6623 }
6624 #endif
6625 
6626 /* Shared logic between LORID and the rest of the LOR* registers.
6627  * Secure state has already been delt with.
6628  */
6629 static CPAccessResult access_lor_ns(CPUARMState *env)
6630 {
6631     int el = arm_current_el(env);
6632 
6633     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6634         return CP_ACCESS_TRAP_EL2;
6635     }
6636     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6637         return CP_ACCESS_TRAP_EL3;
6638     }
6639     return CP_ACCESS_OK;
6640 }
6641 
6642 static CPAccessResult access_lorid(CPUARMState *env, const ARMCPRegInfo *ri,
6643                                    bool isread)
6644 {
6645     if (arm_is_secure_below_el3(env)) {
6646         /* Access ok in secure mode.  */
6647         return CP_ACCESS_OK;
6648     }
6649     return access_lor_ns(env);
6650 }
6651 
6652 static CPAccessResult access_lor_other(CPUARMState *env,
6653                                        const ARMCPRegInfo *ri, bool isread)
6654 {
6655     if (arm_is_secure_below_el3(env)) {
6656         /* Access denied in secure mode.  */
6657         return CP_ACCESS_TRAP;
6658     }
6659     return access_lor_ns(env);
6660 }
6661 
6662 /*
6663  * A trivial implementation of ARMv8.1-LOR leaves all of these
6664  * registers fixed at 0, which indicates that there are zero
6665  * supported Limited Ordering regions.
6666  */
6667 static const ARMCPRegInfo lor_reginfo[] = {
6668     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6669       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6670       .access = PL1_RW, .accessfn = access_lor_other,
6671       .type = ARM_CP_CONST, .resetvalue = 0 },
6672     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6673       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6674       .access = PL1_RW, .accessfn = access_lor_other,
6675       .type = ARM_CP_CONST, .resetvalue = 0 },
6676     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6677       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6678       .access = PL1_RW, .accessfn = access_lor_other,
6679       .type = ARM_CP_CONST, .resetvalue = 0 },
6680     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6681       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6682       .access = PL1_RW, .accessfn = access_lor_other,
6683       .type = ARM_CP_CONST, .resetvalue = 0 },
6684     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6685       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6686       .access = PL1_R, .accessfn = access_lorid,
6687       .type = ARM_CP_CONST, .resetvalue = 0 },
6688     REGINFO_SENTINEL
6689 };
6690 
6691 #ifdef TARGET_AARCH64
6692 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6693                                    bool isread)
6694 {
6695     int el = arm_current_el(env);
6696 
6697     if (el < 2 &&
6698         arm_feature(env, ARM_FEATURE_EL2) &&
6699         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6700         return CP_ACCESS_TRAP_EL2;
6701     }
6702     if (el < 3 &&
6703         arm_feature(env, ARM_FEATURE_EL3) &&
6704         !(env->cp15.scr_el3 & SCR_APK)) {
6705         return CP_ACCESS_TRAP_EL3;
6706     }
6707     return CP_ACCESS_OK;
6708 }
6709 
6710 static const ARMCPRegInfo pauth_reginfo[] = {
6711     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6712       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6713       .access = PL1_RW, .accessfn = access_pauth,
6714       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6715     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6716       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6717       .access = PL1_RW, .accessfn = access_pauth,
6718       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6719     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6720       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6721       .access = PL1_RW, .accessfn = access_pauth,
6722       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6723     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6724       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6725       .access = PL1_RW, .accessfn = access_pauth,
6726       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6727     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6728       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6729       .access = PL1_RW, .accessfn = access_pauth,
6730       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6731     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6732       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6733       .access = PL1_RW, .accessfn = access_pauth,
6734       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6735     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6736       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6737       .access = PL1_RW, .accessfn = access_pauth,
6738       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6739     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6740       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6741       .access = PL1_RW, .accessfn = access_pauth,
6742       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6743     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6744       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6745       .access = PL1_RW, .accessfn = access_pauth,
6746       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6747     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6748       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6749       .access = PL1_RW, .accessfn = access_pauth,
6750       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6751     REGINFO_SENTINEL
6752 };
6753 
6754 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
6755 {
6756     Error *err = NULL;
6757     uint64_t ret;
6758 
6759     /* Success sets NZCV = 0000.  */
6760     env->NF = env->CF = env->VF = 0, env->ZF = 1;
6761 
6762     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
6763         /*
6764          * ??? Failed, for unknown reasons in the crypto subsystem.
6765          * The best we can do is log the reason and return the
6766          * timed-out indication to the guest.  There is no reason
6767          * we know to expect this failure to be transitory, so the
6768          * guest may well hang retrying the operation.
6769          */
6770         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
6771                       ri->name, error_get_pretty(err));
6772         error_free(err);
6773 
6774         env->ZF = 0; /* NZCF = 0100 */
6775         return 0;
6776     }
6777     return ret;
6778 }
6779 
6780 /* We do not support re-seeding, so the two registers operate the same.  */
6781 static const ARMCPRegInfo rndr_reginfo[] = {
6782     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
6783       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6784       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
6785       .access = PL0_R, .readfn = rndr_readfn },
6786     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
6787       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6788       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
6789       .access = PL0_R, .readfn = rndr_readfn },
6790     REGINFO_SENTINEL
6791 };
6792 
6793 #ifndef CONFIG_USER_ONLY
6794 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
6795                           uint64_t value)
6796 {
6797     ARMCPU *cpu = env_archcpu(env);
6798     /* CTR_EL0 System register -> DminLine, bits [19:16] */
6799     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
6800     uint64_t vaddr_in = (uint64_t) value;
6801     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
6802     void *haddr;
6803     int mem_idx = cpu_mmu_index(env, false);
6804 
6805     /* This won't be crossing page boundaries */
6806     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
6807     if (haddr) {
6808 
6809         ram_addr_t offset;
6810         MemoryRegion *mr;
6811 
6812         /* RCU lock is already being held */
6813         mr = memory_region_from_host(haddr, &offset);
6814 
6815         if (mr) {
6816             memory_region_do_writeback(mr, offset, dline_size);
6817         }
6818     }
6819 }
6820 
6821 static const ARMCPRegInfo dcpop_reg[] = {
6822     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
6823       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
6824       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6825       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6826     REGINFO_SENTINEL
6827 };
6828 
6829 static const ARMCPRegInfo dcpodp_reg[] = {
6830     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
6831       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
6832       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6833       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6834     REGINFO_SENTINEL
6835 };
6836 #endif /*CONFIG_USER_ONLY*/
6837 
6838 #endif
6839 
6840 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
6841                                      bool isread)
6842 {
6843     int el = arm_current_el(env);
6844 
6845     if (el == 0) {
6846         uint64_t sctlr = arm_sctlr(env, el);
6847         if (!(sctlr & SCTLR_EnRCTX)) {
6848             return CP_ACCESS_TRAP;
6849         }
6850     } else if (el == 1) {
6851         uint64_t hcr = arm_hcr_el2_eff(env);
6852         if (hcr & HCR_NV) {
6853             return CP_ACCESS_TRAP_EL2;
6854         }
6855     }
6856     return CP_ACCESS_OK;
6857 }
6858 
6859 static const ARMCPRegInfo predinv_reginfo[] = {
6860     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
6861       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
6862       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6863     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
6864       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
6865       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6866     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
6867       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
6868       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6869     /*
6870      * Note the AArch32 opcodes have a different OPC1.
6871      */
6872     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
6873       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
6874       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6875     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
6876       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
6877       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6878     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
6879       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
6880       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
6881     REGINFO_SENTINEL
6882 };
6883 
6884 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
6885 {
6886     /* Read the high 32 bits of the current CCSIDR */
6887     return extract64(ccsidr_read(env, ri), 32, 32);
6888 }
6889 
6890 static const ARMCPRegInfo ccsidr2_reginfo[] = {
6891     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
6892       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
6893       .access = PL1_R,
6894       .accessfn = access_aa64_tid2,
6895       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
6896     REGINFO_SENTINEL
6897 };
6898 
6899 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
6900                                        bool isread)
6901 {
6902     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
6903         return CP_ACCESS_TRAP_EL2;
6904     }
6905 
6906     return CP_ACCESS_OK;
6907 }
6908 
6909 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
6910                                        bool isread)
6911 {
6912     if (arm_feature(env, ARM_FEATURE_V8)) {
6913         return access_aa64_tid3(env, ri, isread);
6914     }
6915 
6916     return CP_ACCESS_OK;
6917 }
6918 
6919 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
6920                                      bool isread)
6921 {
6922     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
6923         return CP_ACCESS_TRAP_EL2;
6924     }
6925 
6926     return CP_ACCESS_OK;
6927 }
6928 
6929 static const ARMCPRegInfo jazelle_regs[] = {
6930     { .name = "JIDR",
6931       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
6932       .access = PL1_R, .accessfn = access_jazelle,
6933       .type = ARM_CP_CONST, .resetvalue = 0 },
6934     { .name = "JOSCR",
6935       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
6936       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
6937     { .name = "JMCR",
6938       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
6939       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
6940     REGINFO_SENTINEL
6941 };
6942 
6943 static const ARMCPRegInfo vhe_reginfo[] = {
6944     { .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
6945       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
6946       .access = PL2_RW,
6947       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2]) },
6948     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
6949       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
6950       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
6951       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
6952 #ifndef CONFIG_USER_ONLY
6953     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
6954       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
6955       .fieldoffset =
6956         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
6957       .type = ARM_CP_IO, .access = PL2_RW,
6958       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
6959     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
6960       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
6961       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
6962       .resetfn = gt_hv_timer_reset,
6963       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
6964     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
6965       .type = ARM_CP_IO,
6966       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
6967       .access = PL2_RW,
6968       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
6969       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
6970     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
6971       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
6972       .type = ARM_CP_IO | ARM_CP_ALIAS,
6973       .access = PL2_RW, .accessfn = e2h_access,
6974       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
6975       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
6976     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
6977       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
6978       .type = ARM_CP_IO | ARM_CP_ALIAS,
6979       .access = PL2_RW, .accessfn = e2h_access,
6980       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
6981       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
6982     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
6983       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
6984       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
6985       .access = PL2_RW, .accessfn = e2h_access,
6986       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
6987     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
6988       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
6989       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
6990       .access = PL2_RW, .accessfn = e2h_access,
6991       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
6992     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
6993       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
6994       .type = ARM_CP_IO | ARM_CP_ALIAS,
6995       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
6996       .access = PL2_RW, .accessfn = e2h_access,
6997       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
6998     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
6999       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7000       .type = ARM_CP_IO | ARM_CP_ALIAS,
7001       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7002       .access = PL2_RW, .accessfn = e2h_access,
7003       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7004 #endif
7005     REGINFO_SENTINEL
7006 };
7007 
7008 #ifndef CONFIG_USER_ONLY
7009 static const ARMCPRegInfo ats1e1_reginfo[] = {
7010     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7011       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7012       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7013       .writefn = ats_write64 },
7014     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7015       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7016       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7017       .writefn = ats_write64 },
7018     REGINFO_SENTINEL
7019 };
7020 
7021 static const ARMCPRegInfo ats1cp_reginfo[] = {
7022     { .name = "ATS1CPRP",
7023       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7024       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7025       .writefn = ats_write },
7026     { .name = "ATS1CPWP",
7027       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7028       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7029       .writefn = ats_write },
7030     REGINFO_SENTINEL
7031 };
7032 #endif
7033 
7034 /*
7035  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7036  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7037  * is non-zero, which is never for ARMv7, optionally in ARMv8
7038  * and mandatorily for ARMv8.2 and up.
7039  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7040  * implementation is RAZ/WI we can ignore this detail, as we
7041  * do for ACTLR.
7042  */
7043 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7044     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7045       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7046       .access = PL1_RW, .accessfn = access_tacr,
7047       .type = ARM_CP_CONST, .resetvalue = 0 },
7048     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7049       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7050       .access = PL2_RW, .type = ARM_CP_CONST,
7051       .resetvalue = 0 },
7052     REGINFO_SENTINEL
7053 };
7054 
7055 void register_cp_regs_for_features(ARMCPU *cpu)
7056 {
7057     /* Register all the coprocessor registers based on feature bits */
7058     CPUARMState *env = &cpu->env;
7059     if (arm_feature(env, ARM_FEATURE_M)) {
7060         /* M profile has no coprocessor registers */
7061         return;
7062     }
7063 
7064     define_arm_cp_regs(cpu, cp_reginfo);
7065     if (!arm_feature(env, ARM_FEATURE_V8)) {
7066         /* Must go early as it is full of wildcards that may be
7067          * overridden by later definitions.
7068          */
7069         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7070     }
7071 
7072     if (arm_feature(env, ARM_FEATURE_V6)) {
7073         /* The ID registers all have impdef reset values */
7074         ARMCPRegInfo v6_idregs[] = {
7075             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7076               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7077               .access = PL1_R, .type = ARM_CP_CONST,
7078               .accessfn = access_aa32_tid3,
7079               .resetvalue = cpu->id_pfr0 },
7080             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7081              * the value of the GIC field until after we define these regs.
7082              */
7083             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7084               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7085               .access = PL1_R, .type = ARM_CP_NO_RAW,
7086               .accessfn = access_aa32_tid3,
7087               .readfn = id_pfr1_read,
7088               .writefn = arm_cp_write_ignore },
7089             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7090               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7091               .access = PL1_R, .type = ARM_CP_CONST,
7092               .accessfn = access_aa32_tid3,
7093               .resetvalue = cpu->isar.id_dfr0 },
7094             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7095               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7096               .access = PL1_R, .type = ARM_CP_CONST,
7097               .accessfn = access_aa32_tid3,
7098               .resetvalue = cpu->id_afr0 },
7099             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7100               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7101               .access = PL1_R, .type = ARM_CP_CONST,
7102               .accessfn = access_aa32_tid3,
7103               .resetvalue = cpu->isar.id_mmfr0 },
7104             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7105               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7106               .access = PL1_R, .type = ARM_CP_CONST,
7107               .accessfn = access_aa32_tid3,
7108               .resetvalue = cpu->isar.id_mmfr1 },
7109             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7110               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7111               .access = PL1_R, .type = ARM_CP_CONST,
7112               .accessfn = access_aa32_tid3,
7113               .resetvalue = cpu->isar.id_mmfr2 },
7114             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7115               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7116               .access = PL1_R, .type = ARM_CP_CONST,
7117               .accessfn = access_aa32_tid3,
7118               .resetvalue = cpu->isar.id_mmfr3 },
7119             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7120               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7121               .access = PL1_R, .type = ARM_CP_CONST,
7122               .accessfn = access_aa32_tid3,
7123               .resetvalue = cpu->isar.id_isar0 },
7124             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7125               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7126               .access = PL1_R, .type = ARM_CP_CONST,
7127               .accessfn = access_aa32_tid3,
7128               .resetvalue = cpu->isar.id_isar1 },
7129             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7130               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7131               .access = PL1_R, .type = ARM_CP_CONST,
7132               .accessfn = access_aa32_tid3,
7133               .resetvalue = cpu->isar.id_isar2 },
7134             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7135               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7136               .access = PL1_R, .type = ARM_CP_CONST,
7137               .accessfn = access_aa32_tid3,
7138               .resetvalue = cpu->isar.id_isar3 },
7139             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7140               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7141               .access = PL1_R, .type = ARM_CP_CONST,
7142               .accessfn = access_aa32_tid3,
7143               .resetvalue = cpu->isar.id_isar4 },
7144             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7145               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7146               .access = PL1_R, .type = ARM_CP_CONST,
7147               .accessfn = access_aa32_tid3,
7148               .resetvalue = cpu->isar.id_isar5 },
7149             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7150               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7151               .access = PL1_R, .type = ARM_CP_CONST,
7152               .accessfn = access_aa32_tid3,
7153               .resetvalue = cpu->isar.id_mmfr4 },
7154             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7155               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7156               .access = PL1_R, .type = ARM_CP_CONST,
7157               .accessfn = access_aa32_tid3,
7158               .resetvalue = cpu->isar.id_isar6 },
7159             REGINFO_SENTINEL
7160         };
7161         define_arm_cp_regs(cpu, v6_idregs);
7162         define_arm_cp_regs(cpu, v6_cp_reginfo);
7163     } else {
7164         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7165     }
7166     if (arm_feature(env, ARM_FEATURE_V6K)) {
7167         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7168     }
7169     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7170         !arm_feature(env, ARM_FEATURE_PMSA)) {
7171         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7172     }
7173     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7174         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7175     }
7176     if (arm_feature(env, ARM_FEATURE_V7)) {
7177         ARMCPRegInfo clidr = {
7178             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7179             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7180             .access = PL1_R, .type = ARM_CP_CONST,
7181             .accessfn = access_aa64_tid2,
7182             .resetvalue = cpu->clidr
7183         };
7184         define_one_arm_cp_reg(cpu, &clidr);
7185         define_arm_cp_regs(cpu, v7_cp_reginfo);
7186         define_debug_regs(cpu);
7187         define_pmu_regs(cpu);
7188     } else {
7189         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7190     }
7191     if (arm_feature(env, ARM_FEATURE_V8)) {
7192         /* AArch64 ID registers, which all have impdef reset values.
7193          * Note that within the ID register ranges the unused slots
7194          * must all RAZ, not UNDEF; future architecture versions may
7195          * define new registers here.
7196          */
7197         ARMCPRegInfo v8_idregs[] = {
7198             /*
7199              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7200              * emulation because we don't know the right value for the
7201              * GIC field until after we define these regs.
7202              */
7203             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7204               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7205               .access = PL1_R,
7206 #ifdef CONFIG_USER_ONLY
7207               .type = ARM_CP_CONST,
7208               .resetvalue = cpu->isar.id_aa64pfr0
7209 #else
7210               .type = ARM_CP_NO_RAW,
7211               .accessfn = access_aa64_tid3,
7212               .readfn = id_aa64pfr0_read,
7213               .writefn = arm_cp_write_ignore
7214 #endif
7215             },
7216             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7217               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7218               .access = PL1_R, .type = ARM_CP_CONST,
7219               .accessfn = access_aa64_tid3,
7220               .resetvalue = cpu->isar.id_aa64pfr1},
7221             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7222               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7223               .access = PL1_R, .type = ARM_CP_CONST,
7224               .accessfn = access_aa64_tid3,
7225               .resetvalue = 0 },
7226             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7227               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7228               .access = PL1_R, .type = ARM_CP_CONST,
7229               .accessfn = access_aa64_tid3,
7230               .resetvalue = 0 },
7231             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7232               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7233               .access = PL1_R, .type = ARM_CP_CONST,
7234               .accessfn = access_aa64_tid3,
7235               /* At present, only SVEver == 0 is defined anyway.  */
7236               .resetvalue = 0 },
7237             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7238               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7239               .access = PL1_R, .type = ARM_CP_CONST,
7240               .accessfn = access_aa64_tid3,
7241               .resetvalue = 0 },
7242             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7243               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7244               .access = PL1_R, .type = ARM_CP_CONST,
7245               .accessfn = access_aa64_tid3,
7246               .resetvalue = 0 },
7247             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7248               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7249               .access = PL1_R, .type = ARM_CP_CONST,
7250               .accessfn = access_aa64_tid3,
7251               .resetvalue = 0 },
7252             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7253               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7254               .access = PL1_R, .type = ARM_CP_CONST,
7255               .accessfn = access_aa64_tid3,
7256               .resetvalue = cpu->isar.id_aa64dfr0 },
7257             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7258               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7259               .access = PL1_R, .type = ARM_CP_CONST,
7260               .accessfn = access_aa64_tid3,
7261               .resetvalue = cpu->isar.id_aa64dfr1 },
7262             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7263               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7264               .access = PL1_R, .type = ARM_CP_CONST,
7265               .accessfn = access_aa64_tid3,
7266               .resetvalue = 0 },
7267             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7268               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7269               .access = PL1_R, .type = ARM_CP_CONST,
7270               .accessfn = access_aa64_tid3,
7271               .resetvalue = 0 },
7272             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7273               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7274               .access = PL1_R, .type = ARM_CP_CONST,
7275               .accessfn = access_aa64_tid3,
7276               .resetvalue = cpu->id_aa64afr0 },
7277             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7278               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7279               .access = PL1_R, .type = ARM_CP_CONST,
7280               .accessfn = access_aa64_tid3,
7281               .resetvalue = cpu->id_aa64afr1 },
7282             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7283               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7284               .access = PL1_R, .type = ARM_CP_CONST,
7285               .accessfn = access_aa64_tid3,
7286               .resetvalue = 0 },
7287             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7288               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7289               .access = PL1_R, .type = ARM_CP_CONST,
7290               .accessfn = access_aa64_tid3,
7291               .resetvalue = 0 },
7292             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7293               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7294               .access = PL1_R, .type = ARM_CP_CONST,
7295               .accessfn = access_aa64_tid3,
7296               .resetvalue = cpu->isar.id_aa64isar0 },
7297             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7298               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7299               .access = PL1_R, .type = ARM_CP_CONST,
7300               .accessfn = access_aa64_tid3,
7301               .resetvalue = cpu->isar.id_aa64isar1 },
7302             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7303               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7304               .access = PL1_R, .type = ARM_CP_CONST,
7305               .accessfn = access_aa64_tid3,
7306               .resetvalue = 0 },
7307             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7308               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7309               .access = PL1_R, .type = ARM_CP_CONST,
7310               .accessfn = access_aa64_tid3,
7311               .resetvalue = 0 },
7312             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7313               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7314               .access = PL1_R, .type = ARM_CP_CONST,
7315               .accessfn = access_aa64_tid3,
7316               .resetvalue = 0 },
7317             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7318               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7319               .access = PL1_R, .type = ARM_CP_CONST,
7320               .accessfn = access_aa64_tid3,
7321               .resetvalue = 0 },
7322             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7323               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7324               .access = PL1_R, .type = ARM_CP_CONST,
7325               .accessfn = access_aa64_tid3,
7326               .resetvalue = 0 },
7327             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7328               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7329               .access = PL1_R, .type = ARM_CP_CONST,
7330               .accessfn = access_aa64_tid3,
7331               .resetvalue = 0 },
7332             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7333               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7334               .access = PL1_R, .type = ARM_CP_CONST,
7335               .accessfn = access_aa64_tid3,
7336               .resetvalue = cpu->isar.id_aa64mmfr0 },
7337             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7338               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7339               .access = PL1_R, .type = ARM_CP_CONST,
7340               .accessfn = access_aa64_tid3,
7341               .resetvalue = cpu->isar.id_aa64mmfr1 },
7342             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7343               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7344               .access = PL1_R, .type = ARM_CP_CONST,
7345               .accessfn = access_aa64_tid3,
7346               .resetvalue = cpu->isar.id_aa64mmfr2 },
7347             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7348               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7349               .access = PL1_R, .type = ARM_CP_CONST,
7350               .accessfn = access_aa64_tid3,
7351               .resetvalue = 0 },
7352             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7353               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7354               .access = PL1_R, .type = ARM_CP_CONST,
7355               .accessfn = access_aa64_tid3,
7356               .resetvalue = 0 },
7357             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7358               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7359               .access = PL1_R, .type = ARM_CP_CONST,
7360               .accessfn = access_aa64_tid3,
7361               .resetvalue = 0 },
7362             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7363               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7364               .access = PL1_R, .type = ARM_CP_CONST,
7365               .accessfn = access_aa64_tid3,
7366               .resetvalue = 0 },
7367             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7368               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7369               .access = PL1_R, .type = ARM_CP_CONST,
7370               .accessfn = access_aa64_tid3,
7371               .resetvalue = 0 },
7372             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7373               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7374               .access = PL1_R, .type = ARM_CP_CONST,
7375               .accessfn = access_aa64_tid3,
7376               .resetvalue = cpu->isar.mvfr0 },
7377             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7378               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7379               .access = PL1_R, .type = ARM_CP_CONST,
7380               .accessfn = access_aa64_tid3,
7381               .resetvalue = cpu->isar.mvfr1 },
7382             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7383               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7384               .access = PL1_R, .type = ARM_CP_CONST,
7385               .accessfn = access_aa64_tid3,
7386               .resetvalue = cpu->isar.mvfr2 },
7387             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7388               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7389               .access = PL1_R, .type = ARM_CP_CONST,
7390               .accessfn = access_aa64_tid3,
7391               .resetvalue = 0 },
7392             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7393               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7394               .access = PL1_R, .type = ARM_CP_CONST,
7395               .accessfn = access_aa64_tid3,
7396               .resetvalue = 0 },
7397             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7398               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7399               .access = PL1_R, .type = ARM_CP_CONST,
7400               .accessfn = access_aa64_tid3,
7401               .resetvalue = 0 },
7402             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7403               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7404               .access = PL1_R, .type = ARM_CP_CONST,
7405               .accessfn = access_aa64_tid3,
7406               .resetvalue = 0 },
7407             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7408               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7409               .access = PL1_R, .type = ARM_CP_CONST,
7410               .accessfn = access_aa64_tid3,
7411               .resetvalue = 0 },
7412             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7413               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7414               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7415               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7416             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7417               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7418               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7419               .resetvalue = cpu->pmceid0 },
7420             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7421               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7422               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7423               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7424             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7425               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7426               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7427               .resetvalue = cpu->pmceid1 },
7428             REGINFO_SENTINEL
7429         };
7430 #ifdef CONFIG_USER_ONLY
7431         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7432             { .name = "ID_AA64PFR0_EL1",
7433               .exported_bits = 0x000f000f00ff0000,
7434               .fixed_bits    = 0x0000000000000011 },
7435             { .name = "ID_AA64PFR1_EL1",
7436               .exported_bits = 0x00000000000000f0 },
7437             { .name = "ID_AA64PFR*_EL1_RESERVED",
7438               .is_glob = true                     },
7439             { .name = "ID_AA64ZFR0_EL1"           },
7440             { .name = "ID_AA64MMFR0_EL1",
7441               .fixed_bits    = 0x00000000ff000000 },
7442             { .name = "ID_AA64MMFR1_EL1"          },
7443             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7444               .is_glob = true                     },
7445             { .name = "ID_AA64DFR0_EL1",
7446               .fixed_bits    = 0x0000000000000006 },
7447             { .name = "ID_AA64DFR1_EL1"           },
7448             { .name = "ID_AA64DFR*_EL1_RESERVED",
7449               .is_glob = true                     },
7450             { .name = "ID_AA64AFR*",
7451               .is_glob = true                     },
7452             { .name = "ID_AA64ISAR0_EL1",
7453               .exported_bits = 0x00fffffff0fffff0 },
7454             { .name = "ID_AA64ISAR1_EL1",
7455               .exported_bits = 0x000000f0ffffffff },
7456             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7457               .is_glob = true                     },
7458             REGUSERINFO_SENTINEL
7459         };
7460         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7461 #endif
7462         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7463         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7464             !arm_feature(env, ARM_FEATURE_EL2)) {
7465             ARMCPRegInfo rvbar = {
7466                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7467                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7468                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
7469             };
7470             define_one_arm_cp_reg(cpu, &rvbar);
7471         }
7472         define_arm_cp_regs(cpu, v8_idregs);
7473         define_arm_cp_regs(cpu, v8_cp_reginfo);
7474     }
7475     if (arm_feature(env, ARM_FEATURE_EL2)) {
7476         uint64_t vmpidr_def = mpidr_read_val(env);
7477         ARMCPRegInfo vpidr_regs[] = {
7478             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7479               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7480               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7481               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
7482               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7483             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7484               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7485               .access = PL2_RW, .resetvalue = cpu->midr,
7486               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7487             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7488               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7489               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7490               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
7491               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7492             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7493               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7494               .access = PL2_RW,
7495               .resetvalue = vmpidr_def,
7496               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7497             REGINFO_SENTINEL
7498         };
7499         define_arm_cp_regs(cpu, vpidr_regs);
7500         define_arm_cp_regs(cpu, el2_cp_reginfo);
7501         if (arm_feature(env, ARM_FEATURE_V8)) {
7502             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
7503         }
7504         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
7505         if (!arm_feature(env, ARM_FEATURE_EL3)) {
7506             ARMCPRegInfo rvbar = {
7507                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
7508                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
7509                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
7510             };
7511             define_one_arm_cp_reg(cpu, &rvbar);
7512         }
7513     } else {
7514         /* If EL2 is missing but higher ELs are enabled, we need to
7515          * register the no_el2 reginfos.
7516          */
7517         if (arm_feature(env, ARM_FEATURE_EL3)) {
7518             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
7519              * of MIDR_EL1 and MPIDR_EL1.
7520              */
7521             ARMCPRegInfo vpidr_regs[] = {
7522                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7523                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7524                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
7525                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
7526                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7527                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7528                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7529                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
7530                   .type = ARM_CP_NO_RAW,
7531                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
7532                 REGINFO_SENTINEL
7533             };
7534             define_arm_cp_regs(cpu, vpidr_regs);
7535             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
7536             if (arm_feature(env, ARM_FEATURE_V8)) {
7537                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
7538             }
7539         }
7540     }
7541     if (arm_feature(env, ARM_FEATURE_EL3)) {
7542         define_arm_cp_regs(cpu, el3_cp_reginfo);
7543         ARMCPRegInfo el3_regs[] = {
7544             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
7545               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
7546               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
7547             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
7548               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
7549               .access = PL3_RW,
7550               .raw_writefn = raw_write, .writefn = sctlr_write,
7551               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
7552               .resetvalue = cpu->reset_sctlr },
7553             REGINFO_SENTINEL
7554         };
7555 
7556         define_arm_cp_regs(cpu, el3_regs);
7557     }
7558     /* The behaviour of NSACR is sufficiently various that we don't
7559      * try to describe it in a single reginfo:
7560      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
7561      *     reads as constant 0xc00 from NS EL1 and NS EL2
7562      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
7563      *  if v7 without EL3, register doesn't exist
7564      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
7565      */
7566     if (arm_feature(env, ARM_FEATURE_EL3)) {
7567         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7568             ARMCPRegInfo nsacr = {
7569                 .name = "NSACR", .type = ARM_CP_CONST,
7570                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7571                 .access = PL1_RW, .accessfn = nsacr_access,
7572                 .resetvalue = 0xc00
7573             };
7574             define_one_arm_cp_reg(cpu, &nsacr);
7575         } else {
7576             ARMCPRegInfo nsacr = {
7577                 .name = "NSACR",
7578                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7579                 .access = PL3_RW | PL1_R,
7580                 .resetvalue = 0,
7581                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
7582             };
7583             define_one_arm_cp_reg(cpu, &nsacr);
7584         }
7585     } else {
7586         if (arm_feature(env, ARM_FEATURE_V8)) {
7587             ARMCPRegInfo nsacr = {
7588                 .name = "NSACR", .type = ARM_CP_CONST,
7589                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7590                 .access = PL1_R,
7591                 .resetvalue = 0xc00
7592             };
7593             define_one_arm_cp_reg(cpu, &nsacr);
7594         }
7595     }
7596 
7597     if (arm_feature(env, ARM_FEATURE_PMSA)) {
7598         if (arm_feature(env, ARM_FEATURE_V6)) {
7599             /* PMSAv6 not implemented */
7600             assert(arm_feature(env, ARM_FEATURE_V7));
7601             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7602             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
7603         } else {
7604             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
7605         }
7606     } else {
7607         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7608         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
7609         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
7610         if (cpu_isar_feature(aa32_hpd, cpu)) {
7611             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
7612         }
7613     }
7614     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
7615         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
7616     }
7617     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
7618         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
7619     }
7620     if (arm_feature(env, ARM_FEATURE_VAPA)) {
7621         define_arm_cp_regs(cpu, vapa_cp_reginfo);
7622     }
7623     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
7624         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
7625     }
7626     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
7627         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
7628     }
7629     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
7630         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
7631     }
7632     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
7633         define_arm_cp_regs(cpu, omap_cp_reginfo);
7634     }
7635     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
7636         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
7637     }
7638     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
7639         define_arm_cp_regs(cpu, xscale_cp_reginfo);
7640     }
7641     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
7642         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
7643     }
7644     if (arm_feature(env, ARM_FEATURE_LPAE)) {
7645         define_arm_cp_regs(cpu, lpae_cp_reginfo);
7646     }
7647     if (cpu_isar_feature(aa32_jazelle, cpu)) {
7648         define_arm_cp_regs(cpu, jazelle_regs);
7649     }
7650     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
7651      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
7652      * be read-only (ie write causes UNDEF exception).
7653      */
7654     {
7655         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
7656             /* Pre-v8 MIDR space.
7657              * Note that the MIDR isn't a simple constant register because
7658              * of the TI925 behaviour where writes to another register can
7659              * cause the MIDR value to change.
7660              *
7661              * Unimplemented registers in the c15 0 0 0 space default to
7662              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
7663              * and friends override accordingly.
7664              */
7665             { .name = "MIDR",
7666               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
7667               .access = PL1_R, .resetvalue = cpu->midr,
7668               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
7669               .readfn = midr_read,
7670               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7671               .type = ARM_CP_OVERRIDE },
7672             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
7673             { .name = "DUMMY",
7674               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
7675               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7676             { .name = "DUMMY",
7677               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
7678               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7679             { .name = "DUMMY",
7680               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
7681               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7682             { .name = "DUMMY",
7683               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
7684               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7685             { .name = "DUMMY",
7686               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
7687               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7688             REGINFO_SENTINEL
7689         };
7690         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
7691             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
7692               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
7693               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
7694               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7695               .readfn = midr_read },
7696             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
7697             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
7698               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
7699               .access = PL1_R, .resetvalue = cpu->midr },
7700             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
7701               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
7702               .access = PL1_R, .resetvalue = cpu->midr },
7703             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
7704               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
7705               .access = PL1_R,
7706               .accessfn = access_aa64_tid1,
7707               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
7708             REGINFO_SENTINEL
7709         };
7710         ARMCPRegInfo id_cp_reginfo[] = {
7711             /* These are common to v8 and pre-v8 */
7712             { .name = "CTR",
7713               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
7714               .access = PL1_R, .accessfn = ctr_el0_access,
7715               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
7716             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
7717               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
7718               .access = PL0_R, .accessfn = ctr_el0_access,
7719               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
7720             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
7721             { .name = "TCMTR",
7722               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
7723               .access = PL1_R,
7724               .accessfn = access_aa32_tid1,
7725               .type = ARM_CP_CONST, .resetvalue = 0 },
7726             REGINFO_SENTINEL
7727         };
7728         /* TLBTR is specific to VMSA */
7729         ARMCPRegInfo id_tlbtr_reginfo = {
7730               .name = "TLBTR",
7731               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
7732               .access = PL1_R,
7733               .accessfn = access_aa32_tid1,
7734               .type = ARM_CP_CONST, .resetvalue = 0,
7735         };
7736         /* MPUIR is specific to PMSA V6+ */
7737         ARMCPRegInfo id_mpuir_reginfo = {
7738               .name = "MPUIR",
7739               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
7740               .access = PL1_R, .type = ARM_CP_CONST,
7741               .resetvalue = cpu->pmsav7_dregion << 8
7742         };
7743         ARMCPRegInfo crn0_wi_reginfo = {
7744             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
7745             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
7746             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
7747         };
7748 #ifdef CONFIG_USER_ONLY
7749         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
7750             { .name = "MIDR_EL1",
7751               .exported_bits = 0x00000000ffffffff },
7752             { .name = "REVIDR_EL1"                },
7753             REGUSERINFO_SENTINEL
7754         };
7755         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
7756 #endif
7757         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
7758             arm_feature(env, ARM_FEATURE_STRONGARM)) {
7759             ARMCPRegInfo *r;
7760             /* Register the blanket "writes ignored" value first to cover the
7761              * whole space. Then update the specific ID registers to allow write
7762              * access, so that they ignore writes rather than causing them to
7763              * UNDEF.
7764              */
7765             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
7766             for (r = id_pre_v8_midr_cp_reginfo;
7767                  r->type != ARM_CP_SENTINEL; r++) {
7768                 r->access = PL1_RW;
7769             }
7770             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
7771                 r->access = PL1_RW;
7772             }
7773             id_mpuir_reginfo.access = PL1_RW;
7774             id_tlbtr_reginfo.access = PL1_RW;
7775         }
7776         if (arm_feature(env, ARM_FEATURE_V8)) {
7777             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
7778         } else {
7779             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
7780         }
7781         define_arm_cp_regs(cpu, id_cp_reginfo);
7782         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
7783             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
7784         } else if (arm_feature(env, ARM_FEATURE_V7)) {
7785             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
7786         }
7787     }
7788 
7789     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
7790         ARMCPRegInfo mpidr_cp_reginfo[] = {
7791             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
7792               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
7793               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
7794             REGINFO_SENTINEL
7795         };
7796 #ifdef CONFIG_USER_ONLY
7797         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
7798             { .name = "MPIDR_EL1",
7799               .fixed_bits = 0x0000000080000000 },
7800             REGUSERINFO_SENTINEL
7801         };
7802         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
7803 #endif
7804         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
7805     }
7806 
7807     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
7808         ARMCPRegInfo auxcr_reginfo[] = {
7809             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
7810               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
7811               .access = PL1_RW, .accessfn = access_tacr,
7812               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
7813             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
7814               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
7815               .access = PL2_RW, .type = ARM_CP_CONST,
7816               .resetvalue = 0 },
7817             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
7818               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
7819               .access = PL3_RW, .type = ARM_CP_CONST,
7820               .resetvalue = 0 },
7821             REGINFO_SENTINEL
7822         };
7823         define_arm_cp_regs(cpu, auxcr_reginfo);
7824         if (cpu_isar_feature(aa32_ac2, cpu)) {
7825             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
7826         }
7827     }
7828 
7829     if (arm_feature(env, ARM_FEATURE_CBAR)) {
7830         /*
7831          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
7832          * There are two flavours:
7833          *  (1) older 32-bit only cores have a simple 32-bit CBAR
7834          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
7835          *      32-bit register visible to AArch32 at a different encoding
7836          *      to the "flavour 1" register and with the bits rearranged to
7837          *      be able to squash a 64-bit address into the 32-bit view.
7838          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
7839          * in future if we support AArch32-only configs of some of the
7840          * AArch64 cores we might need to add a specific feature flag
7841          * to indicate cores with "flavour 2" CBAR.
7842          */
7843         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7844             /* 32 bit view is [31:18] 0...0 [43:32]. */
7845             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
7846                 | extract64(cpu->reset_cbar, 32, 12);
7847             ARMCPRegInfo cbar_reginfo[] = {
7848                 { .name = "CBAR",
7849                   .type = ARM_CP_CONST,
7850                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
7851                   .access = PL1_R, .resetvalue = cbar32 },
7852                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
7853                   .type = ARM_CP_CONST,
7854                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
7855                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
7856                 REGINFO_SENTINEL
7857             };
7858             /* We don't implement a r/w 64 bit CBAR currently */
7859             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
7860             define_arm_cp_regs(cpu, cbar_reginfo);
7861         } else {
7862             ARMCPRegInfo cbar = {
7863                 .name = "CBAR",
7864                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
7865                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
7866                 .fieldoffset = offsetof(CPUARMState,
7867                                         cp15.c15_config_base_address)
7868             };
7869             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
7870                 cbar.access = PL1_R;
7871                 cbar.fieldoffset = 0;
7872                 cbar.type = ARM_CP_CONST;
7873             }
7874             define_one_arm_cp_reg(cpu, &cbar);
7875         }
7876     }
7877 
7878     if (arm_feature(env, ARM_FEATURE_VBAR)) {
7879         ARMCPRegInfo vbar_cp_reginfo[] = {
7880             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
7881               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
7882               .access = PL1_RW, .writefn = vbar_write,
7883               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
7884                                      offsetof(CPUARMState, cp15.vbar_ns) },
7885               .resetvalue = 0 },
7886             REGINFO_SENTINEL
7887         };
7888         define_arm_cp_regs(cpu, vbar_cp_reginfo);
7889     }
7890 
7891     /* Generic registers whose values depend on the implementation */
7892     {
7893         ARMCPRegInfo sctlr = {
7894             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
7895             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
7896             .access = PL1_RW, .accessfn = access_tvm_trvm,
7897             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
7898                                    offsetof(CPUARMState, cp15.sctlr_ns) },
7899             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
7900             .raw_writefn = raw_write,
7901         };
7902         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
7903             /* Normally we would always end the TB on an SCTLR write, but Linux
7904              * arch/arm/mach-pxa/sleep.S expects two instructions following
7905              * an MMU enable to execute from cache.  Imitate this behaviour.
7906              */
7907             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
7908         }
7909         define_one_arm_cp_reg(cpu, &sctlr);
7910     }
7911 
7912     if (cpu_isar_feature(aa64_lor, cpu)) {
7913         define_arm_cp_regs(cpu, lor_reginfo);
7914     }
7915     if (cpu_isar_feature(aa64_pan, cpu)) {
7916         define_one_arm_cp_reg(cpu, &pan_reginfo);
7917     }
7918 #ifndef CONFIG_USER_ONLY
7919     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
7920         define_arm_cp_regs(cpu, ats1e1_reginfo);
7921     }
7922     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
7923         define_arm_cp_regs(cpu, ats1cp_reginfo);
7924     }
7925 #endif
7926     if (cpu_isar_feature(aa64_uao, cpu)) {
7927         define_one_arm_cp_reg(cpu, &uao_reginfo);
7928     }
7929 
7930     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
7931         define_arm_cp_regs(cpu, vhe_reginfo);
7932     }
7933 
7934     if (cpu_isar_feature(aa64_sve, cpu)) {
7935         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
7936         if (arm_feature(env, ARM_FEATURE_EL2)) {
7937             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
7938         } else {
7939             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
7940         }
7941         if (arm_feature(env, ARM_FEATURE_EL3)) {
7942             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
7943         }
7944     }
7945 
7946 #ifdef TARGET_AARCH64
7947     if (cpu_isar_feature(aa64_pauth, cpu)) {
7948         define_arm_cp_regs(cpu, pauth_reginfo);
7949     }
7950     if (cpu_isar_feature(aa64_rndr, cpu)) {
7951         define_arm_cp_regs(cpu, rndr_reginfo);
7952     }
7953 #ifndef CONFIG_USER_ONLY
7954     /* Data Cache clean instructions up to PoP */
7955     if (cpu_isar_feature(aa64_dcpop, cpu)) {
7956         define_one_arm_cp_reg(cpu, dcpop_reg);
7957 
7958         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
7959             define_one_arm_cp_reg(cpu, dcpodp_reg);
7960         }
7961     }
7962 #endif /*CONFIG_USER_ONLY*/
7963 #endif
7964 
7965     if (cpu_isar_feature(any_predinv, cpu)) {
7966         define_arm_cp_regs(cpu, predinv_reginfo);
7967     }
7968 
7969     if (cpu_isar_feature(any_ccidx, cpu)) {
7970         define_arm_cp_regs(cpu, ccsidr2_reginfo);
7971     }
7972 
7973 #ifndef CONFIG_USER_ONLY
7974     /*
7975      * Register redirections and aliases must be done last,
7976      * after the registers from the other extensions have been defined.
7977      */
7978     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
7979         define_arm_vh_e2h_redirects_aliases(cpu);
7980     }
7981 #endif
7982 }
7983 
7984 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
7985 {
7986     CPUState *cs = CPU(cpu);
7987     CPUARMState *env = &cpu->env;
7988 
7989     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7990         /*
7991          * The lower part of each SVE register aliases to the FPU
7992          * registers so we don't need to include both.
7993          */
7994 #ifdef TARGET_AARCH64
7995         if (isar_feature_aa64_sve(&cpu->isar)) {
7996             gdb_register_coprocessor(cs, arm_gdb_get_svereg, arm_gdb_set_svereg,
7997                                      arm_gen_dynamic_svereg_xml(cs, cs->gdb_num_regs),
7998                                      "sve-registers.xml", 0);
7999         } else
8000 #endif
8001         {
8002             gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
8003                                      aarch64_fpu_gdb_set_reg,
8004                                      34, "aarch64-fpu.xml", 0);
8005         }
8006     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
8007         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8008                                  51, "arm-neon.xml", 0);
8009     } else if (cpu_isar_feature(aa32_simd_r32, cpu)) {
8010         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8011                                  35, "arm-vfp3.xml", 0);
8012     } else if (cpu_isar_feature(aa32_vfp_simd, cpu)) {
8013         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8014                                  19, "arm-vfp.xml", 0);
8015     }
8016     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
8017                              arm_gen_dynamic_sysreg_xml(cs, cs->gdb_num_regs),
8018                              "system-registers.xml", 0);
8019 
8020 }
8021 
8022 /* Sort alphabetically by type name, except for "any". */
8023 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8024 {
8025     ObjectClass *class_a = (ObjectClass *)a;
8026     ObjectClass *class_b = (ObjectClass *)b;
8027     const char *name_a, *name_b;
8028 
8029     name_a = object_class_get_name(class_a);
8030     name_b = object_class_get_name(class_b);
8031     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8032         return 1;
8033     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8034         return -1;
8035     } else {
8036         return strcmp(name_a, name_b);
8037     }
8038 }
8039 
8040 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8041 {
8042     ObjectClass *oc = data;
8043     const char *typename;
8044     char *name;
8045 
8046     typename = object_class_get_name(oc);
8047     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8048     qemu_printf("  %s\n", name);
8049     g_free(name);
8050 }
8051 
8052 void arm_cpu_list(void)
8053 {
8054     GSList *list;
8055 
8056     list = object_class_get_list(TYPE_ARM_CPU, false);
8057     list = g_slist_sort(list, arm_cpu_list_compare);
8058     qemu_printf("Available CPUs:\n");
8059     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8060     g_slist_free(list);
8061 }
8062 
8063 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8064 {
8065     ObjectClass *oc = data;
8066     CpuDefinitionInfoList **cpu_list = user_data;
8067     CpuDefinitionInfoList *entry;
8068     CpuDefinitionInfo *info;
8069     const char *typename;
8070 
8071     typename = object_class_get_name(oc);
8072     info = g_malloc0(sizeof(*info));
8073     info->name = g_strndup(typename,
8074                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8075     info->q_typename = g_strdup(typename);
8076 
8077     entry = g_malloc0(sizeof(*entry));
8078     entry->value = info;
8079     entry->next = *cpu_list;
8080     *cpu_list = entry;
8081 }
8082 
8083 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8084 {
8085     CpuDefinitionInfoList *cpu_list = NULL;
8086     GSList *list;
8087 
8088     list = object_class_get_list(TYPE_ARM_CPU, false);
8089     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8090     g_slist_free(list);
8091 
8092     return cpu_list;
8093 }
8094 
8095 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8096                                    void *opaque, int state, int secstate,
8097                                    int crm, int opc1, int opc2,
8098                                    const char *name)
8099 {
8100     /* Private utility function for define_one_arm_cp_reg_with_opaque():
8101      * add a single reginfo struct to the hash table.
8102      */
8103     uint32_t *key = g_new(uint32_t, 1);
8104     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
8105     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
8106     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
8107 
8108     r2->name = g_strdup(name);
8109     /* Reset the secure state to the specific incoming state.  This is
8110      * necessary as the register may have been defined with both states.
8111      */
8112     r2->secure = secstate;
8113 
8114     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8115         /* Register is banked (using both entries in array).
8116          * Overwriting fieldoffset as the array is only used to define
8117          * banked registers but later only fieldoffset is used.
8118          */
8119         r2->fieldoffset = r->bank_fieldoffsets[ns];
8120     }
8121 
8122     if (state == ARM_CP_STATE_AA32) {
8123         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8124             /* If the register is banked then we don't need to migrate or
8125              * reset the 32-bit instance in certain cases:
8126              *
8127              * 1) If the register has both 32-bit and 64-bit instances then we
8128              *    can count on the 64-bit instance taking care of the
8129              *    non-secure bank.
8130              * 2) If ARMv8 is enabled then we can count on a 64-bit version
8131              *    taking care of the secure bank.  This requires that separate
8132              *    32 and 64-bit definitions are provided.
8133              */
8134             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8135                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
8136                 r2->type |= ARM_CP_ALIAS;
8137             }
8138         } else if ((secstate != r->secure) && !ns) {
8139             /* The register is not banked so we only want to allow migration of
8140              * the non-secure instance.
8141              */
8142             r2->type |= ARM_CP_ALIAS;
8143         }
8144 
8145         if (r->state == ARM_CP_STATE_BOTH) {
8146             /* We assume it is a cp15 register if the .cp field is left unset.
8147              */
8148             if (r2->cp == 0) {
8149                 r2->cp = 15;
8150             }
8151 
8152 #ifdef HOST_WORDS_BIGENDIAN
8153             if (r2->fieldoffset) {
8154                 r2->fieldoffset += sizeof(uint32_t);
8155             }
8156 #endif
8157         }
8158     }
8159     if (state == ARM_CP_STATE_AA64) {
8160         /* To allow abbreviation of ARMCPRegInfo
8161          * definitions, we treat cp == 0 as equivalent to
8162          * the value for "standard guest-visible sysreg".
8163          * STATE_BOTH definitions are also always "standard
8164          * sysreg" in their AArch64 view (the .cp value may
8165          * be non-zero for the benefit of the AArch32 view).
8166          */
8167         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8168             r2->cp = CP_REG_ARM64_SYSREG_CP;
8169         }
8170         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
8171                                   r2->opc0, opc1, opc2);
8172     } else {
8173         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
8174     }
8175     if (opaque) {
8176         r2->opaque = opaque;
8177     }
8178     /* reginfo passed to helpers is correct for the actual access,
8179      * and is never ARM_CP_STATE_BOTH:
8180      */
8181     r2->state = state;
8182     /* Make sure reginfo passed to helpers for wildcarded regs
8183      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
8184      */
8185     r2->crm = crm;
8186     r2->opc1 = opc1;
8187     r2->opc2 = opc2;
8188     /* By convention, for wildcarded registers only the first
8189      * entry is used for migration; the others are marked as
8190      * ALIAS so we don't try to transfer the register
8191      * multiple times. Special registers (ie NOP/WFI) are
8192      * never migratable and not even raw-accessible.
8193      */
8194     if ((r->type & ARM_CP_SPECIAL)) {
8195         r2->type |= ARM_CP_NO_RAW;
8196     }
8197     if (((r->crm == CP_ANY) && crm != 0) ||
8198         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8199         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8200         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8201     }
8202 
8203     /* Check that raw accesses are either forbidden or handled. Note that
8204      * we can't assert this earlier because the setup of fieldoffset for
8205      * banked registers has to be done first.
8206      */
8207     if (!(r2->type & ARM_CP_NO_RAW)) {
8208         assert(!raw_accessors_invalid(r2));
8209     }
8210 
8211     /* Overriding of an existing definition must be explicitly
8212      * requested.
8213      */
8214     if (!(r->type & ARM_CP_OVERRIDE)) {
8215         ARMCPRegInfo *oldreg;
8216         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
8217         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
8218             fprintf(stderr, "Register redefined: cp=%d %d bit "
8219                     "crn=%d crm=%d opc1=%d opc2=%d, "
8220                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
8221                     r2->crn, r2->crm, r2->opc1, r2->opc2,
8222                     oldreg->name, r2->name);
8223             g_assert_not_reached();
8224         }
8225     }
8226     g_hash_table_insert(cpu->cp_regs, key, r2);
8227 }
8228 
8229 
8230 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8231                                        const ARMCPRegInfo *r, void *opaque)
8232 {
8233     /* Define implementations of coprocessor registers.
8234      * We store these in a hashtable because typically
8235      * there are less than 150 registers in a space which
8236      * is 16*16*16*8*8 = 262144 in size.
8237      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8238      * If a register is defined twice then the second definition is
8239      * used, so this can be used to define some generic registers and
8240      * then override them with implementation specific variations.
8241      * At least one of the original and the second definition should
8242      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8243      * against accidental use.
8244      *
8245      * The state field defines whether the register is to be
8246      * visible in the AArch32 or AArch64 execution state. If the
8247      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8248      * reginfo structure for the AArch32 view, which sees the lower
8249      * 32 bits of the 64 bit register.
8250      *
8251      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8252      * be wildcarded. AArch64 registers are always considered to be 64
8253      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8254      * the register, if any.
8255      */
8256     int crm, opc1, opc2, state;
8257     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8258     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8259     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8260     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8261     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8262     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8263     /* 64 bit registers have only CRm and Opc1 fields */
8264     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8265     /* op0 only exists in the AArch64 encodings */
8266     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8267     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8268     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8269     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8270      * encodes a minimum access level for the register. We roll this
8271      * runtime check into our general permission check code, so check
8272      * here that the reginfo's specified permissions are strict enough
8273      * to encompass the generic architectural permission check.
8274      */
8275     if (r->state != ARM_CP_STATE_AA32) {
8276         int mask = 0;
8277         switch (r->opc1) {
8278         case 0:
8279             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8280             mask = PL0U_R | PL1_RW;
8281             break;
8282         case 1: case 2:
8283             /* min_EL EL1 */
8284             mask = PL1_RW;
8285             break;
8286         case 3:
8287             /* min_EL EL0 */
8288             mask = PL0_RW;
8289             break;
8290         case 4:
8291         case 5:
8292             /* min_EL EL2 */
8293             mask = PL2_RW;
8294             break;
8295         case 6:
8296             /* min_EL EL3 */
8297             mask = PL3_RW;
8298             break;
8299         case 7:
8300             /* min_EL EL1, secure mode only (we don't check the latter) */
8301             mask = PL1_RW;
8302             break;
8303         default:
8304             /* broken reginfo with out-of-range opc1 */
8305             assert(false);
8306             break;
8307         }
8308         /* assert our permissions are not too lax (stricter is fine) */
8309         assert((r->access & ~mask) == 0);
8310     }
8311 
8312     /* Check that the register definition has enough info to handle
8313      * reads and writes if they are permitted.
8314      */
8315     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
8316         if (r->access & PL3_R) {
8317             assert((r->fieldoffset ||
8318                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8319                    r->readfn);
8320         }
8321         if (r->access & PL3_W) {
8322             assert((r->fieldoffset ||
8323                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8324                    r->writefn);
8325         }
8326     }
8327     /* Bad type field probably means missing sentinel at end of reg list */
8328     assert(cptype_valid(r->type));
8329     for (crm = crmmin; crm <= crmmax; crm++) {
8330         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8331             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8332                 for (state = ARM_CP_STATE_AA32;
8333                      state <= ARM_CP_STATE_AA64; state++) {
8334                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8335                         continue;
8336                     }
8337                     if (state == ARM_CP_STATE_AA32) {
8338                         /* Under AArch32 CP registers can be common
8339                          * (same for secure and non-secure world) or banked.
8340                          */
8341                         char *name;
8342 
8343                         switch (r->secure) {
8344                         case ARM_CP_SECSTATE_S:
8345                         case ARM_CP_SECSTATE_NS:
8346                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8347                                                    r->secure, crm, opc1, opc2,
8348                                                    r->name);
8349                             break;
8350                         default:
8351                             name = g_strdup_printf("%s_S", r->name);
8352                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8353                                                    ARM_CP_SECSTATE_S,
8354                                                    crm, opc1, opc2, name);
8355                             g_free(name);
8356                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8357                                                    ARM_CP_SECSTATE_NS,
8358                                                    crm, opc1, opc2, r->name);
8359                             break;
8360                         }
8361                     } else {
8362                         /* AArch64 registers get mapped to non-secure instance
8363                          * of AArch32 */
8364                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8365                                                ARM_CP_SECSTATE_NS,
8366                                                crm, opc1, opc2, r->name);
8367                     }
8368                 }
8369             }
8370         }
8371     }
8372 }
8373 
8374 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
8375                                     const ARMCPRegInfo *regs, void *opaque)
8376 {
8377     /* Define a whole list of registers */
8378     const ARMCPRegInfo *r;
8379     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8380         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
8381     }
8382 }
8383 
8384 /*
8385  * Modify ARMCPRegInfo for access from userspace.
8386  *
8387  * This is a data driven modification directed by
8388  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8389  * user-space cannot alter any values and dynamic values pertaining to
8390  * execution state are hidden from user space view anyway.
8391  */
8392 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
8393 {
8394     const ARMCPRegUserSpaceInfo *m;
8395     ARMCPRegInfo *r;
8396 
8397     for (m = mods; m->name; m++) {
8398         GPatternSpec *pat = NULL;
8399         if (m->is_glob) {
8400             pat = g_pattern_spec_new(m->name);
8401         }
8402         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8403             if (pat && g_pattern_match_string(pat, r->name)) {
8404                 r->type = ARM_CP_CONST;
8405                 r->access = PL0U_R;
8406                 r->resetvalue = 0;
8407                 /* continue */
8408             } else if (strcmp(r->name, m->name) == 0) {
8409                 r->type = ARM_CP_CONST;
8410                 r->access = PL0U_R;
8411                 r->resetvalue &= m->exported_bits;
8412                 r->resetvalue |= m->fixed_bits;
8413                 break;
8414             }
8415         }
8416         if (pat) {
8417             g_pattern_spec_free(pat);
8418         }
8419     }
8420 }
8421 
8422 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8423 {
8424     return g_hash_table_lookup(cpregs, &encoded_cp);
8425 }
8426 
8427 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8428                          uint64_t value)
8429 {
8430     /* Helper coprocessor write function for write-ignore registers */
8431 }
8432 
8433 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8434 {
8435     /* Helper coprocessor write function for read-as-zero registers */
8436     return 0;
8437 }
8438 
8439 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8440 {
8441     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8442 }
8443 
8444 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8445 {
8446     /* Return true if it is not valid for us to switch to
8447      * this CPU mode (ie all the UNPREDICTABLE cases in
8448      * the ARM ARM CPSRWriteByInstr pseudocode).
8449      */
8450 
8451     /* Changes to or from Hyp via MSR and CPS are illegal. */
8452     if (write_type == CPSRWriteByInstr &&
8453         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8454          mode == ARM_CPU_MODE_HYP)) {
8455         return 1;
8456     }
8457 
8458     switch (mode) {
8459     case ARM_CPU_MODE_USR:
8460         return 0;
8461     case ARM_CPU_MODE_SYS:
8462     case ARM_CPU_MODE_SVC:
8463     case ARM_CPU_MODE_ABT:
8464     case ARM_CPU_MODE_UND:
8465     case ARM_CPU_MODE_IRQ:
8466     case ARM_CPU_MODE_FIQ:
8467         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
8468          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
8469          */
8470         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
8471          * and CPS are treated as illegal mode changes.
8472          */
8473         if (write_type == CPSRWriteByInstr &&
8474             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
8475             (arm_hcr_el2_eff(env) & HCR_TGE)) {
8476             return 1;
8477         }
8478         return 0;
8479     case ARM_CPU_MODE_HYP:
8480         return !arm_feature(env, ARM_FEATURE_EL2)
8481             || arm_current_el(env) < 2 || arm_is_secure_below_el3(env);
8482     case ARM_CPU_MODE_MON:
8483         return arm_current_el(env) < 3;
8484     default:
8485         return 1;
8486     }
8487 }
8488 
8489 uint32_t cpsr_read(CPUARMState *env)
8490 {
8491     int ZF;
8492     ZF = (env->ZF == 0);
8493     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
8494         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
8495         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
8496         | ((env->condexec_bits & 0xfc) << 8)
8497         | (env->GE << 16) | (env->daif & CPSR_AIF);
8498 }
8499 
8500 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
8501                 CPSRWriteType write_type)
8502 {
8503     uint32_t changed_daif;
8504 
8505     if (mask & CPSR_NZCV) {
8506         env->ZF = (~val) & CPSR_Z;
8507         env->NF = val;
8508         env->CF = (val >> 29) & 1;
8509         env->VF = (val << 3) & 0x80000000;
8510     }
8511     if (mask & CPSR_Q)
8512         env->QF = ((val & CPSR_Q) != 0);
8513     if (mask & CPSR_T)
8514         env->thumb = ((val & CPSR_T) != 0);
8515     if (mask & CPSR_IT_0_1) {
8516         env->condexec_bits &= ~3;
8517         env->condexec_bits |= (val >> 25) & 3;
8518     }
8519     if (mask & CPSR_IT_2_7) {
8520         env->condexec_bits &= 3;
8521         env->condexec_bits |= (val >> 8) & 0xfc;
8522     }
8523     if (mask & CPSR_GE) {
8524         env->GE = (val >> 16) & 0xf;
8525     }
8526 
8527     /* In a V7 implementation that includes the security extensions but does
8528      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
8529      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
8530      * bits respectively.
8531      *
8532      * In a V8 implementation, it is permitted for privileged software to
8533      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
8534      */
8535     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
8536         arm_feature(env, ARM_FEATURE_EL3) &&
8537         !arm_feature(env, ARM_FEATURE_EL2) &&
8538         !arm_is_secure(env)) {
8539 
8540         changed_daif = (env->daif ^ val) & mask;
8541 
8542         if (changed_daif & CPSR_A) {
8543             /* Check to see if we are allowed to change the masking of async
8544              * abort exceptions from a non-secure state.
8545              */
8546             if (!(env->cp15.scr_el3 & SCR_AW)) {
8547                 qemu_log_mask(LOG_GUEST_ERROR,
8548                               "Ignoring attempt to switch CPSR_A flag from "
8549                               "non-secure world with SCR.AW bit clear\n");
8550                 mask &= ~CPSR_A;
8551             }
8552         }
8553 
8554         if (changed_daif & CPSR_F) {
8555             /* Check to see if we are allowed to change the masking of FIQ
8556              * exceptions from a non-secure state.
8557              */
8558             if (!(env->cp15.scr_el3 & SCR_FW)) {
8559                 qemu_log_mask(LOG_GUEST_ERROR,
8560                               "Ignoring attempt to switch CPSR_F flag from "
8561                               "non-secure world with SCR.FW bit clear\n");
8562                 mask &= ~CPSR_F;
8563             }
8564 
8565             /* Check whether non-maskable FIQ (NMFI) support is enabled.
8566              * If this bit is set software is not allowed to mask
8567              * FIQs, but is allowed to set CPSR_F to 0.
8568              */
8569             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
8570                 (val & CPSR_F)) {
8571                 qemu_log_mask(LOG_GUEST_ERROR,
8572                               "Ignoring attempt to enable CPSR_F flag "
8573                               "(non-maskable FIQ [NMFI] support enabled)\n");
8574                 mask &= ~CPSR_F;
8575             }
8576         }
8577     }
8578 
8579     env->daif &= ~(CPSR_AIF & mask);
8580     env->daif |= val & CPSR_AIF & mask;
8581 
8582     if (write_type != CPSRWriteRaw &&
8583         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
8584         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
8585             /* Note that we can only get here in USR mode if this is a
8586              * gdb stub write; for this case we follow the architectural
8587              * behaviour for guest writes in USR mode of ignoring an attempt
8588              * to switch mode. (Those are caught by translate.c for writes
8589              * triggered by guest instructions.)
8590              */
8591             mask &= ~CPSR_M;
8592         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
8593             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
8594              * v7, and has defined behaviour in v8:
8595              *  + leave CPSR.M untouched
8596              *  + allow changes to the other CPSR fields
8597              *  + set PSTATE.IL
8598              * For user changes via the GDB stub, we don't set PSTATE.IL,
8599              * as this would be unnecessarily harsh for a user error.
8600              */
8601             mask &= ~CPSR_M;
8602             if (write_type != CPSRWriteByGDBStub &&
8603                 arm_feature(env, ARM_FEATURE_V8)) {
8604                 mask |= CPSR_IL;
8605                 val |= CPSR_IL;
8606             }
8607             qemu_log_mask(LOG_GUEST_ERROR,
8608                           "Illegal AArch32 mode switch attempt from %s to %s\n",
8609                           aarch32_mode_name(env->uncached_cpsr),
8610                           aarch32_mode_name(val));
8611         } else {
8612             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
8613                           write_type == CPSRWriteExceptionReturn ?
8614                           "Exception return from AArch32" :
8615                           "AArch32 mode switch from",
8616                           aarch32_mode_name(env->uncached_cpsr),
8617                           aarch32_mode_name(val), env->regs[15]);
8618             switch_mode(env, val & CPSR_M);
8619         }
8620     }
8621     mask &= ~CACHED_CPSR_BITS;
8622     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
8623 }
8624 
8625 /* Sign/zero extend */
8626 uint32_t HELPER(sxtb16)(uint32_t x)
8627 {
8628     uint32_t res;
8629     res = (uint16_t)(int8_t)x;
8630     res |= (uint32_t)(int8_t)(x >> 16) << 16;
8631     return res;
8632 }
8633 
8634 uint32_t HELPER(uxtb16)(uint32_t x)
8635 {
8636     uint32_t res;
8637     res = (uint16_t)(uint8_t)x;
8638     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
8639     return res;
8640 }
8641 
8642 int32_t HELPER(sdiv)(int32_t num, int32_t den)
8643 {
8644     if (den == 0)
8645       return 0;
8646     if (num == INT_MIN && den == -1)
8647       return INT_MIN;
8648     return num / den;
8649 }
8650 
8651 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
8652 {
8653     if (den == 0)
8654       return 0;
8655     return num / den;
8656 }
8657 
8658 uint32_t HELPER(rbit)(uint32_t x)
8659 {
8660     return revbit32(x);
8661 }
8662 
8663 #ifdef CONFIG_USER_ONLY
8664 
8665 static void switch_mode(CPUARMState *env, int mode)
8666 {
8667     ARMCPU *cpu = env_archcpu(env);
8668 
8669     if (mode != ARM_CPU_MODE_USR) {
8670         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
8671     }
8672 }
8673 
8674 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
8675                                  uint32_t cur_el, bool secure)
8676 {
8677     return 1;
8678 }
8679 
8680 void aarch64_sync_64_to_32(CPUARMState *env)
8681 {
8682     g_assert_not_reached();
8683 }
8684 
8685 #else
8686 
8687 static void switch_mode(CPUARMState *env, int mode)
8688 {
8689     int old_mode;
8690     int i;
8691 
8692     old_mode = env->uncached_cpsr & CPSR_M;
8693     if (mode == old_mode)
8694         return;
8695 
8696     if (old_mode == ARM_CPU_MODE_FIQ) {
8697         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
8698         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
8699     } else if (mode == ARM_CPU_MODE_FIQ) {
8700         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
8701         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
8702     }
8703 
8704     i = bank_number(old_mode);
8705     env->banked_r13[i] = env->regs[13];
8706     env->banked_spsr[i] = env->spsr;
8707 
8708     i = bank_number(mode);
8709     env->regs[13] = env->banked_r13[i];
8710     env->spsr = env->banked_spsr[i];
8711 
8712     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
8713     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
8714 }
8715 
8716 /* Physical Interrupt Target EL Lookup Table
8717  *
8718  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
8719  *
8720  * The below multi-dimensional table is used for looking up the target
8721  * exception level given numerous condition criteria.  Specifically, the
8722  * target EL is based on SCR and HCR routing controls as well as the
8723  * currently executing EL and secure state.
8724  *
8725  *    Dimensions:
8726  *    target_el_table[2][2][2][2][2][4]
8727  *                    |  |  |  |  |  +--- Current EL
8728  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
8729  *                    |  |  |  +--------- HCR mask override
8730  *                    |  |  +------------ SCR exec state control
8731  *                    |  +--------------- SCR mask override
8732  *                    +------------------ 32-bit(0)/64-bit(1) EL3
8733  *
8734  *    The table values are as such:
8735  *    0-3 = EL0-EL3
8736  *     -1 = Cannot occur
8737  *
8738  * The ARM ARM target EL table includes entries indicating that an "exception
8739  * is not taken".  The two cases where this is applicable are:
8740  *    1) An exception is taken from EL3 but the SCR does not have the exception
8741  *    routed to EL3.
8742  *    2) An exception is taken from EL2 but the HCR does not have the exception
8743  *    routed to EL2.
8744  * In these two cases, the below table contain a target of EL1.  This value is
8745  * returned as it is expected that the consumer of the table data will check
8746  * for "target EL >= current EL" to ensure the exception is not taken.
8747  *
8748  *            SCR     HCR
8749  *         64  EA     AMO                 From
8750  *        BIT IRQ     IMO      Non-secure         Secure
8751  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
8752  */
8753 static const int8_t target_el_table[2][2][2][2][2][4] = {
8754     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
8755        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
8756       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
8757        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
8758      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
8759        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
8760       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
8761        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
8762     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
8763        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},
8764       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1, -1,  1 },},
8765        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 1,  1, -1,  1 },},},},
8766      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
8767        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
8768       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
8769        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},},},
8770 };
8771 
8772 /*
8773  * Determine the target EL for physical exceptions
8774  */
8775 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
8776                                  uint32_t cur_el, bool secure)
8777 {
8778     CPUARMState *env = cs->env_ptr;
8779     bool rw;
8780     bool scr;
8781     bool hcr;
8782     int target_el;
8783     /* Is the highest EL AArch64? */
8784     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
8785     uint64_t hcr_el2;
8786 
8787     if (arm_feature(env, ARM_FEATURE_EL3)) {
8788         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
8789     } else {
8790         /* Either EL2 is the highest EL (and so the EL2 register width
8791          * is given by is64); or there is no EL2 or EL3, in which case
8792          * the value of 'rw' does not affect the table lookup anyway.
8793          */
8794         rw = is64;
8795     }
8796 
8797     hcr_el2 = arm_hcr_el2_eff(env);
8798     switch (excp_idx) {
8799     case EXCP_IRQ:
8800         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
8801         hcr = hcr_el2 & HCR_IMO;
8802         break;
8803     case EXCP_FIQ:
8804         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
8805         hcr = hcr_el2 & HCR_FMO;
8806         break;
8807     default:
8808         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
8809         hcr = hcr_el2 & HCR_AMO;
8810         break;
8811     };
8812 
8813     /*
8814      * For these purposes, TGE and AMO/IMO/FMO both force the
8815      * interrupt to EL2.  Fold TGE into the bit extracted above.
8816      */
8817     hcr |= (hcr_el2 & HCR_TGE) != 0;
8818 
8819     /* Perform a table-lookup for the target EL given the current state */
8820     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
8821 
8822     assert(target_el > 0);
8823 
8824     return target_el;
8825 }
8826 
8827 void arm_log_exception(int idx)
8828 {
8829     if (qemu_loglevel_mask(CPU_LOG_INT)) {
8830         const char *exc = NULL;
8831         static const char * const excnames[] = {
8832             [EXCP_UDEF] = "Undefined Instruction",
8833             [EXCP_SWI] = "SVC",
8834             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
8835             [EXCP_DATA_ABORT] = "Data Abort",
8836             [EXCP_IRQ] = "IRQ",
8837             [EXCP_FIQ] = "FIQ",
8838             [EXCP_BKPT] = "Breakpoint",
8839             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
8840             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
8841             [EXCP_HVC] = "Hypervisor Call",
8842             [EXCP_HYP_TRAP] = "Hypervisor Trap",
8843             [EXCP_SMC] = "Secure Monitor Call",
8844             [EXCP_VIRQ] = "Virtual IRQ",
8845             [EXCP_VFIQ] = "Virtual FIQ",
8846             [EXCP_SEMIHOST] = "Semihosting call",
8847             [EXCP_NOCP] = "v7M NOCP UsageFault",
8848             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
8849             [EXCP_STKOF] = "v8M STKOF UsageFault",
8850             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
8851             [EXCP_LSERR] = "v8M LSERR UsageFault",
8852             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
8853         };
8854 
8855         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
8856             exc = excnames[idx];
8857         }
8858         if (!exc) {
8859             exc = "unknown";
8860         }
8861         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
8862     }
8863 }
8864 
8865 /*
8866  * Function used to synchronize QEMU's AArch64 register set with AArch32
8867  * register set.  This is necessary when switching between AArch32 and AArch64
8868  * execution state.
8869  */
8870 void aarch64_sync_32_to_64(CPUARMState *env)
8871 {
8872     int i;
8873     uint32_t mode = env->uncached_cpsr & CPSR_M;
8874 
8875     /* We can blanket copy R[0:7] to X[0:7] */
8876     for (i = 0; i < 8; i++) {
8877         env->xregs[i] = env->regs[i];
8878     }
8879 
8880     /*
8881      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
8882      * Otherwise, they come from the banked user regs.
8883      */
8884     if (mode == ARM_CPU_MODE_FIQ) {
8885         for (i = 8; i < 13; i++) {
8886             env->xregs[i] = env->usr_regs[i - 8];
8887         }
8888     } else {
8889         for (i = 8; i < 13; i++) {
8890             env->xregs[i] = env->regs[i];
8891         }
8892     }
8893 
8894     /*
8895      * Registers x13-x23 are the various mode SP and FP registers. Registers
8896      * r13 and r14 are only copied if we are in that mode, otherwise we copy
8897      * from the mode banked register.
8898      */
8899     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
8900         env->xregs[13] = env->regs[13];
8901         env->xregs[14] = env->regs[14];
8902     } else {
8903         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
8904         /* HYP is an exception in that it is copied from r14 */
8905         if (mode == ARM_CPU_MODE_HYP) {
8906             env->xregs[14] = env->regs[14];
8907         } else {
8908             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
8909         }
8910     }
8911 
8912     if (mode == ARM_CPU_MODE_HYP) {
8913         env->xregs[15] = env->regs[13];
8914     } else {
8915         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
8916     }
8917 
8918     if (mode == ARM_CPU_MODE_IRQ) {
8919         env->xregs[16] = env->regs[14];
8920         env->xregs[17] = env->regs[13];
8921     } else {
8922         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
8923         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
8924     }
8925 
8926     if (mode == ARM_CPU_MODE_SVC) {
8927         env->xregs[18] = env->regs[14];
8928         env->xregs[19] = env->regs[13];
8929     } else {
8930         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
8931         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
8932     }
8933 
8934     if (mode == ARM_CPU_MODE_ABT) {
8935         env->xregs[20] = env->regs[14];
8936         env->xregs[21] = env->regs[13];
8937     } else {
8938         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
8939         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
8940     }
8941 
8942     if (mode == ARM_CPU_MODE_UND) {
8943         env->xregs[22] = env->regs[14];
8944         env->xregs[23] = env->regs[13];
8945     } else {
8946         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
8947         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
8948     }
8949 
8950     /*
8951      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
8952      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
8953      * FIQ bank for r8-r14.
8954      */
8955     if (mode == ARM_CPU_MODE_FIQ) {
8956         for (i = 24; i < 31; i++) {
8957             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
8958         }
8959     } else {
8960         for (i = 24; i < 29; i++) {
8961             env->xregs[i] = env->fiq_regs[i - 24];
8962         }
8963         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
8964         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
8965     }
8966 
8967     env->pc = env->regs[15];
8968 }
8969 
8970 /*
8971  * Function used to synchronize QEMU's AArch32 register set with AArch64
8972  * register set.  This is necessary when switching between AArch32 and AArch64
8973  * execution state.
8974  */
8975 void aarch64_sync_64_to_32(CPUARMState *env)
8976 {
8977     int i;
8978     uint32_t mode = env->uncached_cpsr & CPSR_M;
8979 
8980     /* We can blanket copy X[0:7] to R[0:7] */
8981     for (i = 0; i < 8; i++) {
8982         env->regs[i] = env->xregs[i];
8983     }
8984 
8985     /*
8986      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
8987      * Otherwise, we copy x8-x12 into the banked user regs.
8988      */
8989     if (mode == ARM_CPU_MODE_FIQ) {
8990         for (i = 8; i < 13; i++) {
8991             env->usr_regs[i - 8] = env->xregs[i];
8992         }
8993     } else {
8994         for (i = 8; i < 13; i++) {
8995             env->regs[i] = env->xregs[i];
8996         }
8997     }
8998 
8999     /*
9000      * Registers r13 & r14 depend on the current mode.
9001      * If we are in a given mode, we copy the corresponding x registers to r13
9002      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9003      * for the mode.
9004      */
9005     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9006         env->regs[13] = env->xregs[13];
9007         env->regs[14] = env->xregs[14];
9008     } else {
9009         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9010 
9011         /*
9012          * HYP is an exception in that it does not have its own banked r14 but
9013          * shares the USR r14
9014          */
9015         if (mode == ARM_CPU_MODE_HYP) {
9016             env->regs[14] = env->xregs[14];
9017         } else {
9018             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9019         }
9020     }
9021 
9022     if (mode == ARM_CPU_MODE_HYP) {
9023         env->regs[13] = env->xregs[15];
9024     } else {
9025         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9026     }
9027 
9028     if (mode == ARM_CPU_MODE_IRQ) {
9029         env->regs[14] = env->xregs[16];
9030         env->regs[13] = env->xregs[17];
9031     } else {
9032         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9033         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9034     }
9035 
9036     if (mode == ARM_CPU_MODE_SVC) {
9037         env->regs[14] = env->xregs[18];
9038         env->regs[13] = env->xregs[19];
9039     } else {
9040         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9041         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9042     }
9043 
9044     if (mode == ARM_CPU_MODE_ABT) {
9045         env->regs[14] = env->xregs[20];
9046         env->regs[13] = env->xregs[21];
9047     } else {
9048         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9049         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9050     }
9051 
9052     if (mode == ARM_CPU_MODE_UND) {
9053         env->regs[14] = env->xregs[22];
9054         env->regs[13] = env->xregs[23];
9055     } else {
9056         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9057         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9058     }
9059 
9060     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9061      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9062      * FIQ bank for r8-r14.
9063      */
9064     if (mode == ARM_CPU_MODE_FIQ) {
9065         for (i = 24; i < 31; i++) {
9066             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9067         }
9068     } else {
9069         for (i = 24; i < 29; i++) {
9070             env->fiq_regs[i - 24] = env->xregs[i];
9071         }
9072         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9073         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9074     }
9075 
9076     env->regs[15] = env->pc;
9077 }
9078 
9079 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9080                                    uint32_t mask, uint32_t offset,
9081                                    uint32_t newpc)
9082 {
9083     int new_el;
9084 
9085     /* Change the CPU state so as to actually take the exception. */
9086     switch_mode(env, new_mode);
9087 
9088     /*
9089      * For exceptions taken to AArch32 we must clear the SS bit in both
9090      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9091      */
9092     env->uncached_cpsr &= ~PSTATE_SS;
9093     env->spsr = cpsr_read(env);
9094     /* Clear IT bits.  */
9095     env->condexec_bits = 0;
9096     /* Switch to the new mode, and to the correct instruction set.  */
9097     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9098 
9099     /* This must be after mode switching. */
9100     new_el = arm_current_el(env);
9101 
9102     /* Set new mode endianness */
9103     env->uncached_cpsr &= ~CPSR_E;
9104     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9105         env->uncached_cpsr |= CPSR_E;
9106     }
9107     /* J and IL must always be cleared for exception entry */
9108     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9109     env->daif |= mask;
9110 
9111     if (new_mode == ARM_CPU_MODE_HYP) {
9112         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9113         env->elr_el[2] = env->regs[15];
9114     } else {
9115         /* CPSR.PAN is normally preserved preserved unless...  */
9116         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9117             switch (new_el) {
9118             case 3:
9119                 if (!arm_is_secure_below_el3(env)) {
9120                     /* ... the target is EL3, from non-secure state.  */
9121                     env->uncached_cpsr &= ~CPSR_PAN;
9122                     break;
9123                 }
9124                 /* ... the target is EL3, from secure state ... */
9125                 /* fall through */
9126             case 1:
9127                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9128                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9129                     env->uncached_cpsr |= CPSR_PAN;
9130                 }
9131                 break;
9132             }
9133         }
9134         /*
9135          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9136          * and we should just guard the thumb mode on V4
9137          */
9138         if (arm_feature(env, ARM_FEATURE_V4T)) {
9139             env->thumb =
9140                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9141         }
9142         env->regs[14] = env->regs[15] + offset;
9143     }
9144     env->regs[15] = newpc;
9145     arm_rebuild_hflags(env);
9146 }
9147 
9148 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9149 {
9150     /*
9151      * Handle exception entry to Hyp mode; this is sufficiently
9152      * different to entry to other AArch32 modes that we handle it
9153      * separately here.
9154      *
9155      * The vector table entry used is always the 0x14 Hyp mode entry point,
9156      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
9157      * The offset applied to the preferred return address is always zero
9158      * (see DDI0487C.a section G1.12.3).
9159      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9160      */
9161     uint32_t addr, mask;
9162     ARMCPU *cpu = ARM_CPU(cs);
9163     CPUARMState *env = &cpu->env;
9164 
9165     switch (cs->exception_index) {
9166     case EXCP_UDEF:
9167         addr = 0x04;
9168         break;
9169     case EXCP_SWI:
9170         addr = 0x14;
9171         break;
9172     case EXCP_BKPT:
9173         /* Fall through to prefetch abort.  */
9174     case EXCP_PREFETCH_ABORT:
9175         env->cp15.ifar_s = env->exception.vaddress;
9176         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9177                       (uint32_t)env->exception.vaddress);
9178         addr = 0x0c;
9179         break;
9180     case EXCP_DATA_ABORT:
9181         env->cp15.dfar_s = env->exception.vaddress;
9182         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9183                       (uint32_t)env->exception.vaddress);
9184         addr = 0x10;
9185         break;
9186     case EXCP_IRQ:
9187         addr = 0x18;
9188         break;
9189     case EXCP_FIQ:
9190         addr = 0x1c;
9191         break;
9192     case EXCP_HVC:
9193         addr = 0x08;
9194         break;
9195     case EXCP_HYP_TRAP:
9196         addr = 0x14;
9197         break;
9198     default:
9199         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9200     }
9201 
9202     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9203         if (!arm_feature(env, ARM_FEATURE_V8)) {
9204             /*
9205              * QEMU syndrome values are v8-style. v7 has the IL bit
9206              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9207              * If this is a v7 CPU, squash the IL bit in those cases.
9208              */
9209             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9210                 (cs->exception_index == EXCP_DATA_ABORT &&
9211                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9212                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9213                 env->exception.syndrome &= ~ARM_EL_IL;
9214             }
9215         }
9216         env->cp15.esr_el[2] = env->exception.syndrome;
9217     }
9218 
9219     if (arm_current_el(env) != 2 && addr < 0x14) {
9220         addr = 0x14;
9221     }
9222 
9223     mask = 0;
9224     if (!(env->cp15.scr_el3 & SCR_EA)) {
9225         mask |= CPSR_A;
9226     }
9227     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9228         mask |= CPSR_I;
9229     }
9230     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9231         mask |= CPSR_F;
9232     }
9233 
9234     addr += env->cp15.hvbar;
9235 
9236     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9237 }
9238 
9239 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9240 {
9241     ARMCPU *cpu = ARM_CPU(cs);
9242     CPUARMState *env = &cpu->env;
9243     uint32_t addr;
9244     uint32_t mask;
9245     int new_mode;
9246     uint32_t offset;
9247     uint32_t moe;
9248 
9249     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9250     switch (syn_get_ec(env->exception.syndrome)) {
9251     case EC_BREAKPOINT:
9252     case EC_BREAKPOINT_SAME_EL:
9253         moe = 1;
9254         break;
9255     case EC_WATCHPOINT:
9256     case EC_WATCHPOINT_SAME_EL:
9257         moe = 10;
9258         break;
9259     case EC_AA32_BKPT:
9260         moe = 3;
9261         break;
9262     case EC_VECTORCATCH:
9263         moe = 5;
9264         break;
9265     default:
9266         moe = 0;
9267         break;
9268     }
9269 
9270     if (moe) {
9271         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9272     }
9273 
9274     if (env->exception.target_el == 2) {
9275         arm_cpu_do_interrupt_aarch32_hyp(cs);
9276         return;
9277     }
9278 
9279     switch (cs->exception_index) {
9280     case EXCP_UDEF:
9281         new_mode = ARM_CPU_MODE_UND;
9282         addr = 0x04;
9283         mask = CPSR_I;
9284         if (env->thumb)
9285             offset = 2;
9286         else
9287             offset = 4;
9288         break;
9289     case EXCP_SWI:
9290         new_mode = ARM_CPU_MODE_SVC;
9291         addr = 0x08;
9292         mask = CPSR_I;
9293         /* The PC already points to the next instruction.  */
9294         offset = 0;
9295         break;
9296     case EXCP_BKPT:
9297         /* Fall through to prefetch abort.  */
9298     case EXCP_PREFETCH_ABORT:
9299         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9300         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9301         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9302                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9303         new_mode = ARM_CPU_MODE_ABT;
9304         addr = 0x0c;
9305         mask = CPSR_A | CPSR_I;
9306         offset = 4;
9307         break;
9308     case EXCP_DATA_ABORT:
9309         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9310         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9311         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9312                       env->exception.fsr,
9313                       (uint32_t)env->exception.vaddress);
9314         new_mode = ARM_CPU_MODE_ABT;
9315         addr = 0x10;
9316         mask = CPSR_A | CPSR_I;
9317         offset = 8;
9318         break;
9319     case EXCP_IRQ:
9320         new_mode = ARM_CPU_MODE_IRQ;
9321         addr = 0x18;
9322         /* Disable IRQ and imprecise data aborts.  */
9323         mask = CPSR_A | CPSR_I;
9324         offset = 4;
9325         if (env->cp15.scr_el3 & SCR_IRQ) {
9326             /* IRQ routed to monitor mode */
9327             new_mode = ARM_CPU_MODE_MON;
9328             mask |= CPSR_F;
9329         }
9330         break;
9331     case EXCP_FIQ:
9332         new_mode = ARM_CPU_MODE_FIQ;
9333         addr = 0x1c;
9334         /* Disable FIQ, IRQ and imprecise data aborts.  */
9335         mask = CPSR_A | CPSR_I | CPSR_F;
9336         if (env->cp15.scr_el3 & SCR_FIQ) {
9337             /* FIQ routed to monitor mode */
9338             new_mode = ARM_CPU_MODE_MON;
9339         }
9340         offset = 4;
9341         break;
9342     case EXCP_VIRQ:
9343         new_mode = ARM_CPU_MODE_IRQ;
9344         addr = 0x18;
9345         /* Disable IRQ and imprecise data aborts.  */
9346         mask = CPSR_A | CPSR_I;
9347         offset = 4;
9348         break;
9349     case EXCP_VFIQ:
9350         new_mode = ARM_CPU_MODE_FIQ;
9351         addr = 0x1c;
9352         /* Disable FIQ, IRQ and imprecise data aborts.  */
9353         mask = CPSR_A | CPSR_I | CPSR_F;
9354         offset = 4;
9355         break;
9356     case EXCP_SMC:
9357         new_mode = ARM_CPU_MODE_MON;
9358         addr = 0x08;
9359         mask = CPSR_A | CPSR_I | CPSR_F;
9360         offset = 0;
9361         break;
9362     default:
9363         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9364         return; /* Never happens.  Keep compiler happy.  */
9365     }
9366 
9367     if (new_mode == ARM_CPU_MODE_MON) {
9368         addr += env->cp15.mvbar;
9369     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9370         /* High vectors. When enabled, base address cannot be remapped. */
9371         addr += 0xffff0000;
9372     } else {
9373         /* ARM v7 architectures provide a vector base address register to remap
9374          * the interrupt vector table.
9375          * This register is only followed in non-monitor mode, and is banked.
9376          * Note: only bits 31:5 are valid.
9377          */
9378         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9379     }
9380 
9381     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9382         env->cp15.scr_el3 &= ~SCR_NS;
9383     }
9384 
9385     take_aarch32_exception(env, new_mode, mask, offset, addr);
9386 }
9387 
9388 /* Handle exception entry to a target EL which is using AArch64 */
9389 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
9390 {
9391     ARMCPU *cpu = ARM_CPU(cs);
9392     CPUARMState *env = &cpu->env;
9393     unsigned int new_el = env->exception.target_el;
9394     target_ulong addr = env->cp15.vbar_el[new_el];
9395     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
9396     unsigned int old_mode;
9397     unsigned int cur_el = arm_current_el(env);
9398 
9399     /*
9400      * Note that new_el can never be 0.  If cur_el is 0, then
9401      * el0_a64 is is_a64(), else el0_a64 is ignored.
9402      */
9403     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
9404 
9405     if (cur_el < new_el) {
9406         /* Entry vector offset depends on whether the implemented EL
9407          * immediately lower than the target level is using AArch32 or AArch64
9408          */
9409         bool is_aa64;
9410         uint64_t hcr;
9411 
9412         switch (new_el) {
9413         case 3:
9414             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
9415             break;
9416         case 2:
9417             hcr = arm_hcr_el2_eff(env);
9418             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
9419                 is_aa64 = (hcr & HCR_RW) != 0;
9420                 break;
9421             }
9422             /* fall through */
9423         case 1:
9424             is_aa64 = is_a64(env);
9425             break;
9426         default:
9427             g_assert_not_reached();
9428         }
9429 
9430         if (is_aa64) {
9431             addr += 0x400;
9432         } else {
9433             addr += 0x600;
9434         }
9435     } else if (pstate_read(env) & PSTATE_SP) {
9436         addr += 0x200;
9437     }
9438 
9439     switch (cs->exception_index) {
9440     case EXCP_PREFETCH_ABORT:
9441     case EXCP_DATA_ABORT:
9442         env->cp15.far_el[new_el] = env->exception.vaddress;
9443         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
9444                       env->cp15.far_el[new_el]);
9445         /* fall through */
9446     case EXCP_BKPT:
9447     case EXCP_UDEF:
9448     case EXCP_SWI:
9449     case EXCP_HVC:
9450     case EXCP_HYP_TRAP:
9451     case EXCP_SMC:
9452         if (syn_get_ec(env->exception.syndrome) == EC_ADVSIMDFPACCESSTRAP) {
9453             /*
9454              * QEMU internal FP/SIMD syndromes from AArch32 include the
9455              * TA and coproc fields which are only exposed if the exception
9456              * is taken to AArch32 Hyp mode. Mask them out to get a valid
9457              * AArch64 format syndrome.
9458              */
9459             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
9460         }
9461         env->cp15.esr_el[new_el] = env->exception.syndrome;
9462         break;
9463     case EXCP_IRQ:
9464     case EXCP_VIRQ:
9465         addr += 0x80;
9466         break;
9467     case EXCP_FIQ:
9468     case EXCP_VFIQ:
9469         addr += 0x100;
9470         break;
9471     default:
9472         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9473     }
9474 
9475     if (is_a64(env)) {
9476         old_mode = pstate_read(env);
9477         aarch64_save_sp(env, arm_current_el(env));
9478         env->elr_el[new_el] = env->pc;
9479     } else {
9480         old_mode = cpsr_read(env);
9481         env->elr_el[new_el] = env->regs[15];
9482 
9483         aarch64_sync_32_to_64(env);
9484 
9485         env->condexec_bits = 0;
9486     }
9487     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
9488 
9489     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
9490                   env->elr_el[new_el]);
9491 
9492     if (cpu_isar_feature(aa64_pan, cpu)) {
9493         /* The value of PSTATE.PAN is normally preserved, except when ... */
9494         new_mode |= old_mode & PSTATE_PAN;
9495         switch (new_el) {
9496         case 2:
9497             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
9498             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
9499                 != (HCR_E2H | HCR_TGE)) {
9500                 break;
9501             }
9502             /* fall through */
9503         case 1:
9504             /* ... the target is EL1 ... */
9505             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
9506             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
9507                 new_mode |= PSTATE_PAN;
9508             }
9509             break;
9510         }
9511     }
9512 
9513     pstate_write(env, PSTATE_DAIF | new_mode);
9514     env->aarch64 = 1;
9515     aarch64_restore_sp(env, new_el);
9516     helper_rebuild_hflags_a64(env, new_el);
9517 
9518     env->pc = addr;
9519 
9520     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
9521                   new_el, env->pc, pstate_read(env));
9522 }
9523 
9524 /*
9525  * Do semihosting call and set the appropriate return value. All the
9526  * permission and validity checks have been done at translate time.
9527  *
9528  * We only see semihosting exceptions in TCG only as they are not
9529  * trapped to the hypervisor in KVM.
9530  */
9531 #ifdef CONFIG_TCG
9532 static void handle_semihosting(CPUState *cs)
9533 {
9534     ARMCPU *cpu = ARM_CPU(cs);
9535     CPUARMState *env = &cpu->env;
9536 
9537     if (is_a64(env)) {
9538         qemu_log_mask(CPU_LOG_INT,
9539                       "...handling as semihosting call 0x%" PRIx64 "\n",
9540                       env->xregs[0]);
9541         env->xregs[0] = do_arm_semihosting(env);
9542         env->pc += 4;
9543     } else {
9544         qemu_log_mask(CPU_LOG_INT,
9545                       "...handling as semihosting call 0x%x\n",
9546                       env->regs[0]);
9547         env->regs[0] = do_arm_semihosting(env);
9548         env->regs[15] += env->thumb ? 2 : 4;
9549     }
9550 }
9551 #endif
9552 
9553 /* Handle a CPU exception for A and R profile CPUs.
9554  * Do any appropriate logging, handle PSCI calls, and then hand off
9555  * to the AArch64-entry or AArch32-entry function depending on the
9556  * target exception level's register width.
9557  */
9558 void arm_cpu_do_interrupt(CPUState *cs)
9559 {
9560     ARMCPU *cpu = ARM_CPU(cs);
9561     CPUARMState *env = &cpu->env;
9562     unsigned int new_el = env->exception.target_el;
9563 
9564     assert(!arm_feature(env, ARM_FEATURE_M));
9565 
9566     arm_log_exception(cs->exception_index);
9567     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
9568                   new_el);
9569     if (qemu_loglevel_mask(CPU_LOG_INT)
9570         && !excp_is_internal(cs->exception_index)) {
9571         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
9572                       syn_get_ec(env->exception.syndrome),
9573                       env->exception.syndrome);
9574     }
9575 
9576     if (arm_is_psci_call(cpu, cs->exception_index)) {
9577         arm_handle_psci_call(cpu);
9578         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
9579         return;
9580     }
9581 
9582     /*
9583      * Semihosting semantics depend on the register width of the code
9584      * that caused the exception, not the target exception level, so
9585      * must be handled here.
9586      */
9587 #ifdef CONFIG_TCG
9588     if (cs->exception_index == EXCP_SEMIHOST) {
9589         handle_semihosting(cs);
9590         return;
9591     }
9592 #endif
9593 
9594     /* Hooks may change global state so BQL should be held, also the
9595      * BQL needs to be held for any modification of
9596      * cs->interrupt_request.
9597      */
9598     g_assert(qemu_mutex_iothread_locked());
9599 
9600     arm_call_pre_el_change_hook(cpu);
9601 
9602     assert(!excp_is_internal(cs->exception_index));
9603     if (arm_el_is_aa64(env, new_el)) {
9604         arm_cpu_do_interrupt_aarch64(cs);
9605     } else {
9606         arm_cpu_do_interrupt_aarch32(cs);
9607     }
9608 
9609     arm_call_el_change_hook(cpu);
9610 
9611     if (!kvm_enabled()) {
9612         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
9613     }
9614 }
9615 #endif /* !CONFIG_USER_ONLY */
9616 
9617 /* Return the exception level which controls this address translation regime */
9618 static uint32_t regime_el(CPUARMState *env, ARMMMUIdx mmu_idx)
9619 {
9620     switch (mmu_idx) {
9621     case ARMMMUIdx_E20_0:
9622     case ARMMMUIdx_E20_2:
9623     case ARMMMUIdx_E20_2_PAN:
9624     case ARMMMUIdx_Stage2:
9625     case ARMMMUIdx_E2:
9626         return 2;
9627     case ARMMMUIdx_SE3:
9628         return 3;
9629     case ARMMMUIdx_SE10_0:
9630         return arm_el_is_aa64(env, 3) ? 1 : 3;
9631     case ARMMMUIdx_SE10_1:
9632     case ARMMMUIdx_SE10_1_PAN:
9633     case ARMMMUIdx_Stage1_E0:
9634     case ARMMMUIdx_Stage1_E1:
9635     case ARMMMUIdx_Stage1_E1_PAN:
9636     case ARMMMUIdx_E10_0:
9637     case ARMMMUIdx_E10_1:
9638     case ARMMMUIdx_E10_1_PAN:
9639     case ARMMMUIdx_MPrivNegPri:
9640     case ARMMMUIdx_MUserNegPri:
9641     case ARMMMUIdx_MPriv:
9642     case ARMMMUIdx_MUser:
9643     case ARMMMUIdx_MSPrivNegPri:
9644     case ARMMMUIdx_MSUserNegPri:
9645     case ARMMMUIdx_MSPriv:
9646     case ARMMMUIdx_MSUser:
9647         return 1;
9648     default:
9649         g_assert_not_reached();
9650     }
9651 }
9652 
9653 uint64_t arm_sctlr(CPUARMState *env, int el)
9654 {
9655     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
9656     if (el == 0) {
9657         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
9658         el = (mmu_idx == ARMMMUIdx_E20_0 ? 2 : 1);
9659     }
9660     return env->cp15.sctlr_el[el];
9661 }
9662 
9663 /* Return the SCTLR value which controls this address translation regime */
9664 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
9665 {
9666     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
9667 }
9668 
9669 #ifndef CONFIG_USER_ONLY
9670 
9671 /* Return true if the specified stage of address translation is disabled */
9672 static inline bool regime_translation_disabled(CPUARMState *env,
9673                                                ARMMMUIdx mmu_idx)
9674 {
9675     if (arm_feature(env, ARM_FEATURE_M)) {
9676         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
9677                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
9678         case R_V7M_MPU_CTRL_ENABLE_MASK:
9679             /* Enabled, but not for HardFault and NMI */
9680             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
9681         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
9682             /* Enabled for all cases */
9683             return false;
9684         case 0:
9685         default:
9686             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
9687              * we warned about that in armv7m_nvic.c when the guest set it.
9688              */
9689             return true;
9690         }
9691     }
9692 
9693     if (mmu_idx == ARMMMUIdx_Stage2) {
9694         /* HCR.DC means HCR.VM behaves as 1 */
9695         return (env->cp15.hcr_el2 & (HCR_DC | HCR_VM)) == 0;
9696     }
9697 
9698     if (env->cp15.hcr_el2 & HCR_TGE) {
9699         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
9700         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
9701             return true;
9702         }
9703     }
9704 
9705     if ((env->cp15.hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
9706         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
9707         return true;
9708     }
9709 
9710     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
9711 }
9712 
9713 static inline bool regime_translation_big_endian(CPUARMState *env,
9714                                                  ARMMMUIdx mmu_idx)
9715 {
9716     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
9717 }
9718 
9719 /* Return the TTBR associated with this translation regime */
9720 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
9721                                    int ttbrn)
9722 {
9723     if (mmu_idx == ARMMMUIdx_Stage2) {
9724         return env->cp15.vttbr_el2;
9725     }
9726     if (ttbrn == 0) {
9727         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
9728     } else {
9729         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
9730     }
9731 }
9732 
9733 #endif /* !CONFIG_USER_ONLY */
9734 
9735 /* Return the TCR controlling this translation regime */
9736 static inline TCR *regime_tcr(CPUARMState *env, ARMMMUIdx mmu_idx)
9737 {
9738     if (mmu_idx == ARMMMUIdx_Stage2) {
9739         return &env->cp15.vtcr_el2;
9740     }
9741     return &env->cp15.tcr_el[regime_el(env, mmu_idx)];
9742 }
9743 
9744 /* Convert a possible stage1+2 MMU index into the appropriate
9745  * stage 1 MMU index
9746  */
9747 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
9748 {
9749     switch (mmu_idx) {
9750     case ARMMMUIdx_E10_0:
9751         return ARMMMUIdx_Stage1_E0;
9752     case ARMMMUIdx_E10_1:
9753         return ARMMMUIdx_Stage1_E1;
9754     case ARMMMUIdx_E10_1_PAN:
9755         return ARMMMUIdx_Stage1_E1_PAN;
9756     default:
9757         return mmu_idx;
9758     }
9759 }
9760 
9761 /* Return true if the translation regime is using LPAE format page tables */
9762 static inline bool regime_using_lpae_format(CPUARMState *env,
9763                                             ARMMMUIdx mmu_idx)
9764 {
9765     int el = regime_el(env, mmu_idx);
9766     if (el == 2 || arm_el_is_aa64(env, el)) {
9767         return true;
9768     }
9769     if (arm_feature(env, ARM_FEATURE_LPAE)
9770         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
9771         return true;
9772     }
9773     return false;
9774 }
9775 
9776 /* Returns true if the stage 1 translation regime is using LPAE format page
9777  * tables. Used when raising alignment exceptions, whose FSR changes depending
9778  * on whether the long or short descriptor format is in use. */
9779 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
9780 {
9781     mmu_idx = stage_1_mmu_idx(mmu_idx);
9782 
9783     return regime_using_lpae_format(env, mmu_idx);
9784 }
9785 
9786 #ifndef CONFIG_USER_ONLY
9787 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
9788 {
9789     switch (mmu_idx) {
9790     case ARMMMUIdx_SE10_0:
9791     case ARMMMUIdx_E20_0:
9792     case ARMMMUIdx_Stage1_E0:
9793     case ARMMMUIdx_MUser:
9794     case ARMMMUIdx_MSUser:
9795     case ARMMMUIdx_MUserNegPri:
9796     case ARMMMUIdx_MSUserNegPri:
9797         return true;
9798     default:
9799         return false;
9800     case ARMMMUIdx_E10_0:
9801     case ARMMMUIdx_E10_1:
9802     case ARMMMUIdx_E10_1_PAN:
9803         g_assert_not_reached();
9804     }
9805 }
9806 
9807 /* Translate section/page access permissions to page
9808  * R/W protection flags
9809  *
9810  * @env:         CPUARMState
9811  * @mmu_idx:     MMU index indicating required translation regime
9812  * @ap:          The 3-bit access permissions (AP[2:0])
9813  * @domain_prot: The 2-bit domain access permissions
9814  */
9815 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
9816                                 int ap, int domain_prot)
9817 {
9818     bool is_user = regime_is_user(env, mmu_idx);
9819 
9820     if (domain_prot == 3) {
9821         return PAGE_READ | PAGE_WRITE;
9822     }
9823 
9824     switch (ap) {
9825     case 0:
9826         if (arm_feature(env, ARM_FEATURE_V7)) {
9827             return 0;
9828         }
9829         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
9830         case SCTLR_S:
9831             return is_user ? 0 : PAGE_READ;
9832         case SCTLR_R:
9833             return PAGE_READ;
9834         default:
9835             return 0;
9836         }
9837     case 1:
9838         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
9839     case 2:
9840         if (is_user) {
9841             return PAGE_READ;
9842         } else {
9843             return PAGE_READ | PAGE_WRITE;
9844         }
9845     case 3:
9846         return PAGE_READ | PAGE_WRITE;
9847     case 4: /* Reserved.  */
9848         return 0;
9849     case 5:
9850         return is_user ? 0 : PAGE_READ;
9851     case 6:
9852         return PAGE_READ;
9853     case 7:
9854         if (!arm_feature(env, ARM_FEATURE_V6K)) {
9855             return 0;
9856         }
9857         return PAGE_READ;
9858     default:
9859         g_assert_not_reached();
9860     }
9861 }
9862 
9863 /* Translate section/page access permissions to page
9864  * R/W protection flags.
9865  *
9866  * @ap:      The 2-bit simple AP (AP[2:1])
9867  * @is_user: TRUE if accessing from PL0
9868  */
9869 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
9870 {
9871     switch (ap) {
9872     case 0:
9873         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
9874     case 1:
9875         return PAGE_READ | PAGE_WRITE;
9876     case 2:
9877         return is_user ? 0 : PAGE_READ;
9878     case 3:
9879         return PAGE_READ;
9880     default:
9881         g_assert_not_reached();
9882     }
9883 }
9884 
9885 static inline int
9886 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
9887 {
9888     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
9889 }
9890 
9891 /* Translate S2 section/page access permissions to protection flags
9892  *
9893  * @env:     CPUARMState
9894  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
9895  * @xn:      XN (execute-never) bits
9896  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
9897  */
9898 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
9899 {
9900     int prot = 0;
9901 
9902     if (s2ap & 1) {
9903         prot |= PAGE_READ;
9904     }
9905     if (s2ap & 2) {
9906         prot |= PAGE_WRITE;
9907     }
9908 
9909     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
9910         switch (xn) {
9911         case 0:
9912             prot |= PAGE_EXEC;
9913             break;
9914         case 1:
9915             if (s1_is_el0) {
9916                 prot |= PAGE_EXEC;
9917             }
9918             break;
9919         case 2:
9920             break;
9921         case 3:
9922             if (!s1_is_el0) {
9923                 prot |= PAGE_EXEC;
9924             }
9925             break;
9926         default:
9927             g_assert_not_reached();
9928         }
9929     } else {
9930         if (!extract32(xn, 1, 1)) {
9931             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
9932                 prot |= PAGE_EXEC;
9933             }
9934         }
9935     }
9936     return prot;
9937 }
9938 
9939 /* Translate section/page access permissions to protection flags
9940  *
9941  * @env:     CPUARMState
9942  * @mmu_idx: MMU index indicating required translation regime
9943  * @is_aa64: TRUE if AArch64
9944  * @ap:      The 2-bit simple AP (AP[2:1])
9945  * @ns:      NS (non-secure) bit
9946  * @xn:      XN (execute-never) bit
9947  * @pxn:     PXN (privileged execute-never) bit
9948  */
9949 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
9950                       int ap, int ns, int xn, int pxn)
9951 {
9952     bool is_user = regime_is_user(env, mmu_idx);
9953     int prot_rw, user_rw;
9954     bool have_wxn;
9955     int wxn = 0;
9956 
9957     assert(mmu_idx != ARMMMUIdx_Stage2);
9958 
9959     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
9960     if (is_user) {
9961         prot_rw = user_rw;
9962     } else {
9963         if (user_rw && regime_is_pan(env, mmu_idx)) {
9964             /* PAN forbids data accesses but doesn't affect insn fetch */
9965             prot_rw = 0;
9966         } else {
9967             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
9968         }
9969     }
9970 
9971     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
9972         return prot_rw;
9973     }
9974 
9975     /* TODO have_wxn should be replaced with
9976      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
9977      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
9978      * compatible processors have EL2, which is required for [U]WXN.
9979      */
9980     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
9981 
9982     if (have_wxn) {
9983         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
9984     }
9985 
9986     if (is_aa64) {
9987         if (regime_has_2_ranges(mmu_idx) && !is_user) {
9988             xn = pxn || (user_rw & PAGE_WRITE);
9989         }
9990     } else if (arm_feature(env, ARM_FEATURE_V7)) {
9991         switch (regime_el(env, mmu_idx)) {
9992         case 1:
9993         case 3:
9994             if (is_user) {
9995                 xn = xn || !(user_rw & PAGE_READ);
9996             } else {
9997                 int uwxn = 0;
9998                 if (have_wxn) {
9999                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10000                 }
10001                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10002                      (uwxn && (user_rw & PAGE_WRITE));
10003             }
10004             break;
10005         case 2:
10006             break;
10007         }
10008     } else {
10009         xn = wxn = 0;
10010     }
10011 
10012     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10013         return prot_rw;
10014     }
10015     return prot_rw | PAGE_EXEC;
10016 }
10017 
10018 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10019                                      uint32_t *table, uint32_t address)
10020 {
10021     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10022     TCR *tcr = regime_tcr(env, mmu_idx);
10023 
10024     if (address & tcr->mask) {
10025         if (tcr->raw_tcr & TTBCR_PD1) {
10026             /* Translation table walk disabled for TTBR1 */
10027             return false;
10028         }
10029         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10030     } else {
10031         if (tcr->raw_tcr & TTBCR_PD0) {
10032             /* Translation table walk disabled for TTBR0 */
10033             return false;
10034         }
10035         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10036     }
10037     *table |= (address >> 18) & 0x3ffc;
10038     return true;
10039 }
10040 
10041 /* Translate a S1 pagetable walk through S2 if needed.  */
10042 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10043                                hwaddr addr, MemTxAttrs txattrs,
10044                                ARMMMUFaultInfo *fi)
10045 {
10046     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10047         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10048         target_ulong s2size;
10049         hwaddr s2pa;
10050         int s2prot;
10051         int ret;
10052         ARMCacheAttrs cacheattrs = {};
10053         ARMCacheAttrs *pcacheattrs = NULL;
10054 
10055         if (env->cp15.hcr_el2 & HCR_PTW) {
10056             /*
10057              * PTW means we must fault if this S1 walk touches S2 Device
10058              * memory; otherwise we don't care about the attributes and can
10059              * save the S2 translation the effort of computing them.
10060              */
10061             pcacheattrs = &cacheattrs;
10062         }
10063 
10064         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, ARMMMUIdx_Stage2,
10065                                  false,
10066                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10067                                  pcacheattrs);
10068         if (ret) {
10069             assert(fi->type != ARMFault_None);
10070             fi->s2addr = addr;
10071             fi->stage2 = true;
10072             fi->s1ptw = true;
10073             return ~0;
10074         }
10075         if (pcacheattrs && (pcacheattrs->attrs & 0xf0) == 0) {
10076             /* Access was to Device memory: generate Permission fault */
10077             fi->type = ARMFault_Permission;
10078             fi->s2addr = addr;
10079             fi->stage2 = true;
10080             fi->s1ptw = true;
10081             return ~0;
10082         }
10083         addr = s2pa;
10084     }
10085     return addr;
10086 }
10087 
10088 /* All loads done in the course of a page table walk go through here. */
10089 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10090                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10091 {
10092     ARMCPU *cpu = ARM_CPU(cs);
10093     CPUARMState *env = &cpu->env;
10094     MemTxAttrs attrs = {};
10095     MemTxResult result = MEMTX_OK;
10096     AddressSpace *as;
10097     uint32_t data;
10098 
10099     attrs.secure = is_secure;
10100     as = arm_addressspace(cs, attrs);
10101     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10102     if (fi->s1ptw) {
10103         return 0;
10104     }
10105     if (regime_translation_big_endian(env, mmu_idx)) {
10106         data = address_space_ldl_be(as, addr, attrs, &result);
10107     } else {
10108         data = address_space_ldl_le(as, addr, attrs, &result);
10109     }
10110     if (result == MEMTX_OK) {
10111         return data;
10112     }
10113     fi->type = ARMFault_SyncExternalOnWalk;
10114     fi->ea = arm_extabort_type(result);
10115     return 0;
10116 }
10117 
10118 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10119                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10120 {
10121     ARMCPU *cpu = ARM_CPU(cs);
10122     CPUARMState *env = &cpu->env;
10123     MemTxAttrs attrs = {};
10124     MemTxResult result = MEMTX_OK;
10125     AddressSpace *as;
10126     uint64_t data;
10127 
10128     attrs.secure = is_secure;
10129     as = arm_addressspace(cs, attrs);
10130     addr = S1_ptw_translate(env, mmu_idx, addr, attrs, fi);
10131     if (fi->s1ptw) {
10132         return 0;
10133     }
10134     if (regime_translation_big_endian(env, mmu_idx)) {
10135         data = address_space_ldq_be(as, addr, attrs, &result);
10136     } else {
10137         data = address_space_ldq_le(as, addr, attrs, &result);
10138     }
10139     if (result == MEMTX_OK) {
10140         return data;
10141     }
10142     fi->type = ARMFault_SyncExternalOnWalk;
10143     fi->ea = arm_extabort_type(result);
10144     return 0;
10145 }
10146 
10147 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10148                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10149                              hwaddr *phys_ptr, int *prot,
10150                              target_ulong *page_size,
10151                              ARMMMUFaultInfo *fi)
10152 {
10153     CPUState *cs = env_cpu(env);
10154     int level = 1;
10155     uint32_t table;
10156     uint32_t desc;
10157     int type;
10158     int ap;
10159     int domain = 0;
10160     int domain_prot;
10161     hwaddr phys_addr;
10162     uint32_t dacr;
10163 
10164     /* Pagetable walk.  */
10165     /* Lookup l1 descriptor.  */
10166     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10167         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10168         fi->type = ARMFault_Translation;
10169         goto do_fault;
10170     }
10171     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10172                        mmu_idx, fi);
10173     if (fi->type != ARMFault_None) {
10174         goto do_fault;
10175     }
10176     type = (desc & 3);
10177     domain = (desc >> 5) & 0x0f;
10178     if (regime_el(env, mmu_idx) == 1) {
10179         dacr = env->cp15.dacr_ns;
10180     } else {
10181         dacr = env->cp15.dacr_s;
10182     }
10183     domain_prot = (dacr >> (domain * 2)) & 3;
10184     if (type == 0) {
10185         /* Section translation fault.  */
10186         fi->type = ARMFault_Translation;
10187         goto do_fault;
10188     }
10189     if (type != 2) {
10190         level = 2;
10191     }
10192     if (domain_prot == 0 || domain_prot == 2) {
10193         fi->type = ARMFault_Domain;
10194         goto do_fault;
10195     }
10196     if (type == 2) {
10197         /* 1Mb section.  */
10198         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10199         ap = (desc >> 10) & 3;
10200         *page_size = 1024 * 1024;
10201     } else {
10202         /* Lookup l2 entry.  */
10203         if (type == 1) {
10204             /* Coarse pagetable.  */
10205             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10206         } else {
10207             /* Fine pagetable.  */
10208             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10209         }
10210         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10211                            mmu_idx, fi);
10212         if (fi->type != ARMFault_None) {
10213             goto do_fault;
10214         }
10215         switch (desc & 3) {
10216         case 0: /* Page translation fault.  */
10217             fi->type = ARMFault_Translation;
10218             goto do_fault;
10219         case 1: /* 64k page.  */
10220             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10221             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10222             *page_size = 0x10000;
10223             break;
10224         case 2: /* 4k page.  */
10225             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10226             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10227             *page_size = 0x1000;
10228             break;
10229         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10230             if (type == 1) {
10231                 /* ARMv6/XScale extended small page format */
10232                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10233                     || arm_feature(env, ARM_FEATURE_V6)) {
10234                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10235                     *page_size = 0x1000;
10236                 } else {
10237                     /* UNPREDICTABLE in ARMv5; we choose to take a
10238                      * page translation fault.
10239                      */
10240                     fi->type = ARMFault_Translation;
10241                     goto do_fault;
10242                 }
10243             } else {
10244                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10245                 *page_size = 0x400;
10246             }
10247             ap = (desc >> 4) & 3;
10248             break;
10249         default:
10250             /* Never happens, but compiler isn't smart enough to tell.  */
10251             abort();
10252         }
10253     }
10254     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10255     *prot |= *prot ? PAGE_EXEC : 0;
10256     if (!(*prot & (1 << access_type))) {
10257         /* Access permission fault.  */
10258         fi->type = ARMFault_Permission;
10259         goto do_fault;
10260     }
10261     *phys_ptr = phys_addr;
10262     return false;
10263 do_fault:
10264     fi->domain = domain;
10265     fi->level = level;
10266     return true;
10267 }
10268 
10269 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10270                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10271                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10272                              target_ulong *page_size, ARMMMUFaultInfo *fi)
10273 {
10274     CPUState *cs = env_cpu(env);
10275     int level = 1;
10276     uint32_t table;
10277     uint32_t desc;
10278     uint32_t xn;
10279     uint32_t pxn = 0;
10280     int type;
10281     int ap;
10282     int domain = 0;
10283     int domain_prot;
10284     hwaddr phys_addr;
10285     uint32_t dacr;
10286     bool ns;
10287 
10288     /* Pagetable walk.  */
10289     /* Lookup l1 descriptor.  */
10290     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10291         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10292         fi->type = ARMFault_Translation;
10293         goto do_fault;
10294     }
10295     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10296                        mmu_idx, fi);
10297     if (fi->type != ARMFault_None) {
10298         goto do_fault;
10299     }
10300     type = (desc & 3);
10301     if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {
10302         /* Section translation fault, or attempt to use the encoding
10303          * which is Reserved on implementations without PXN.
10304          */
10305         fi->type = ARMFault_Translation;
10306         goto do_fault;
10307     }
10308     if ((type == 1) || !(desc & (1 << 18))) {
10309         /* Page or Section.  */
10310         domain = (desc >> 5) & 0x0f;
10311     }
10312     if (regime_el(env, mmu_idx) == 1) {
10313         dacr = env->cp15.dacr_ns;
10314     } else {
10315         dacr = env->cp15.dacr_s;
10316     }
10317     if (type == 1) {
10318         level = 2;
10319     }
10320     domain_prot = (dacr >> (domain * 2)) & 3;
10321     if (domain_prot == 0 || domain_prot == 2) {
10322         /* Section or Page domain fault */
10323         fi->type = ARMFault_Domain;
10324         goto do_fault;
10325     }
10326     if (type != 1) {
10327         if (desc & (1 << 18)) {
10328             /* Supersection.  */
10329             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
10330             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
10331             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
10332             *page_size = 0x1000000;
10333         } else {
10334             /* Section.  */
10335             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10336             *page_size = 0x100000;
10337         }
10338         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
10339         xn = desc & (1 << 4);
10340         pxn = desc & 1;
10341         ns = extract32(desc, 19, 1);
10342     } else {
10343         if (arm_feature(env, ARM_FEATURE_PXN)) {
10344             pxn = (desc >> 2) & 1;
10345         }
10346         ns = extract32(desc, 3, 1);
10347         /* Lookup l2 entry.  */
10348         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10349         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10350                            mmu_idx, fi);
10351         if (fi->type != ARMFault_None) {
10352             goto do_fault;
10353         }
10354         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
10355         switch (desc & 3) {
10356         case 0: /* Page translation fault.  */
10357             fi->type = ARMFault_Translation;
10358             goto do_fault;
10359         case 1: /* 64k page.  */
10360             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10361             xn = desc & (1 << 15);
10362             *page_size = 0x10000;
10363             break;
10364         case 2: case 3: /* 4k page.  */
10365             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10366             xn = desc & 1;
10367             *page_size = 0x1000;
10368             break;
10369         default:
10370             /* Never happens, but compiler isn't smart enough to tell.  */
10371             abort();
10372         }
10373     }
10374     if (domain_prot == 3) {
10375         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10376     } else {
10377         if (pxn && !regime_is_user(env, mmu_idx)) {
10378             xn = 1;
10379         }
10380         if (xn && access_type == MMU_INST_FETCH) {
10381             fi->type = ARMFault_Permission;
10382             goto do_fault;
10383         }
10384 
10385         if (arm_feature(env, ARM_FEATURE_V6K) &&
10386                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
10387             /* The simplified model uses AP[0] as an access control bit.  */
10388             if ((ap & 1) == 0) {
10389                 /* Access flag fault.  */
10390                 fi->type = ARMFault_AccessFlag;
10391                 goto do_fault;
10392             }
10393             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
10394         } else {
10395             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10396         }
10397         if (*prot && !xn) {
10398             *prot |= PAGE_EXEC;
10399         }
10400         if (!(*prot & (1 << access_type))) {
10401             /* Access permission fault.  */
10402             fi->type = ARMFault_Permission;
10403             goto do_fault;
10404         }
10405     }
10406     if (ns) {
10407         /* The NS bit will (as required by the architecture) have no effect if
10408          * the CPU doesn't support TZ or this is a non-secure translation
10409          * regime, because the attribute will already be non-secure.
10410          */
10411         attrs->secure = false;
10412     }
10413     *phys_ptr = phys_addr;
10414     return false;
10415 do_fault:
10416     fi->domain = domain;
10417     fi->level = level;
10418     return true;
10419 }
10420 
10421 /*
10422  * check_s2_mmu_setup
10423  * @cpu:        ARMCPU
10424  * @is_aa64:    True if the translation regime is in AArch64 state
10425  * @startlevel: Suggested starting level
10426  * @inputsize:  Bitsize of IPAs
10427  * @stride:     Page-table stride (See the ARM ARM)
10428  *
10429  * Returns true if the suggested S2 translation parameters are OK and
10430  * false otherwise.
10431  */
10432 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
10433                                int inputsize, int stride)
10434 {
10435     const int grainsize = stride + 3;
10436     int startsizecheck;
10437 
10438     /* Negative levels are never allowed.  */
10439     if (level < 0) {
10440         return false;
10441     }
10442 
10443     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
10444     if (startsizecheck < 1 || startsizecheck > stride + 4) {
10445         return false;
10446     }
10447 
10448     if (is_aa64) {
10449         CPUARMState *env = &cpu->env;
10450         unsigned int pamax = arm_pamax(cpu);
10451 
10452         switch (stride) {
10453         case 13: /* 64KB Pages.  */
10454             if (level == 0 || (level == 1 && pamax <= 42)) {
10455                 return false;
10456             }
10457             break;
10458         case 11: /* 16KB Pages.  */
10459             if (level == 0 || (level == 1 && pamax <= 40)) {
10460                 return false;
10461             }
10462             break;
10463         case 9: /* 4KB Pages.  */
10464             if (level == 0 && pamax <= 42) {
10465                 return false;
10466             }
10467             break;
10468         default:
10469             g_assert_not_reached();
10470         }
10471 
10472         /* Inputsize checks.  */
10473         if (inputsize > pamax &&
10474             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
10475             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
10476             return false;
10477         }
10478     } else {
10479         /* AArch32 only supports 4KB pages. Assert on that.  */
10480         assert(stride == 9);
10481 
10482         if (level == 0) {
10483             return false;
10484         }
10485     }
10486     return true;
10487 }
10488 
10489 /* Translate from the 4-bit stage 2 representation of
10490  * memory attributes (without cache-allocation hints) to
10491  * the 8-bit representation of the stage 1 MAIR registers
10492  * (which includes allocation hints).
10493  *
10494  * ref: shared/translation/attrs/S2AttrDecode()
10495  *      .../S2ConvertAttrsHints()
10496  */
10497 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
10498 {
10499     uint8_t hiattr = extract32(s2attrs, 2, 2);
10500     uint8_t loattr = extract32(s2attrs, 0, 2);
10501     uint8_t hihint = 0, lohint = 0;
10502 
10503     if (hiattr != 0) { /* normal memory */
10504         if ((env->cp15.hcr_el2 & HCR_CD) != 0) { /* cache disabled */
10505             hiattr = loattr = 1; /* non-cacheable */
10506         } else {
10507             if (hiattr != 1) { /* Write-through or write-back */
10508                 hihint = 3; /* RW allocate */
10509             }
10510             if (loattr != 1) { /* Write-through or write-back */
10511                 lohint = 3; /* RW allocate */
10512             }
10513         }
10514     }
10515 
10516     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
10517 }
10518 #endif /* !CONFIG_USER_ONLY */
10519 
10520 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
10521 {
10522     if (regime_has_2_ranges(mmu_idx)) {
10523         return extract64(tcr, 37, 2);
10524     } else if (mmu_idx == ARMMMUIdx_Stage2) {
10525         return 0; /* VTCR_EL2 */
10526     } else {
10527         /* Replicate the single TBI bit so we always have 2 bits.  */
10528         return extract32(tcr, 20, 1) * 3;
10529     }
10530 }
10531 
10532 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
10533 {
10534     if (regime_has_2_ranges(mmu_idx)) {
10535         return extract64(tcr, 51, 2);
10536     } else if (mmu_idx == ARMMMUIdx_Stage2) {
10537         return 0; /* VTCR_EL2 */
10538     } else {
10539         /* Replicate the single TBID bit so we always have 2 bits.  */
10540         return extract32(tcr, 29, 1) * 3;
10541     }
10542 }
10543 
10544 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
10545                                    ARMMMUIdx mmu_idx, bool data)
10546 {
10547     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
10548     bool epd, hpd, using16k, using64k;
10549     int select, tsz, tbi;
10550 
10551     if (!regime_has_2_ranges(mmu_idx)) {
10552         select = 0;
10553         tsz = extract32(tcr, 0, 6);
10554         using64k = extract32(tcr, 14, 1);
10555         using16k = extract32(tcr, 15, 1);
10556         if (mmu_idx == ARMMMUIdx_Stage2) {
10557             /* VTCR_EL2 */
10558             hpd = false;
10559         } else {
10560             hpd = extract32(tcr, 24, 1);
10561         }
10562         epd = false;
10563     } else {
10564         /*
10565          * Bit 55 is always between the two regions, and is canonical for
10566          * determining if address tagging is enabled.
10567          */
10568         select = extract64(va, 55, 1);
10569         if (!select) {
10570             tsz = extract32(tcr, 0, 6);
10571             epd = extract32(tcr, 7, 1);
10572             using64k = extract32(tcr, 14, 1);
10573             using16k = extract32(tcr, 15, 1);
10574             hpd = extract64(tcr, 41, 1);
10575         } else {
10576             int tg = extract32(tcr, 30, 2);
10577             using16k = tg == 1;
10578             using64k = tg == 3;
10579             tsz = extract32(tcr, 16, 6);
10580             epd = extract32(tcr, 23, 1);
10581             hpd = extract64(tcr, 42, 1);
10582         }
10583     }
10584     tsz = MIN(tsz, 39);  /* TODO: ARMv8.4-TTST */
10585     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
10586 
10587     /* Present TBI as a composite with TBID.  */
10588     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
10589     if (!data) {
10590         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
10591     }
10592     tbi = (tbi >> select) & 1;
10593 
10594     return (ARMVAParameters) {
10595         .tsz = tsz,
10596         .select = select,
10597         .tbi = tbi,
10598         .epd = epd,
10599         .hpd = hpd,
10600         .using16k = using16k,
10601         .using64k = using64k,
10602     };
10603 }
10604 
10605 #ifndef CONFIG_USER_ONLY
10606 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
10607                                           ARMMMUIdx mmu_idx)
10608 {
10609     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
10610     uint32_t el = regime_el(env, mmu_idx);
10611     int select, tsz;
10612     bool epd, hpd;
10613 
10614     if (mmu_idx == ARMMMUIdx_Stage2) {
10615         /* VTCR */
10616         bool sext = extract32(tcr, 4, 1);
10617         bool sign = extract32(tcr, 3, 1);
10618 
10619         /*
10620          * If the sign-extend bit is not the same as t0sz[3], the result
10621          * is unpredictable. Flag this as a guest error.
10622          */
10623         if (sign != sext) {
10624             qemu_log_mask(LOG_GUEST_ERROR,
10625                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
10626         }
10627         tsz = sextract32(tcr, 0, 4) + 8;
10628         select = 0;
10629         hpd = false;
10630         epd = false;
10631     } else if (el == 2) {
10632         /* HTCR */
10633         tsz = extract32(tcr, 0, 3);
10634         select = 0;
10635         hpd = extract64(tcr, 24, 1);
10636         epd = false;
10637     } else {
10638         int t0sz = extract32(tcr, 0, 3);
10639         int t1sz = extract32(tcr, 16, 3);
10640 
10641         if (t1sz == 0) {
10642             select = va > (0xffffffffu >> t0sz);
10643         } else {
10644             /* Note that we will detect errors later.  */
10645             select = va >= ~(0xffffffffu >> t1sz);
10646         }
10647         if (!select) {
10648             tsz = t0sz;
10649             epd = extract32(tcr, 7, 1);
10650             hpd = extract64(tcr, 41, 1);
10651         } else {
10652             tsz = t1sz;
10653             epd = extract32(tcr, 23, 1);
10654             hpd = extract64(tcr, 42, 1);
10655         }
10656         /* For aarch32, hpd0 is not enabled without t2e as well.  */
10657         hpd &= extract32(tcr, 6, 1);
10658     }
10659 
10660     return (ARMVAParameters) {
10661         .tsz = tsz,
10662         .select = select,
10663         .epd = epd,
10664         .hpd = hpd,
10665     };
10666 }
10667 
10668 /**
10669  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
10670  *
10671  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
10672  * prot and page_size may not be filled in, and the populated fsr value provides
10673  * information on why the translation aborted, in the format of a long-format
10674  * DFSR/IFSR fault register, with the following caveats:
10675  *  * the WnR bit is never set (the caller must do this).
10676  *
10677  * @env: CPUARMState
10678  * @address: virtual address to get physical address for
10679  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
10680  * @mmu_idx: MMU index indicating required translation regime
10681  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
10682  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
10683  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
10684  * @phys_ptr: set to the physical address corresponding to the virtual address
10685  * @attrs: set to the memory transaction attributes to use
10686  * @prot: set to the permissions for the page containing phys_ptr
10687  * @page_size_ptr: set to the size of the page containing phys_ptr
10688  * @fi: set to fault info if the translation fails
10689  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
10690  */
10691 static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,
10692                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
10693                                bool s1_is_el0,
10694                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
10695                                target_ulong *page_size_ptr,
10696                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
10697 {
10698     ARMCPU *cpu = env_archcpu(env);
10699     CPUState *cs = CPU(cpu);
10700     /* Read an LPAE long-descriptor translation table. */
10701     ARMFaultType fault_type = ARMFault_Translation;
10702     uint32_t level;
10703     ARMVAParameters param;
10704     uint64_t ttbr;
10705     hwaddr descaddr, indexmask, indexmask_grainsize;
10706     uint32_t tableattrs;
10707     target_ulong page_size;
10708     uint32_t attrs;
10709     int32_t stride;
10710     int addrsize, inputsize;
10711     TCR *tcr = regime_tcr(env, mmu_idx);
10712     int ap, ns, xn, pxn;
10713     uint32_t el = regime_el(env, mmu_idx);
10714     uint64_t descaddrmask;
10715     bool aarch64 = arm_el_is_aa64(env, el);
10716     bool guarded = false;
10717 
10718     /* TODO: This code does not support shareability levels. */
10719     if (aarch64) {
10720         param = aa64_va_parameters(env, address, mmu_idx,
10721                                    access_type != MMU_INST_FETCH);
10722         level = 0;
10723         addrsize = 64 - 8 * param.tbi;
10724         inputsize = 64 - param.tsz;
10725     } else {
10726         param = aa32_va_parameters(env, address, mmu_idx);
10727         level = 1;
10728         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
10729         inputsize = addrsize - param.tsz;
10730     }
10731 
10732     /*
10733      * We determined the region when collecting the parameters, but we
10734      * have not yet validated that the address is valid for the region.
10735      * Extract the top bits and verify that they all match select.
10736      *
10737      * For aa32, if inputsize == addrsize, then we have selected the
10738      * region by exclusion in aa32_va_parameters and there is no more
10739      * validation to do here.
10740      */
10741     if (inputsize < addrsize) {
10742         target_ulong top_bits = sextract64(address, inputsize,
10743                                            addrsize - inputsize);
10744         if (-top_bits != param.select) {
10745             /* The gap between the two regions is a Translation fault */
10746             fault_type = ARMFault_Translation;
10747             goto do_fault;
10748         }
10749     }
10750 
10751     if (param.using64k) {
10752         stride = 13;
10753     } else if (param.using16k) {
10754         stride = 11;
10755     } else {
10756         stride = 9;
10757     }
10758 
10759     /* Note that QEMU ignores shareability and cacheability attributes,
10760      * so we don't need to do anything with the SH, ORGN, IRGN fields
10761      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
10762      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
10763      * implement any ASID-like capability so we can ignore it (instead
10764      * we will always flush the TLB any time the ASID is changed).
10765      */
10766     ttbr = regime_ttbr(env, mmu_idx, param.select);
10767 
10768     /* Here we should have set up all the parameters for the translation:
10769      * inputsize, ttbr, epd, stride, tbi
10770      */
10771 
10772     if (param.epd) {
10773         /* Translation table walk disabled => Translation fault on TLB miss
10774          * Note: This is always 0 on 64-bit EL2 and EL3.
10775          */
10776         goto do_fault;
10777     }
10778 
10779     if (mmu_idx != ARMMMUIdx_Stage2) {
10780         /* The starting level depends on the virtual address size (which can
10781          * be up to 48 bits) and the translation granule size. It indicates
10782          * the number of strides (stride bits at a time) needed to
10783          * consume the bits of the input address. In the pseudocode this is:
10784          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
10785          * where their 'inputsize' is our 'inputsize', 'grainsize' is
10786          * our 'stride + 3' and 'stride' is our 'stride'.
10787          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
10788          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
10789          * = 4 - (inputsize - 4) / stride;
10790          */
10791         level = 4 - (inputsize - 4) / stride;
10792     } else {
10793         /* For stage 2 translations the starting level is specified by the
10794          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
10795          */
10796         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
10797         uint32_t startlevel;
10798         bool ok;
10799 
10800         if (!aarch64 || stride == 9) {
10801             /* AArch32 or 4KB pages */
10802             startlevel = 2 - sl0;
10803         } else {
10804             /* 16KB or 64KB pages */
10805             startlevel = 3 - sl0;
10806         }
10807 
10808         /* Check that the starting level is valid. */
10809         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
10810                                 inputsize, stride);
10811         if (!ok) {
10812             fault_type = ARMFault_Translation;
10813             goto do_fault;
10814         }
10815         level = startlevel;
10816     }
10817 
10818     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
10819     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
10820 
10821     /* Now we can extract the actual base address from the TTBR */
10822     descaddr = extract64(ttbr, 0, 48);
10823     /*
10824      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
10825      * and also to mask out CnP (bit 0) which could validly be non-zero.
10826      */
10827     descaddr &= ~indexmask;
10828 
10829     /* The address field in the descriptor goes up to bit 39 for ARMv7
10830      * but up to bit 47 for ARMv8, but we use the descaddrmask
10831      * up to bit 39 for AArch32, because we don't need other bits in that case
10832      * to construct next descriptor address (anyway they should be all zeroes).
10833      */
10834     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
10835                    ~indexmask_grainsize;
10836 
10837     /* Secure accesses start with the page table in secure memory and
10838      * can be downgraded to non-secure at any step. Non-secure accesses
10839      * remain non-secure. We implement this by just ORing in the NSTable/NS
10840      * bits at each step.
10841      */
10842     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
10843     for (;;) {
10844         uint64_t descriptor;
10845         bool nstable;
10846 
10847         descaddr |= (address >> (stride * (4 - level))) & indexmask;
10848         descaddr &= ~7ULL;
10849         nstable = extract32(tableattrs, 4, 1);
10850         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
10851         if (fi->type != ARMFault_None) {
10852             goto do_fault;
10853         }
10854 
10855         if (!(descriptor & 1) ||
10856             (!(descriptor & 2) && (level == 3))) {
10857             /* Invalid, or the Reserved level 3 encoding */
10858             goto do_fault;
10859         }
10860         descaddr = descriptor & descaddrmask;
10861 
10862         if ((descriptor & 2) && (level < 3)) {
10863             /* Table entry. The top five bits are attributes which may
10864              * propagate down through lower levels of the table (and
10865              * which are all arranged so that 0 means "no effect", so
10866              * we can gather them up by ORing in the bits at each level).
10867              */
10868             tableattrs |= extract64(descriptor, 59, 5);
10869             level++;
10870             indexmask = indexmask_grainsize;
10871             continue;
10872         }
10873         /* Block entry at level 1 or 2, or page entry at level 3.
10874          * These are basically the same thing, although the number
10875          * of bits we pull in from the vaddr varies.
10876          */
10877         page_size = (1ULL << ((stride * (4 - level)) + 3));
10878         descaddr |= (address & (page_size - 1));
10879         /* Extract attributes from the descriptor */
10880         attrs = extract64(descriptor, 2, 10)
10881             | (extract64(descriptor, 52, 12) << 10);
10882 
10883         if (mmu_idx == ARMMMUIdx_Stage2) {
10884             /* Stage 2 table descriptors do not include any attribute fields */
10885             break;
10886         }
10887         /* Merge in attributes from table descriptors */
10888         attrs |= nstable << 3; /* NS */
10889         guarded = extract64(descriptor, 50, 1);  /* GP */
10890         if (param.hpd) {
10891             /* HPD disables all the table attributes except NSTable.  */
10892             break;
10893         }
10894         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
10895         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
10896          * means "force PL1 access only", which means forcing AP[1] to 0.
10897          */
10898         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
10899         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
10900         break;
10901     }
10902     /* Here descaddr is the final physical address, and attributes
10903      * are all in attrs.
10904      */
10905     fault_type = ARMFault_AccessFlag;
10906     if ((attrs & (1 << 8)) == 0) {
10907         /* Access flag */
10908         goto do_fault;
10909     }
10910 
10911     ap = extract32(attrs, 4, 2);
10912 
10913     if (mmu_idx == ARMMMUIdx_Stage2) {
10914         ns = true;
10915         xn = extract32(attrs, 11, 2);
10916         *prot = get_S2prot(env, ap, xn, s1_is_el0);
10917     } else {
10918         ns = extract32(attrs, 3, 1);
10919         xn = extract32(attrs, 12, 1);
10920         pxn = extract32(attrs, 11, 1);
10921         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
10922     }
10923 
10924     fault_type = ARMFault_Permission;
10925     if (!(*prot & (1 << access_type))) {
10926         goto do_fault;
10927     }
10928 
10929     if (ns) {
10930         /* The NS bit will (as required by the architecture) have no effect if
10931          * the CPU doesn't support TZ or this is a non-secure translation
10932          * regime, because the attribute will already be non-secure.
10933          */
10934         txattrs->secure = false;
10935     }
10936     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
10937     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
10938         txattrs->target_tlb_bit0 = true;
10939     }
10940 
10941     if (cacheattrs != NULL) {
10942         if (mmu_idx == ARMMMUIdx_Stage2) {
10943             cacheattrs->attrs = convert_stage2_attrs(env,
10944                                                      extract32(attrs, 0, 4));
10945         } else {
10946             /* Index into MAIR registers for cache attributes */
10947             uint8_t attrindx = extract32(attrs, 0, 3);
10948             uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
10949             assert(attrindx <= 7);
10950             cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
10951         }
10952         cacheattrs->shareability = extract32(attrs, 6, 2);
10953     }
10954 
10955     *phys_ptr = descaddr;
10956     *page_size_ptr = page_size;
10957     return false;
10958 
10959 do_fault:
10960     fi->type = fault_type;
10961     fi->level = level;
10962     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
10963     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2);
10964     return true;
10965 }
10966 
10967 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
10968                                                 ARMMMUIdx mmu_idx,
10969                                                 int32_t address, int *prot)
10970 {
10971     if (!arm_feature(env, ARM_FEATURE_M)) {
10972         *prot = PAGE_READ | PAGE_WRITE;
10973         switch (address) {
10974         case 0xF0000000 ... 0xFFFFFFFF:
10975             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
10976                 /* hivecs execing is ok */
10977                 *prot |= PAGE_EXEC;
10978             }
10979             break;
10980         case 0x00000000 ... 0x7FFFFFFF:
10981             *prot |= PAGE_EXEC;
10982             break;
10983         }
10984     } else {
10985         /* Default system address map for M profile cores.
10986          * The architecture specifies which regions are execute-never;
10987          * at the MPU level no other checks are defined.
10988          */
10989         switch (address) {
10990         case 0x00000000 ... 0x1fffffff: /* ROM */
10991         case 0x20000000 ... 0x3fffffff: /* SRAM */
10992         case 0x60000000 ... 0x7fffffff: /* RAM */
10993         case 0x80000000 ... 0x9fffffff: /* RAM */
10994             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10995             break;
10996         case 0x40000000 ... 0x5fffffff: /* Peripheral */
10997         case 0xa0000000 ... 0xbfffffff: /* Device */
10998         case 0xc0000000 ... 0xdfffffff: /* Device */
10999         case 0xe0000000 ... 0xffffffff: /* System */
11000             *prot = PAGE_READ | PAGE_WRITE;
11001             break;
11002         default:
11003             g_assert_not_reached();
11004         }
11005     }
11006 }
11007 
11008 static bool pmsav7_use_background_region(ARMCPU *cpu,
11009                                          ARMMMUIdx mmu_idx, bool is_user)
11010 {
11011     /* Return true if we should use the default memory map as a
11012      * "background" region if there are no hits against any MPU regions.
11013      */
11014     CPUARMState *env = &cpu->env;
11015 
11016     if (is_user) {
11017         return false;
11018     }
11019 
11020     if (arm_feature(env, ARM_FEATURE_M)) {
11021         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11022             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11023     } else {
11024         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11025     }
11026 }
11027 
11028 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11029 {
11030     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11031     return arm_feature(env, ARM_FEATURE_M) &&
11032         extract32(address, 20, 12) == 0xe00;
11033 }
11034 
11035 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11036 {
11037     /* True if address is in the M profile system region
11038      * 0xe0000000 - 0xffffffff
11039      */
11040     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11041 }
11042 
11043 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11044                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11045                                  hwaddr *phys_ptr, int *prot,
11046                                  target_ulong *page_size,
11047                                  ARMMMUFaultInfo *fi)
11048 {
11049     ARMCPU *cpu = env_archcpu(env);
11050     int n;
11051     bool is_user = regime_is_user(env, mmu_idx);
11052 
11053     *phys_ptr = address;
11054     *page_size = TARGET_PAGE_SIZE;
11055     *prot = 0;
11056 
11057     if (regime_translation_disabled(env, mmu_idx) ||
11058         m_is_ppb_region(env, address)) {
11059         /* MPU disabled or M profile PPB access: use default memory map.
11060          * The other case which uses the default memory map in the
11061          * v7M ARM ARM pseudocode is exception vector reads from the vector
11062          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11063          * which always does a direct read using address_space_ldl(), rather
11064          * than going via this function, so we don't need to check that here.
11065          */
11066         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11067     } else { /* MPU enabled */
11068         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11069             /* region search */
11070             uint32_t base = env->pmsav7.drbar[n];
11071             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11072             uint32_t rmask;
11073             bool srdis = false;
11074 
11075             if (!(env->pmsav7.drsr[n] & 0x1)) {
11076                 continue;
11077             }
11078 
11079             if (!rsize) {
11080                 qemu_log_mask(LOG_GUEST_ERROR,
11081                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11082                 continue;
11083             }
11084             rsize++;
11085             rmask = (1ull << rsize) - 1;
11086 
11087             if (base & rmask) {
11088                 qemu_log_mask(LOG_GUEST_ERROR,
11089                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11090                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11091                               n, base, rmask);
11092                 continue;
11093             }
11094 
11095             if (address < base || address > base + rmask) {
11096                 /*
11097                  * Address not in this region. We must check whether the
11098                  * region covers addresses in the same page as our address.
11099                  * In that case we must not report a size that covers the
11100                  * whole page for a subsequent hit against a different MPU
11101                  * region or the background region, because it would result in
11102                  * incorrect TLB hits for subsequent accesses to addresses that
11103                  * are in this MPU region.
11104                  */
11105                 if (ranges_overlap(base, rmask,
11106                                    address & TARGET_PAGE_MASK,
11107                                    TARGET_PAGE_SIZE)) {
11108                     *page_size = 1;
11109                 }
11110                 continue;
11111             }
11112 
11113             /* Region matched */
11114 
11115             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11116                 int i, snd;
11117                 uint32_t srdis_mask;
11118 
11119                 rsize -= 3; /* sub region size (power of 2) */
11120                 snd = ((address - base) >> rsize) & 0x7;
11121                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11122 
11123                 srdis_mask = srdis ? 0x3 : 0x0;
11124                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11125                     /* This will check in groups of 2, 4 and then 8, whether
11126                      * the subregion bits are consistent. rsize is incremented
11127                      * back up to give the region size, considering consistent
11128                      * adjacent subregions as one region. Stop testing if rsize
11129                      * is already big enough for an entire QEMU page.
11130                      */
11131                     int snd_rounded = snd & ~(i - 1);
11132                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11133                                                      snd_rounded + 8, i);
11134                     if (srdis_mask ^ srdis_multi) {
11135                         break;
11136                     }
11137                     srdis_mask = (srdis_mask << i) | srdis_mask;
11138                     rsize++;
11139                 }
11140             }
11141             if (srdis) {
11142                 continue;
11143             }
11144             if (rsize < TARGET_PAGE_BITS) {
11145                 *page_size = 1 << rsize;
11146             }
11147             break;
11148         }
11149 
11150         if (n == -1) { /* no hits */
11151             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11152                 /* background fault */
11153                 fi->type = ARMFault_Background;
11154                 return true;
11155             }
11156             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11157         } else { /* a MPU hit! */
11158             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
11159             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
11160 
11161             if (m_is_system_region(env, address)) {
11162                 /* System space is always execute never */
11163                 xn = 1;
11164             }
11165 
11166             if (is_user) { /* User mode AP bit decoding */
11167                 switch (ap) {
11168                 case 0:
11169                 case 1:
11170                 case 5:
11171                     break; /* no access */
11172                 case 3:
11173                     *prot |= PAGE_WRITE;
11174                     /* fall through */
11175                 case 2:
11176                 case 6:
11177                     *prot |= PAGE_READ | PAGE_EXEC;
11178                     break;
11179                 case 7:
11180                     /* for v7M, same as 6; for R profile a reserved value */
11181                     if (arm_feature(env, ARM_FEATURE_M)) {
11182                         *prot |= PAGE_READ | PAGE_EXEC;
11183                         break;
11184                     }
11185                     /* fall through */
11186                 default:
11187                     qemu_log_mask(LOG_GUEST_ERROR,
11188                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11189                                   PRIx32 "\n", n, ap);
11190                 }
11191             } else { /* Priv. mode AP bits decoding */
11192                 switch (ap) {
11193                 case 0:
11194                     break; /* no access */
11195                 case 1:
11196                 case 2:
11197                 case 3:
11198                     *prot |= PAGE_WRITE;
11199                     /* fall through */
11200                 case 5:
11201                 case 6:
11202                     *prot |= PAGE_READ | PAGE_EXEC;
11203                     break;
11204                 case 7:
11205                     /* for v7M, same as 6; for R profile a reserved value */
11206                     if (arm_feature(env, ARM_FEATURE_M)) {
11207                         *prot |= PAGE_READ | PAGE_EXEC;
11208                         break;
11209                     }
11210                     /* fall through */
11211                 default:
11212                     qemu_log_mask(LOG_GUEST_ERROR,
11213                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11214                                   PRIx32 "\n", n, ap);
11215                 }
11216             }
11217 
11218             /* execute never */
11219             if (xn) {
11220                 *prot &= ~PAGE_EXEC;
11221             }
11222         }
11223     }
11224 
11225     fi->type = ARMFault_Permission;
11226     fi->level = 1;
11227     return !(*prot & (1 << access_type));
11228 }
11229 
11230 static bool v8m_is_sau_exempt(CPUARMState *env,
11231                               uint32_t address, MMUAccessType access_type)
11232 {
11233     /* The architecture specifies that certain address ranges are
11234      * exempt from v8M SAU/IDAU checks.
11235      */
11236     return
11237         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
11238         (address >= 0xe0000000 && address <= 0xe0002fff) ||
11239         (address >= 0xe000e000 && address <= 0xe000efff) ||
11240         (address >= 0xe002e000 && address <= 0xe002efff) ||
11241         (address >= 0xe0040000 && address <= 0xe0041fff) ||
11242         (address >= 0xe00ff000 && address <= 0xe00fffff);
11243 }
11244 
11245 void v8m_security_lookup(CPUARMState *env, uint32_t address,
11246                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
11247                                 V8M_SAttributes *sattrs)
11248 {
11249     /* Look up the security attributes for this address. Compare the
11250      * pseudocode SecurityCheck() function.
11251      * We assume the caller has zero-initialized *sattrs.
11252      */
11253     ARMCPU *cpu = env_archcpu(env);
11254     int r;
11255     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
11256     int idau_region = IREGION_NOTVALID;
11257     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11258     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11259 
11260     if (cpu->idau) {
11261         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
11262         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
11263 
11264         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
11265                    &idau_nsc);
11266     }
11267 
11268     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
11269         /* 0xf0000000..0xffffffff is always S for insn fetches */
11270         return;
11271     }
11272 
11273     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
11274         sattrs->ns = !regime_is_secure(env, mmu_idx);
11275         return;
11276     }
11277 
11278     if (idau_region != IREGION_NOTVALID) {
11279         sattrs->irvalid = true;
11280         sattrs->iregion = idau_region;
11281     }
11282 
11283     switch (env->sau.ctrl & 3) {
11284     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
11285         break;
11286     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
11287         sattrs->ns = true;
11288         break;
11289     default: /* SAU.ENABLE == 1 */
11290         for (r = 0; r < cpu->sau_sregion; r++) {
11291             if (env->sau.rlar[r] & 1) {
11292                 uint32_t base = env->sau.rbar[r] & ~0x1f;
11293                 uint32_t limit = env->sau.rlar[r] | 0x1f;
11294 
11295                 if (base <= address && limit >= address) {
11296                     if (base > addr_page_base || limit < addr_page_limit) {
11297                         sattrs->subpage = true;
11298                     }
11299                     if (sattrs->srvalid) {
11300                         /* If we hit in more than one region then we must report
11301                          * as Secure, not NS-Callable, with no valid region
11302                          * number info.
11303                          */
11304                         sattrs->ns = false;
11305                         sattrs->nsc = false;
11306                         sattrs->sregion = 0;
11307                         sattrs->srvalid = false;
11308                         break;
11309                     } else {
11310                         if (env->sau.rlar[r] & 2) {
11311                             sattrs->nsc = true;
11312                         } else {
11313                             sattrs->ns = true;
11314                         }
11315                         sattrs->srvalid = true;
11316                         sattrs->sregion = r;
11317                     }
11318                 } else {
11319                     /*
11320                      * Address not in this region. We must check whether the
11321                      * region covers addresses in the same page as our address.
11322                      * In that case we must not report a size that covers the
11323                      * whole page for a subsequent hit against a different MPU
11324                      * region or the background region, because it would result
11325                      * in incorrect TLB hits for subsequent accesses to
11326                      * addresses that are in this MPU region.
11327                      */
11328                     if (limit >= base &&
11329                         ranges_overlap(base, limit - base + 1,
11330                                        addr_page_base,
11331                                        TARGET_PAGE_SIZE)) {
11332                         sattrs->subpage = true;
11333                     }
11334                 }
11335             }
11336         }
11337         break;
11338     }
11339 
11340     /*
11341      * The IDAU will override the SAU lookup results if it specifies
11342      * higher security than the SAU does.
11343      */
11344     if (!idau_ns) {
11345         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
11346             sattrs->ns = false;
11347             sattrs->nsc = idau_nsc;
11348         }
11349     }
11350 }
11351 
11352 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
11353                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
11354                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
11355                               int *prot, bool *is_subpage,
11356                               ARMMMUFaultInfo *fi, uint32_t *mregion)
11357 {
11358     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
11359      * that a full phys-to-virt translation does).
11360      * mregion is (if not NULL) set to the region number which matched,
11361      * or -1 if no region number is returned (MPU off, address did not
11362      * hit a region, address hit in multiple regions).
11363      * We set is_subpage to true if the region hit doesn't cover the
11364      * entire TARGET_PAGE the address is within.
11365      */
11366     ARMCPU *cpu = env_archcpu(env);
11367     bool is_user = regime_is_user(env, mmu_idx);
11368     uint32_t secure = regime_is_secure(env, mmu_idx);
11369     int n;
11370     int matchregion = -1;
11371     bool hit = false;
11372     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11373     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11374 
11375     *is_subpage = false;
11376     *phys_ptr = address;
11377     *prot = 0;
11378     if (mregion) {
11379         *mregion = -1;
11380     }
11381 
11382     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
11383      * was an exception vector read from the vector table (which is always
11384      * done using the default system address map), because those accesses
11385      * are done in arm_v7m_load_vector(), which always does a direct
11386      * read using address_space_ldl(), rather than going via this function.
11387      */
11388     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
11389         hit = true;
11390     } else if (m_is_ppb_region(env, address)) {
11391         hit = true;
11392     } else {
11393         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11394             hit = true;
11395         }
11396 
11397         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11398             /* region search */
11399             /* Note that the base address is bits [31:5] from the register
11400              * with bits [4:0] all zeroes, but the limit address is bits
11401              * [31:5] from the register with bits [4:0] all ones.
11402              */
11403             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
11404             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
11405 
11406             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
11407                 /* Region disabled */
11408                 continue;
11409             }
11410 
11411             if (address < base || address > limit) {
11412                 /*
11413                  * Address not in this region. We must check whether the
11414                  * region covers addresses in the same page as our address.
11415                  * In that case we must not report a size that covers the
11416                  * whole page for a subsequent hit against a different MPU
11417                  * region or the background region, because it would result in
11418                  * incorrect TLB hits for subsequent accesses to addresses that
11419                  * are in this MPU region.
11420                  */
11421                 if (limit >= base &&
11422                     ranges_overlap(base, limit - base + 1,
11423                                    addr_page_base,
11424                                    TARGET_PAGE_SIZE)) {
11425                     *is_subpage = true;
11426                 }
11427                 continue;
11428             }
11429 
11430             if (base > addr_page_base || limit < addr_page_limit) {
11431                 *is_subpage = true;
11432             }
11433 
11434             if (matchregion != -1) {
11435                 /* Multiple regions match -- always a failure (unlike
11436                  * PMSAv7 where highest-numbered-region wins)
11437                  */
11438                 fi->type = ARMFault_Permission;
11439                 fi->level = 1;
11440                 return true;
11441             }
11442 
11443             matchregion = n;
11444             hit = true;
11445         }
11446     }
11447 
11448     if (!hit) {
11449         /* background fault */
11450         fi->type = ARMFault_Background;
11451         return true;
11452     }
11453 
11454     if (matchregion == -1) {
11455         /* hit using the background region */
11456         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11457     } else {
11458         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
11459         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
11460 
11461         if (m_is_system_region(env, address)) {
11462             /* System space is always execute never */
11463             xn = 1;
11464         }
11465 
11466         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
11467         if (*prot && !xn) {
11468             *prot |= PAGE_EXEC;
11469         }
11470         /* We don't need to look the attribute up in the MAIR0/MAIR1
11471          * registers because that only tells us about cacheability.
11472          */
11473         if (mregion) {
11474             *mregion = matchregion;
11475         }
11476     }
11477 
11478     fi->type = ARMFault_Permission;
11479     fi->level = 1;
11480     return !(*prot & (1 << access_type));
11481 }
11482 
11483 
11484 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
11485                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11486                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
11487                                  int *prot, target_ulong *page_size,
11488                                  ARMMMUFaultInfo *fi)
11489 {
11490     uint32_t secure = regime_is_secure(env, mmu_idx);
11491     V8M_SAttributes sattrs = {};
11492     bool ret;
11493     bool mpu_is_subpage;
11494 
11495     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
11496         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
11497         if (access_type == MMU_INST_FETCH) {
11498             /* Instruction fetches always use the MMU bank and the
11499              * transaction attribute determined by the fetch address,
11500              * regardless of CPU state. This is painful for QEMU
11501              * to handle, because it would mean we need to encode
11502              * into the mmu_idx not just the (user, negpri) information
11503              * for the current security state but also that for the
11504              * other security state, which would balloon the number
11505              * of mmu_idx values needed alarmingly.
11506              * Fortunately we can avoid this because it's not actually
11507              * possible to arbitrarily execute code from memory with
11508              * the wrong security attribute: it will always generate
11509              * an exception of some kind or another, apart from the
11510              * special case of an NS CPU executing an SG instruction
11511              * in S&NSC memory. So we always just fail the translation
11512              * here and sort things out in the exception handler
11513              * (including possibly emulating an SG instruction).
11514              */
11515             if (sattrs.ns != !secure) {
11516                 if (sattrs.nsc) {
11517                     fi->type = ARMFault_QEMU_NSCExec;
11518                 } else {
11519                     fi->type = ARMFault_QEMU_SFault;
11520                 }
11521                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
11522                 *phys_ptr = address;
11523                 *prot = 0;
11524                 return true;
11525             }
11526         } else {
11527             /* For data accesses we always use the MMU bank indicated
11528              * by the current CPU state, but the security attributes
11529              * might downgrade a secure access to nonsecure.
11530              */
11531             if (sattrs.ns) {
11532                 txattrs->secure = false;
11533             } else if (!secure) {
11534                 /* NS access to S memory must fault.
11535                  * Architecturally we should first check whether the
11536                  * MPU information for this address indicates that we
11537                  * are doing an unaligned access to Device memory, which
11538                  * should generate a UsageFault instead. QEMU does not
11539                  * currently check for that kind of unaligned access though.
11540                  * If we added it we would need to do so as a special case
11541                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
11542                  */
11543                 fi->type = ARMFault_QEMU_SFault;
11544                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
11545                 *phys_ptr = address;
11546                 *prot = 0;
11547                 return true;
11548             }
11549         }
11550     }
11551 
11552     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
11553                             txattrs, prot, &mpu_is_subpage, fi, NULL);
11554     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
11555     return ret;
11556 }
11557 
11558 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
11559                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11560                                  hwaddr *phys_ptr, int *prot,
11561                                  ARMMMUFaultInfo *fi)
11562 {
11563     int n;
11564     uint32_t mask;
11565     uint32_t base;
11566     bool is_user = regime_is_user(env, mmu_idx);
11567 
11568     if (regime_translation_disabled(env, mmu_idx)) {
11569         /* MPU disabled.  */
11570         *phys_ptr = address;
11571         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11572         return false;
11573     }
11574 
11575     *phys_ptr = address;
11576     for (n = 7; n >= 0; n--) {
11577         base = env->cp15.c6_region[n];
11578         if ((base & 1) == 0) {
11579             continue;
11580         }
11581         mask = 1 << ((base >> 1) & 0x1f);
11582         /* Keep this shift separate from the above to avoid an
11583            (undefined) << 32.  */
11584         mask = (mask << 1) - 1;
11585         if (((base ^ address) & ~mask) == 0) {
11586             break;
11587         }
11588     }
11589     if (n < 0) {
11590         fi->type = ARMFault_Background;
11591         return true;
11592     }
11593 
11594     if (access_type == MMU_INST_FETCH) {
11595         mask = env->cp15.pmsav5_insn_ap;
11596     } else {
11597         mask = env->cp15.pmsav5_data_ap;
11598     }
11599     mask = (mask >> (n * 4)) & 0xf;
11600     switch (mask) {
11601     case 0:
11602         fi->type = ARMFault_Permission;
11603         fi->level = 1;
11604         return true;
11605     case 1:
11606         if (is_user) {
11607             fi->type = ARMFault_Permission;
11608             fi->level = 1;
11609             return true;
11610         }
11611         *prot = PAGE_READ | PAGE_WRITE;
11612         break;
11613     case 2:
11614         *prot = PAGE_READ;
11615         if (!is_user) {
11616             *prot |= PAGE_WRITE;
11617         }
11618         break;
11619     case 3:
11620         *prot = PAGE_READ | PAGE_WRITE;
11621         break;
11622     case 5:
11623         if (is_user) {
11624             fi->type = ARMFault_Permission;
11625             fi->level = 1;
11626             return true;
11627         }
11628         *prot = PAGE_READ;
11629         break;
11630     case 6:
11631         *prot = PAGE_READ;
11632         break;
11633     default:
11634         /* Bad permission.  */
11635         fi->type = ARMFault_Permission;
11636         fi->level = 1;
11637         return true;
11638     }
11639     *prot |= PAGE_EXEC;
11640     return false;
11641 }
11642 
11643 /* Combine either inner or outer cacheability attributes for normal
11644  * memory, according to table D4-42 and pseudocode procedure
11645  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
11646  *
11647  * NB: only stage 1 includes allocation hints (RW bits), leading to
11648  * some asymmetry.
11649  */
11650 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
11651 {
11652     if (s1 == 4 || s2 == 4) {
11653         /* non-cacheable has precedence */
11654         return 4;
11655     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
11656         /* stage 1 write-through takes precedence */
11657         return s1;
11658     } else if (extract32(s2, 2, 2) == 2) {
11659         /* stage 2 write-through takes precedence, but the allocation hint
11660          * is still taken from stage 1
11661          */
11662         return (2 << 2) | extract32(s1, 0, 2);
11663     } else { /* write-back */
11664         return s1;
11665     }
11666 }
11667 
11668 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
11669  * and CombineS1S2Desc()
11670  *
11671  * @s1:      Attributes from stage 1 walk
11672  * @s2:      Attributes from stage 2 walk
11673  */
11674 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
11675 {
11676     uint8_t s1lo = extract32(s1.attrs, 0, 4), s2lo = extract32(s2.attrs, 0, 4);
11677     uint8_t s1hi = extract32(s1.attrs, 4, 4), s2hi = extract32(s2.attrs, 4, 4);
11678     ARMCacheAttrs ret;
11679 
11680     /* Combine shareability attributes (table D4-43) */
11681     if (s1.shareability == 2 || s2.shareability == 2) {
11682         /* if either are outer-shareable, the result is outer-shareable */
11683         ret.shareability = 2;
11684     } else if (s1.shareability == 3 || s2.shareability == 3) {
11685         /* if either are inner-shareable, the result is inner-shareable */
11686         ret.shareability = 3;
11687     } else {
11688         /* both non-shareable */
11689         ret.shareability = 0;
11690     }
11691 
11692     /* Combine memory type and cacheability attributes */
11693     if (s1hi == 0 || s2hi == 0) {
11694         /* Device has precedence over normal */
11695         if (s1lo == 0 || s2lo == 0) {
11696             /* nGnRnE has precedence over anything */
11697             ret.attrs = 0;
11698         } else if (s1lo == 4 || s2lo == 4) {
11699             /* non-Reordering has precedence over Reordering */
11700             ret.attrs = 4;  /* nGnRE */
11701         } else if (s1lo == 8 || s2lo == 8) {
11702             /* non-Gathering has precedence over Gathering */
11703             ret.attrs = 8;  /* nGRE */
11704         } else {
11705             ret.attrs = 0xc; /* GRE */
11706         }
11707 
11708         /* Any location for which the resultant memory type is any
11709          * type of Device memory is always treated as Outer Shareable.
11710          */
11711         ret.shareability = 2;
11712     } else { /* Normal memory */
11713         /* Outer/inner cacheability combine independently */
11714         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
11715                   | combine_cacheattr_nibble(s1lo, s2lo);
11716 
11717         if (ret.attrs == 0x44) {
11718             /* Any location for which the resultant memory type is Normal
11719              * Inner Non-cacheable, Outer Non-cacheable is always treated
11720              * as Outer Shareable.
11721              */
11722             ret.shareability = 2;
11723         }
11724     }
11725 
11726     return ret;
11727 }
11728 
11729 
11730 /* get_phys_addr - get the physical address for this virtual address
11731  *
11732  * Find the physical address corresponding to the given virtual address,
11733  * by doing a translation table walk on MMU based systems or using the
11734  * MPU state on MPU based systems.
11735  *
11736  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11737  * prot and page_size may not be filled in, and the populated fsr value provides
11738  * information on why the translation aborted, in the format of a
11739  * DFSR/IFSR fault register, with the following caveats:
11740  *  * we honour the short vs long DFSR format differences.
11741  *  * the WnR bit is never set (the caller must do this).
11742  *  * for PSMAv5 based systems we don't bother to return a full FSR format
11743  *    value.
11744  *
11745  * @env: CPUARMState
11746  * @address: virtual address to get physical address for
11747  * @access_type: 0 for read, 1 for write, 2 for execute
11748  * @mmu_idx: MMU index indicating required translation regime
11749  * @phys_ptr: set to the physical address corresponding to the virtual address
11750  * @attrs: set to the memory transaction attributes to use
11751  * @prot: set to the permissions for the page containing phys_ptr
11752  * @page_size: set to the size of the page containing phys_ptr
11753  * @fi: set to fault info if the translation fails
11754  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11755  */
11756 bool get_phys_addr(CPUARMState *env, target_ulong address,
11757                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
11758                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
11759                    target_ulong *page_size,
11760                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11761 {
11762     if (mmu_idx == ARMMMUIdx_E10_0 ||
11763         mmu_idx == ARMMMUIdx_E10_1 ||
11764         mmu_idx == ARMMMUIdx_E10_1_PAN) {
11765         /* Call ourselves recursively to do the stage 1 and then stage 2
11766          * translations.
11767          */
11768         if (arm_feature(env, ARM_FEATURE_EL2)) {
11769             hwaddr ipa;
11770             int s2_prot;
11771             int ret;
11772             ARMCacheAttrs cacheattrs2 = {};
11773 
11774             ret = get_phys_addr(env, address, access_type,
11775                                 stage_1_mmu_idx(mmu_idx), &ipa, attrs,
11776                                 prot, page_size, fi, cacheattrs);
11777 
11778             /* If S1 fails or S2 is disabled, return early.  */
11779             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
11780                 *phys_ptr = ipa;
11781                 return ret;
11782             }
11783 
11784             /* S1 is done. Now do S2 translation.  */
11785             ret = get_phys_addr_lpae(env, ipa, access_type, ARMMMUIdx_Stage2,
11786                                      mmu_idx == ARMMMUIdx_E10_0,
11787                                      phys_ptr, attrs, &s2_prot,
11788                                      page_size, fi,
11789                                      cacheattrs != NULL ? &cacheattrs2 : NULL);
11790             fi->s2addr = ipa;
11791             /* Combine the S1 and S2 perms.  */
11792             *prot &= s2_prot;
11793 
11794             /* Combine the S1 and S2 cache attributes, if needed */
11795             if (!ret && cacheattrs != NULL) {
11796                 if (env->cp15.hcr_el2 & HCR_DC) {
11797                     /*
11798                      * HCR.DC forces the first stage attributes to
11799                      *  Normal Non-Shareable,
11800                      *  Inner Write-Back Read-Allocate Write-Allocate,
11801                      *  Outer Write-Back Read-Allocate Write-Allocate.
11802                      */
11803                     cacheattrs->attrs = 0xff;
11804                     cacheattrs->shareability = 0;
11805                 }
11806                 *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
11807             }
11808 
11809             return ret;
11810         } else {
11811             /*
11812              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
11813              */
11814             mmu_idx = stage_1_mmu_idx(mmu_idx);
11815         }
11816     }
11817 
11818     /* The page table entries may downgrade secure to non-secure, but
11819      * cannot upgrade an non-secure translation regime's attributes
11820      * to secure.
11821      */
11822     attrs->secure = regime_is_secure(env, mmu_idx);
11823     attrs->user = regime_is_user(env, mmu_idx);
11824 
11825     /* Fast Context Switch Extension. This doesn't exist at all in v8.
11826      * In v7 and earlier it affects all stage 1 translations.
11827      */
11828     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
11829         && !arm_feature(env, ARM_FEATURE_V8)) {
11830         if (regime_el(env, mmu_idx) == 3) {
11831             address += env->cp15.fcseidr_s;
11832         } else {
11833             address += env->cp15.fcseidr_ns;
11834         }
11835     }
11836 
11837     if (arm_feature(env, ARM_FEATURE_PMSA)) {
11838         bool ret;
11839         *page_size = TARGET_PAGE_SIZE;
11840 
11841         if (arm_feature(env, ARM_FEATURE_V8)) {
11842             /* PMSAv8 */
11843             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
11844                                        phys_ptr, attrs, prot, page_size, fi);
11845         } else if (arm_feature(env, ARM_FEATURE_V7)) {
11846             /* PMSAv7 */
11847             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
11848                                        phys_ptr, prot, page_size, fi);
11849         } else {
11850             /* Pre-v7 MPU */
11851             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
11852                                        phys_ptr, prot, fi);
11853         }
11854         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
11855                       " mmu_idx %u -> %s (prot %c%c%c)\n",
11856                       access_type == MMU_DATA_LOAD ? "reading" :
11857                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
11858                       (uint32_t)address, mmu_idx,
11859                       ret ? "Miss" : "Hit",
11860                       *prot & PAGE_READ ? 'r' : '-',
11861                       *prot & PAGE_WRITE ? 'w' : '-',
11862                       *prot & PAGE_EXEC ? 'x' : '-');
11863 
11864         return ret;
11865     }
11866 
11867     /* Definitely a real MMU, not an MPU */
11868 
11869     if (regime_translation_disabled(env, mmu_idx)) {
11870         /*
11871          * MMU disabled.  S1 addresses within aa64 translation regimes are
11872          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
11873          */
11874         if (mmu_idx != ARMMMUIdx_Stage2) {
11875             int r_el = regime_el(env, mmu_idx);
11876             if (arm_el_is_aa64(env, r_el)) {
11877                 int pamax = arm_pamax(env_archcpu(env));
11878                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
11879                 int addrtop, tbi;
11880 
11881                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11882                 if (access_type == MMU_INST_FETCH) {
11883                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11884                 }
11885                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
11886                 addrtop = (tbi ? 55 : 63);
11887 
11888                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
11889                     fi->type = ARMFault_AddressSize;
11890                     fi->level = 0;
11891                     fi->stage2 = false;
11892                     return 1;
11893                 }
11894 
11895                 /*
11896                  * When TBI is disabled, we've just validated that all of the
11897                  * bits above PAMax are zero, so logically we only need to
11898                  * clear the top byte for TBI.  But it's clearer to follow
11899                  * the pseudocode set of addrdesc.paddress.
11900                  */
11901                 address = extract64(address, 0, 52);
11902             }
11903         }
11904         *phys_ptr = address;
11905         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11906         *page_size = TARGET_PAGE_SIZE;
11907         return 0;
11908     }
11909 
11910     if (regime_using_lpae_format(env, mmu_idx)) {
11911         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
11912                                   phys_ptr, attrs, prot, page_size,
11913                                   fi, cacheattrs);
11914     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
11915         return get_phys_addr_v6(env, address, access_type, mmu_idx,
11916                                 phys_ptr, attrs, prot, page_size, fi);
11917     } else {
11918         return get_phys_addr_v5(env, address, access_type, mmu_idx,
11919                                     phys_ptr, prot, page_size, fi);
11920     }
11921 }
11922 
11923 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
11924                                          MemTxAttrs *attrs)
11925 {
11926     ARMCPU *cpu = ARM_CPU(cs);
11927     CPUARMState *env = &cpu->env;
11928     hwaddr phys_addr;
11929     target_ulong page_size;
11930     int prot;
11931     bool ret;
11932     ARMMMUFaultInfo fi = {};
11933     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
11934 
11935     *attrs = (MemTxAttrs) {};
11936 
11937     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
11938                         attrs, &prot, &page_size, &fi, NULL);
11939 
11940     if (ret) {
11941         return -1;
11942     }
11943     return phys_addr;
11944 }
11945 
11946 #endif
11947 
11948 /* Note that signed overflow is undefined in C.  The following routines are
11949    careful to use unsigned types where modulo arithmetic is required.
11950    Failure to do so _will_ break on newer gcc.  */
11951 
11952 /* Signed saturating arithmetic.  */
11953 
11954 /* Perform 16-bit signed saturating addition.  */
11955 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
11956 {
11957     uint16_t res;
11958 
11959     res = a + b;
11960     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
11961         if (a & 0x8000)
11962             res = 0x8000;
11963         else
11964             res = 0x7fff;
11965     }
11966     return res;
11967 }
11968 
11969 /* Perform 8-bit signed saturating addition.  */
11970 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
11971 {
11972     uint8_t res;
11973 
11974     res = a + b;
11975     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
11976         if (a & 0x80)
11977             res = 0x80;
11978         else
11979             res = 0x7f;
11980     }
11981     return res;
11982 }
11983 
11984 /* Perform 16-bit signed saturating subtraction.  */
11985 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
11986 {
11987     uint16_t res;
11988 
11989     res = a - b;
11990     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
11991         if (a & 0x8000)
11992             res = 0x8000;
11993         else
11994             res = 0x7fff;
11995     }
11996     return res;
11997 }
11998 
11999 /* Perform 8-bit signed saturating subtraction.  */
12000 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
12001 {
12002     uint8_t res;
12003 
12004     res = a - b;
12005     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
12006         if (a & 0x80)
12007             res = 0x80;
12008         else
12009             res = 0x7f;
12010     }
12011     return res;
12012 }
12013 
12014 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
12015 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
12016 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
12017 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
12018 #define PFX q
12019 
12020 #include "op_addsub.h"
12021 
12022 /* Unsigned saturating arithmetic.  */
12023 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
12024 {
12025     uint16_t res;
12026     res = a + b;
12027     if (res < a)
12028         res = 0xffff;
12029     return res;
12030 }
12031 
12032 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
12033 {
12034     if (a > b)
12035         return a - b;
12036     else
12037         return 0;
12038 }
12039 
12040 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
12041 {
12042     uint8_t res;
12043     res = a + b;
12044     if (res < a)
12045         res = 0xff;
12046     return res;
12047 }
12048 
12049 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
12050 {
12051     if (a > b)
12052         return a - b;
12053     else
12054         return 0;
12055 }
12056 
12057 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
12058 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
12059 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
12060 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
12061 #define PFX uq
12062 
12063 #include "op_addsub.h"
12064 
12065 /* Signed modulo arithmetic.  */
12066 #define SARITH16(a, b, n, op) do { \
12067     int32_t sum; \
12068     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
12069     RESULT(sum, n, 16); \
12070     if (sum >= 0) \
12071         ge |= 3 << (n * 2); \
12072     } while(0)
12073 
12074 #define SARITH8(a, b, n, op) do { \
12075     int32_t sum; \
12076     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
12077     RESULT(sum, n, 8); \
12078     if (sum >= 0) \
12079         ge |= 1 << n; \
12080     } while(0)
12081 
12082 
12083 #define ADD16(a, b, n) SARITH16(a, b, n, +)
12084 #define SUB16(a, b, n) SARITH16(a, b, n, -)
12085 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
12086 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
12087 #define PFX s
12088 #define ARITH_GE
12089 
12090 #include "op_addsub.h"
12091 
12092 /* Unsigned modulo arithmetic.  */
12093 #define ADD16(a, b, n) do { \
12094     uint32_t sum; \
12095     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
12096     RESULT(sum, n, 16); \
12097     if ((sum >> 16) == 1) \
12098         ge |= 3 << (n * 2); \
12099     } while(0)
12100 
12101 #define ADD8(a, b, n) do { \
12102     uint32_t sum; \
12103     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
12104     RESULT(sum, n, 8); \
12105     if ((sum >> 8) == 1) \
12106         ge |= 1 << n; \
12107     } while(0)
12108 
12109 #define SUB16(a, b, n) do { \
12110     uint32_t sum; \
12111     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
12112     RESULT(sum, n, 16); \
12113     if ((sum >> 16) == 0) \
12114         ge |= 3 << (n * 2); \
12115     } while(0)
12116 
12117 #define SUB8(a, b, n) do { \
12118     uint32_t sum; \
12119     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
12120     RESULT(sum, n, 8); \
12121     if ((sum >> 8) == 0) \
12122         ge |= 1 << n; \
12123     } while(0)
12124 
12125 #define PFX u
12126 #define ARITH_GE
12127 
12128 #include "op_addsub.h"
12129 
12130 /* Halved signed arithmetic.  */
12131 #define ADD16(a, b, n) \
12132   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
12133 #define SUB16(a, b, n) \
12134   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
12135 #define ADD8(a, b, n) \
12136   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
12137 #define SUB8(a, b, n) \
12138   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
12139 #define PFX sh
12140 
12141 #include "op_addsub.h"
12142 
12143 /* Halved unsigned arithmetic.  */
12144 #define ADD16(a, b, n) \
12145   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12146 #define SUB16(a, b, n) \
12147   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12148 #define ADD8(a, b, n) \
12149   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12150 #define SUB8(a, b, n) \
12151   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12152 #define PFX uh
12153 
12154 #include "op_addsub.h"
12155 
12156 static inline uint8_t do_usad(uint8_t a, uint8_t b)
12157 {
12158     if (a > b)
12159         return a - b;
12160     else
12161         return b - a;
12162 }
12163 
12164 /* Unsigned sum of absolute byte differences.  */
12165 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
12166 {
12167     uint32_t sum;
12168     sum = do_usad(a, b);
12169     sum += do_usad(a >> 8, b >> 8);
12170     sum += do_usad(a >> 16, b >>16);
12171     sum += do_usad(a >> 24, b >> 24);
12172     return sum;
12173 }
12174 
12175 /* For ARMv6 SEL instruction.  */
12176 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
12177 {
12178     uint32_t mask;
12179 
12180     mask = 0;
12181     if (flags & 1)
12182         mask |= 0xff;
12183     if (flags & 2)
12184         mask |= 0xff00;
12185     if (flags & 4)
12186         mask |= 0xff0000;
12187     if (flags & 8)
12188         mask |= 0xff000000;
12189     return (a & mask) | (b & ~mask);
12190 }
12191 
12192 /* CRC helpers.
12193  * The upper bytes of val (above the number specified by 'bytes') must have
12194  * been zeroed out by the caller.
12195  */
12196 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12197 {
12198     uint8_t buf[4];
12199 
12200     stl_le_p(buf, val);
12201 
12202     /* zlib crc32 converts the accumulator and output to one's complement.  */
12203     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12204 }
12205 
12206 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12207 {
12208     uint8_t buf[4];
12209 
12210     stl_le_p(buf, val);
12211 
12212     /* Linux crc32c converts the output to one's complement.  */
12213     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12214 }
12215 
12216 /* Return the exception level to which FP-disabled exceptions should
12217  * be taken, or 0 if FP is enabled.
12218  */
12219 int fp_exception_el(CPUARMState *env, int cur_el)
12220 {
12221 #ifndef CONFIG_USER_ONLY
12222     /* CPACR and the CPTR registers don't exist before v6, so FP is
12223      * always accessible
12224      */
12225     if (!arm_feature(env, ARM_FEATURE_V6)) {
12226         return 0;
12227     }
12228 
12229     if (arm_feature(env, ARM_FEATURE_M)) {
12230         /* CPACR can cause a NOCP UsageFault taken to current security state */
12231         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
12232             return 1;
12233         }
12234 
12235         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
12236             if (!extract32(env->v7m.nsacr, 10, 1)) {
12237                 /* FP insns cause a NOCP UsageFault taken to Secure */
12238                 return 3;
12239             }
12240         }
12241 
12242         return 0;
12243     }
12244 
12245     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12246      * 0, 2 : trap EL0 and EL1/PL1 accesses
12247      * 1    : trap only EL0 accesses
12248      * 3    : trap no accesses
12249      * This register is ignored if E2H+TGE are both set.
12250      */
12251     if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
12252         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12253 
12254         switch (fpen) {
12255         case 0:
12256         case 2:
12257             if (cur_el == 0 || cur_el == 1) {
12258                 /* Trap to PL1, which might be EL1 or EL3 */
12259                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12260                     return 3;
12261                 }
12262                 return 1;
12263             }
12264             if (cur_el == 3 && !is_a64(env)) {
12265                 /* Secure PL1 running at EL3 */
12266                 return 3;
12267             }
12268             break;
12269         case 1:
12270             if (cur_el == 0) {
12271                 return 1;
12272             }
12273             break;
12274         case 3:
12275             break;
12276         }
12277     }
12278 
12279     /*
12280      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
12281      * to control non-secure access to the FPU. It doesn't have any
12282      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
12283      */
12284     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
12285          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
12286         if (!extract32(env->cp15.nsacr, 10, 1)) {
12287             /* FP insns act as UNDEF */
12288             return cur_el == 2 ? 2 : 1;
12289         }
12290     }
12291 
12292     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12293      * check because zero bits in the registers mean "don't trap".
12294      */
12295 
12296     /* CPTR_EL2 : present in v7VE or v8 */
12297     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12298         && !arm_is_secure_below_el3(env)) {
12299         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12300         return 2;
12301     }
12302 
12303     /* CPTR_EL3 : present in v8 */
12304     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12305         /* Trap all FP ops to EL3 */
12306         return 3;
12307     }
12308 #endif
12309     return 0;
12310 }
12311 
12312 /* Return the exception level we're running at if this is our mmu_idx */
12313 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
12314 {
12315     if (mmu_idx & ARM_MMU_IDX_M) {
12316         return mmu_idx & ARM_MMU_IDX_M_PRIV;
12317     }
12318 
12319     switch (mmu_idx) {
12320     case ARMMMUIdx_E10_0:
12321     case ARMMMUIdx_E20_0:
12322     case ARMMMUIdx_SE10_0:
12323         return 0;
12324     case ARMMMUIdx_E10_1:
12325     case ARMMMUIdx_E10_1_PAN:
12326     case ARMMMUIdx_SE10_1:
12327     case ARMMMUIdx_SE10_1_PAN:
12328         return 1;
12329     case ARMMMUIdx_E2:
12330     case ARMMMUIdx_E20_2:
12331     case ARMMMUIdx_E20_2_PAN:
12332         return 2;
12333     case ARMMMUIdx_SE3:
12334         return 3;
12335     default:
12336         g_assert_not_reached();
12337     }
12338 }
12339 
12340 #ifndef CONFIG_TCG
12341 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
12342 {
12343     g_assert_not_reached();
12344 }
12345 #endif
12346 
12347 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
12348 {
12349     if (arm_feature(env, ARM_FEATURE_M)) {
12350         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
12351     }
12352 
12353     /* See ARM pseudo-function ELIsInHost.  */
12354     switch (el) {
12355     case 0:
12356         if (arm_is_secure_below_el3(env)) {
12357             return ARMMMUIdx_SE10_0;
12358         }
12359         if ((env->cp15.hcr_el2 & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)
12360             && arm_el_is_aa64(env, 2)) {
12361             return ARMMMUIdx_E20_0;
12362         }
12363         return ARMMMUIdx_E10_0;
12364     case 1:
12365         if (arm_is_secure_below_el3(env)) {
12366             if (env->pstate & PSTATE_PAN) {
12367                 return ARMMMUIdx_SE10_1_PAN;
12368             }
12369             return ARMMMUIdx_SE10_1;
12370         }
12371         if (env->pstate & PSTATE_PAN) {
12372             return ARMMMUIdx_E10_1_PAN;
12373         }
12374         return ARMMMUIdx_E10_1;
12375     case 2:
12376         /* TODO: ARMv8.4-SecEL2 */
12377         /* Note that TGE does not apply at EL2.  */
12378         if ((env->cp15.hcr_el2 & HCR_E2H) && arm_el_is_aa64(env, 2)) {
12379             if (env->pstate & PSTATE_PAN) {
12380                 return ARMMMUIdx_E20_2_PAN;
12381             }
12382             return ARMMMUIdx_E20_2;
12383         }
12384         return ARMMMUIdx_E2;
12385     case 3:
12386         return ARMMMUIdx_SE3;
12387     default:
12388         g_assert_not_reached();
12389     }
12390 }
12391 
12392 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
12393 {
12394     return arm_mmu_idx_el(env, arm_current_el(env));
12395 }
12396 
12397 #ifndef CONFIG_USER_ONLY
12398 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
12399 {
12400     return stage_1_mmu_idx(arm_mmu_idx(env));
12401 }
12402 #endif
12403 
12404 static uint32_t rebuild_hflags_common(CPUARMState *env, int fp_el,
12405                                       ARMMMUIdx mmu_idx, uint32_t flags)
12406 {
12407     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
12408     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX,
12409                        arm_to_core_mmu_idx(mmu_idx));
12410 
12411     if (arm_singlestep_active(env)) {
12412         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
12413     }
12414     return flags;
12415 }
12416 
12417 static uint32_t rebuild_hflags_common_32(CPUARMState *env, int fp_el,
12418                                          ARMMMUIdx mmu_idx, uint32_t flags)
12419 {
12420     bool sctlr_b = arm_sctlr_b(env);
12421 
12422     if (sctlr_b) {
12423         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, 1);
12424     }
12425     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
12426         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
12427     }
12428     flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
12429 
12430     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
12431 }
12432 
12433 static uint32_t rebuild_hflags_m32(CPUARMState *env, int fp_el,
12434                                    ARMMMUIdx mmu_idx)
12435 {
12436     uint32_t flags = 0;
12437 
12438     if (arm_v7m_is_handler_mode(env)) {
12439         flags = FIELD_DP32(flags, TBFLAG_M32, HANDLER, 1);
12440     }
12441 
12442     /*
12443      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
12444      * is suppressing them because the requested execution priority
12445      * is less than 0.
12446      */
12447     if (arm_feature(env, ARM_FEATURE_V8) &&
12448         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
12449           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
12450         flags = FIELD_DP32(flags, TBFLAG_M32, STACKCHECK, 1);
12451     }
12452 
12453     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
12454 }
12455 
12456 static uint32_t rebuild_hflags_aprofile(CPUARMState *env)
12457 {
12458     int flags = 0;
12459 
12460     flags = FIELD_DP32(flags, TBFLAG_ANY, DEBUG_TARGET_EL,
12461                        arm_debug_target_el(env));
12462     return flags;
12463 }
12464 
12465 static uint32_t rebuild_hflags_a32(CPUARMState *env, int fp_el,
12466                                    ARMMMUIdx mmu_idx)
12467 {
12468     uint32_t flags = rebuild_hflags_aprofile(env);
12469 
12470     if (arm_el_is_aa64(env, 1)) {
12471         flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
12472     }
12473 
12474     if (arm_current_el(env) < 2 && env->cp15.hstr_el2 &&
12475         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
12476         flags = FIELD_DP32(flags, TBFLAG_A32, HSTR_ACTIVE, 1);
12477     }
12478 
12479     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
12480 }
12481 
12482 static uint32_t rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
12483                                    ARMMMUIdx mmu_idx)
12484 {
12485     uint32_t flags = rebuild_hflags_aprofile(env);
12486     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
12487     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
12488     uint64_t sctlr;
12489     int tbii, tbid;
12490 
12491     flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
12492 
12493     /* Get control bits for tagged addresses.  */
12494     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
12495     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
12496 
12497     flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
12498     flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
12499 
12500     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
12501         int sve_el = sve_exception_el(env, el);
12502         uint32_t zcr_len;
12503 
12504         /*
12505          * If SVE is disabled, but FP is enabled,
12506          * then the effective len is 0.
12507          */
12508         if (sve_el != 0 && fp_el == 0) {
12509             zcr_len = 0;
12510         } else {
12511             zcr_len = sve_zcr_len_for_el(env, el);
12512         }
12513         flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
12514         flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
12515     }
12516 
12517     sctlr = regime_sctlr(env, stage1);
12518 
12519     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
12520         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
12521     }
12522 
12523     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
12524         /*
12525          * In order to save space in flags, we record only whether
12526          * pauth is "inactive", meaning all insns are implemented as
12527          * a nop, or "active" when some action must be performed.
12528          * The decision of which action to take is left to a helper.
12529          */
12530         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
12531             flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
12532         }
12533     }
12534 
12535     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
12536         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
12537         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
12538             flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
12539         }
12540     }
12541 
12542     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
12543     if (!(env->pstate & PSTATE_UAO)) {
12544         switch (mmu_idx) {
12545         case ARMMMUIdx_E10_1:
12546         case ARMMMUIdx_E10_1_PAN:
12547         case ARMMMUIdx_SE10_1:
12548         case ARMMMUIdx_SE10_1_PAN:
12549             /* TODO: ARMv8.3-NV */
12550             flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
12551             break;
12552         case ARMMMUIdx_E20_2:
12553         case ARMMMUIdx_E20_2_PAN:
12554             /* TODO: ARMv8.4-SecEL2 */
12555             /*
12556              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
12557              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
12558              */
12559             if (env->cp15.hcr_el2 & HCR_TGE) {
12560                 flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
12561             }
12562             break;
12563         default:
12564             break;
12565         }
12566     }
12567 
12568     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
12569 }
12570 
12571 static uint32_t rebuild_hflags_internal(CPUARMState *env)
12572 {
12573     int el = arm_current_el(env);
12574     int fp_el = fp_exception_el(env, el);
12575     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12576 
12577     if (is_a64(env)) {
12578         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
12579     } else if (arm_feature(env, ARM_FEATURE_M)) {
12580         return rebuild_hflags_m32(env, fp_el, mmu_idx);
12581     } else {
12582         return rebuild_hflags_a32(env, fp_el, mmu_idx);
12583     }
12584 }
12585 
12586 void arm_rebuild_hflags(CPUARMState *env)
12587 {
12588     env->hflags = rebuild_hflags_internal(env);
12589 }
12590 
12591 /*
12592  * If we have triggered a EL state change we can't rely on the
12593  * translator having passed it to us, we need to recompute.
12594  */
12595 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
12596 {
12597     int el = arm_current_el(env);
12598     int fp_el = fp_exception_el(env, el);
12599     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12600     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
12601 }
12602 
12603 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
12604 {
12605     int fp_el = fp_exception_el(env, el);
12606     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12607 
12608     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
12609 }
12610 
12611 /*
12612  * If we have triggered a EL state change we can't rely on the
12613  * translator having passed it to us, we need to recompute.
12614  */
12615 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
12616 {
12617     int el = arm_current_el(env);
12618     int fp_el = fp_exception_el(env, el);
12619     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12620     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
12621 }
12622 
12623 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
12624 {
12625     int fp_el = fp_exception_el(env, el);
12626     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12627 
12628     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
12629 }
12630 
12631 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
12632 {
12633     int fp_el = fp_exception_el(env, el);
12634     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
12635 
12636     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
12637 }
12638 
12639 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
12640 {
12641 #ifdef CONFIG_DEBUG_TCG
12642     uint32_t env_flags_current = env->hflags;
12643     uint32_t env_flags_rebuilt = rebuild_hflags_internal(env);
12644 
12645     if (unlikely(env_flags_current != env_flags_rebuilt)) {
12646         fprintf(stderr, "TCG hflags mismatch (current:0x%08x rebuilt:0x%08x)\n",
12647                 env_flags_current, env_flags_rebuilt);
12648         abort();
12649     }
12650 #endif
12651 }
12652 
12653 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
12654                           target_ulong *cs_base, uint32_t *pflags)
12655 {
12656     uint32_t flags = env->hflags;
12657     uint32_t pstate_for_ss;
12658 
12659     *cs_base = 0;
12660     assert_hflags_rebuild_correctly(env);
12661 
12662     if (FIELD_EX32(flags, TBFLAG_ANY, AARCH64_STATE)) {
12663         *pc = env->pc;
12664         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
12665             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
12666         }
12667         pstate_for_ss = env->pstate;
12668     } else {
12669         *pc = env->regs[15];
12670 
12671         if (arm_feature(env, ARM_FEATURE_M)) {
12672             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
12673                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
12674                 != env->v7m.secure) {
12675                 flags = FIELD_DP32(flags, TBFLAG_M32, FPCCR_S_WRONG, 1);
12676             }
12677 
12678             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
12679                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
12680                  (env->v7m.secure &&
12681                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
12682                 /*
12683                  * ASPEN is set, but FPCA/SFPA indicate that there is no
12684                  * active FP context; we must create a new FP context before
12685                  * executing any FP insn.
12686                  */
12687                 flags = FIELD_DP32(flags, TBFLAG_M32, NEW_FP_CTXT_NEEDED, 1);
12688             }
12689 
12690             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
12691             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
12692                 flags = FIELD_DP32(flags, TBFLAG_M32, LSPACT, 1);
12693             }
12694         } else {
12695             /*
12696              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
12697              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
12698              */
12699             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
12700                 flags = FIELD_DP32(flags, TBFLAG_A32,
12701                                    XSCALE_CPAR, env->cp15.c15_cpar);
12702             } else {
12703                 flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN,
12704                                    env->vfp.vec_len);
12705                 flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE,
12706                                    env->vfp.vec_stride);
12707             }
12708             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
12709                 flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
12710             }
12711         }
12712 
12713         flags = FIELD_DP32(flags, TBFLAG_AM32, THUMB, env->thumb);
12714         flags = FIELD_DP32(flags, TBFLAG_AM32, CONDEXEC, env->condexec_bits);
12715         pstate_for_ss = env->uncached_cpsr;
12716     }
12717 
12718     /*
12719      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
12720      * states defined in the ARM ARM for software singlestep:
12721      *  SS_ACTIVE   PSTATE.SS   State
12722      *     0            x       Inactive (the TB flag for SS is always 0)
12723      *     1            0       Active-pending
12724      *     1            1       Active-not-pending
12725      * SS_ACTIVE is set in hflags; PSTATE_SS is computed every TB.
12726      */
12727     if (FIELD_EX32(flags, TBFLAG_ANY, SS_ACTIVE) &&
12728         (pstate_for_ss & PSTATE_SS)) {
12729         flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
12730     }
12731 
12732     *pflags = flags;
12733 }
12734 
12735 #ifdef TARGET_AARCH64
12736 /*
12737  * The manual says that when SVE is enabled and VQ is widened the
12738  * implementation is allowed to zero the previously inaccessible
12739  * portion of the registers.  The corollary to that is that when
12740  * SVE is enabled and VQ is narrowed we are also allowed to zero
12741  * the now inaccessible portion of the registers.
12742  *
12743  * The intent of this is that no predicate bit beyond VQ is ever set.
12744  * Which means that some operations on predicate registers themselves
12745  * may operate on full uint64_t or even unrolled across the maximum
12746  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
12747  * may well be cheaper than conditionals to restrict the operation
12748  * to the relevant portion of a uint16_t[16].
12749  */
12750 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
12751 {
12752     int i, j;
12753     uint64_t pmask;
12754 
12755     assert(vq >= 1 && vq <= ARM_MAX_VQ);
12756     assert(vq <= env_archcpu(env)->sve_max_vq);
12757 
12758     /* Zap the high bits of the zregs.  */
12759     for (i = 0; i < 32; i++) {
12760         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
12761     }
12762 
12763     /* Zap the high bits of the pregs and ffr.  */
12764     pmask = 0;
12765     if (vq & 3) {
12766         pmask = ~(-1ULL << (16 * (vq & 3)));
12767     }
12768     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
12769         for (i = 0; i < 17; ++i) {
12770             env->vfp.pregs[i].p[j] &= pmask;
12771         }
12772         pmask = 0;
12773     }
12774 }
12775 
12776 /*
12777  * Notice a change in SVE vector size when changing EL.
12778  */
12779 void aarch64_sve_change_el(CPUARMState *env, int old_el,
12780                            int new_el, bool el0_a64)
12781 {
12782     ARMCPU *cpu = env_archcpu(env);
12783     int old_len, new_len;
12784     bool old_a64, new_a64;
12785 
12786     /* Nothing to do if no SVE.  */
12787     if (!cpu_isar_feature(aa64_sve, cpu)) {
12788         return;
12789     }
12790 
12791     /* Nothing to do if FP is disabled in either EL.  */
12792     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
12793         return;
12794     }
12795 
12796     /*
12797      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
12798      * at ELx, or not available because the EL is in AArch32 state, then
12799      * for all purposes other than a direct read, the ZCR_ELx.LEN field
12800      * has an effective value of 0".
12801      *
12802      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
12803      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
12804      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
12805      * we already have the correct register contents when encountering the
12806      * vq0->vq0 transition between EL0->EL1.
12807      */
12808     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
12809     old_len = (old_a64 && !sve_exception_el(env, old_el)
12810                ? sve_zcr_len_for_el(env, old_el) : 0);
12811     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
12812     new_len = (new_a64 && !sve_exception_el(env, new_el)
12813                ? sve_zcr_len_for_el(env, new_el) : 0);
12814 
12815     /* When changing vector length, clear inaccessible state.  */
12816     if (new_len < old_len) {
12817         aarch64_sve_narrow_vq(env, new_len + 1);
12818     }
12819 }
12820 #endif
12821