xref: /openbmc/qemu/target/arm/helper.c (revision 2182e405)
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/cpu-timers.h"
28 #include "sysemu/kvm.h"
29 #include "sysemu/tcg.h"
30 #include "qemu/range.h"
31 #include "qapi/qapi-commands-machine-target.h"
32 #include "qapi/error.h"
33 #include "qemu/guest-random.h"
34 #ifdef CONFIG_TCG
35 #include "arm_ldst.h"
36 #include "exec/cpu_ldst.h"
37 #include "hw/semihosting/common-semi.h"
38 #endif
39 
40 #define ARM_CPU_FREQ 1000000000 /* FIXME: 1 GHz, should be configurable */
41 #define PMCR_NUM_COUNTERS 4 /* QEMU IMPDEF choice */
42 
43 #ifndef CONFIG_USER_ONLY
44 
45 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
46                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
47                                bool s1_is_el0,
48                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
49                                target_ulong *page_size_ptr,
50                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
51     __attribute__((nonnull));
52 #endif
53 
54 static void switch_mode(CPUARMState *env, int mode);
55 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx);
56 
57 static int vfp_gdb_get_reg(CPUARMState *env, GByteArray *buf, int reg)
58 {
59     ARMCPU *cpu = env_archcpu(env);
60     int nregs = cpu_isar_feature(aa32_simd_r32, cpu) ? 32 : 16;
61 
62     /* VFP data registers are always little-endian.  */
63     if (reg < nregs) {
64         return gdb_get_reg64(buf, *aa32_vfp_dreg(env, reg));
65     }
66     if (arm_feature(env, ARM_FEATURE_NEON)) {
67         /* Aliases for Q regs.  */
68         nregs += 16;
69         if (reg < nregs) {
70             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
71             return gdb_get_reg128(buf, q[0], q[1]);
72         }
73     }
74     switch (reg - nregs) {
75     case 0: return gdb_get_reg32(buf, env->vfp.xregs[ARM_VFP_FPSID]); break;
76     case 1: return gdb_get_reg32(buf, vfp_get_fpscr(env)); break;
77     case 2: return gdb_get_reg32(buf, env->vfp.xregs[ARM_VFP_FPEXC]); break;
78     }
79     return 0;
80 }
81 
82 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
83 {
84     ARMCPU *cpu = env_archcpu(env);
85     int nregs = cpu_isar_feature(aa32_simd_r32, cpu) ? 32 : 16;
86 
87     if (reg < nregs) {
88         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
89         return 8;
90     }
91     if (arm_feature(env, ARM_FEATURE_NEON)) {
92         nregs += 16;
93         if (reg < nregs) {
94             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
95             q[0] = ldq_le_p(buf);
96             q[1] = ldq_le_p(buf + 8);
97             return 16;
98         }
99     }
100     switch (reg - nregs) {
101     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
102     case 1: vfp_set_fpscr(env, ldl_p(buf)); return 4;
103     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
104     }
105     return 0;
106 }
107 
108 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, GByteArray *buf, int reg)
109 {
110     switch (reg) {
111     case 0 ... 31:
112     {
113         /* 128 bit FP register - quads are in LE order */
114         uint64_t *q = aa64_vfp_qreg(env, reg);
115         return gdb_get_reg128(buf, q[1], q[0]);
116     }
117     case 32:
118         /* FPSR */
119         return gdb_get_reg32(buf, vfp_get_fpsr(env));
120     case 33:
121         /* FPCR */
122         return gdb_get_reg32(buf,vfp_get_fpcr(env));
123     default:
124         return 0;
125     }
126 }
127 
128 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
129 {
130     switch (reg) {
131     case 0 ... 31:
132         /* 128 bit FP register */
133         {
134             uint64_t *q = aa64_vfp_qreg(env, reg);
135             q[0] = ldq_le_p(buf);
136             q[1] = ldq_le_p(buf + 8);
137             return 16;
138         }
139     case 32:
140         /* FPSR */
141         vfp_set_fpsr(env, ldl_p(buf));
142         return 4;
143     case 33:
144         /* FPCR */
145         vfp_set_fpcr(env, ldl_p(buf));
146         return 4;
147     default:
148         return 0;
149     }
150 }
151 
152 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
153 {
154     assert(ri->fieldoffset);
155     if (cpreg_field_is_64bit(ri)) {
156         return CPREG_FIELD64(env, ri);
157     } else {
158         return CPREG_FIELD32(env, ri);
159     }
160 }
161 
162 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
163                       uint64_t value)
164 {
165     assert(ri->fieldoffset);
166     if (cpreg_field_is_64bit(ri)) {
167         CPREG_FIELD64(env, ri) = value;
168     } else {
169         CPREG_FIELD32(env, ri) = value;
170     }
171 }
172 
173 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
174 {
175     return (char *)env + ri->fieldoffset;
176 }
177 
178 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
179 {
180     /* Raw read of a coprocessor register (as needed for migration, etc). */
181     if (ri->type & ARM_CP_CONST) {
182         return ri->resetvalue;
183     } else if (ri->raw_readfn) {
184         return ri->raw_readfn(env, ri);
185     } else if (ri->readfn) {
186         return ri->readfn(env, ri);
187     } else {
188         return raw_read(env, ri);
189     }
190 }
191 
192 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
193                              uint64_t v)
194 {
195     /* Raw write of a coprocessor register (as needed for migration, etc).
196      * Note that constant registers are treated as write-ignored; the
197      * caller should check for success by whether a readback gives the
198      * value written.
199      */
200     if (ri->type & ARM_CP_CONST) {
201         return;
202     } else if (ri->raw_writefn) {
203         ri->raw_writefn(env, ri, v);
204     } else if (ri->writefn) {
205         ri->writefn(env, ri, v);
206     } else {
207         raw_write(env, ri, v);
208     }
209 }
210 
211 /**
212  * arm_get/set_gdb_*: get/set a gdb register
213  * @env: the CPU state
214  * @buf: a buffer to copy to/from
215  * @reg: register number (offset from start of group)
216  *
217  * We return the number of bytes copied
218  */
219 
220 static int arm_gdb_get_sysreg(CPUARMState *env, GByteArray *buf, int reg)
221 {
222     ARMCPU *cpu = env_archcpu(env);
223     const ARMCPRegInfo *ri;
224     uint32_t key;
225 
226     key = cpu->dyn_sysreg_xml.data.cpregs.keys[reg];
227     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
228     if (ri) {
229         if (cpreg_field_is_64bit(ri)) {
230             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
231         } else {
232             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
233         }
234     }
235     return 0;
236 }
237 
238 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
239 {
240     return 0;
241 }
242 
243 #ifdef TARGET_AARCH64
244 static int arm_gdb_get_svereg(CPUARMState *env, GByteArray *buf, int reg)
245 {
246     ARMCPU *cpu = env_archcpu(env);
247 
248     switch (reg) {
249     /* The first 32 registers are the zregs */
250     case 0 ... 31:
251     {
252         int vq, len = 0;
253         for (vq = 0; vq < cpu->sve_max_vq; vq++) {
254             len += gdb_get_reg128(buf,
255                                   env->vfp.zregs[reg].d[vq * 2 + 1],
256                                   env->vfp.zregs[reg].d[vq * 2]);
257         }
258         return len;
259     }
260     case 32:
261         return gdb_get_reg32(buf, vfp_get_fpsr(env));
262     case 33:
263         return gdb_get_reg32(buf, vfp_get_fpcr(env));
264     /* then 16 predicates and the ffr */
265     case 34 ... 50:
266     {
267         int preg = reg - 34;
268         int vq, len = 0;
269         for (vq = 0; vq < cpu->sve_max_vq; vq = vq + 4) {
270             len += gdb_get_reg64(buf, env->vfp.pregs[preg].p[vq / 4]);
271         }
272         return len;
273     }
274     case 51:
275     {
276         /*
277          * We report in Vector Granules (VG) which is 64bit in a Z reg
278          * while the ZCR works in Vector Quads (VQ) which is 128bit chunks.
279          */
280         int vq = sve_zcr_len_for_el(env, arm_current_el(env)) + 1;
281         return gdb_get_reg64(buf, vq * 2);
282     }
283     default:
284         /* gdbstub asked for something out our range */
285         qemu_log_mask(LOG_UNIMP, "%s: out of range register %d", __func__, reg);
286         break;
287     }
288 
289     return 0;
290 }
291 
292 static int arm_gdb_set_svereg(CPUARMState *env, uint8_t *buf, int reg)
293 {
294     ARMCPU *cpu = env_archcpu(env);
295 
296     /* The first 32 registers are the zregs */
297     switch (reg) {
298     /* The first 32 registers are the zregs */
299     case 0 ... 31:
300     {
301         int vq, len = 0;
302         uint64_t *p = (uint64_t *) buf;
303         for (vq = 0; vq < cpu->sve_max_vq; vq++) {
304             env->vfp.zregs[reg].d[vq * 2 + 1] = *p++;
305             env->vfp.zregs[reg].d[vq * 2] = *p++;
306             len += 16;
307         }
308         return len;
309     }
310     case 32:
311         vfp_set_fpsr(env, *(uint32_t *)buf);
312         return 4;
313     case 33:
314         vfp_set_fpcr(env, *(uint32_t *)buf);
315         return 4;
316     case 34 ... 50:
317     {
318         int preg = reg - 34;
319         int vq, len = 0;
320         uint64_t *p = (uint64_t *) buf;
321         for (vq = 0; vq < cpu->sve_max_vq; vq = vq + 4) {
322             env->vfp.pregs[preg].p[vq / 4] = *p++;
323             len += 8;
324         }
325         return len;
326     }
327     case 51:
328         /* cannot set vg via gdbstub */
329         return 0;
330     default:
331         /* gdbstub asked for something out our range */
332         break;
333     }
334 
335     return 0;
336 }
337 #endif /* TARGET_AARCH64 */
338 
339 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
340 {
341    /* Return true if the regdef would cause an assertion if you called
342     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
343     * program bug for it not to have the NO_RAW flag).
344     * NB that returning false here doesn't necessarily mean that calling
345     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
346     * read/write access functions which are safe for raw use" from "has
347     * read/write access functions which have side effects but has forgotten
348     * to provide raw access functions".
349     * The tests here line up with the conditions in read/write_raw_cp_reg()
350     * and assertions in raw_read()/raw_write().
351     */
352     if ((ri->type & ARM_CP_CONST) ||
353         ri->fieldoffset ||
354         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
355         return false;
356     }
357     return true;
358 }
359 
360 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
361 {
362     /* Write the coprocessor state from cpu->env to the (index,value) list. */
363     int i;
364     bool ok = true;
365 
366     for (i = 0; i < cpu->cpreg_array_len; i++) {
367         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
368         const ARMCPRegInfo *ri;
369         uint64_t newval;
370 
371         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
372         if (!ri) {
373             ok = false;
374             continue;
375         }
376         if (ri->type & ARM_CP_NO_RAW) {
377             continue;
378         }
379 
380         newval = read_raw_cp_reg(&cpu->env, ri);
381         if (kvm_sync) {
382             /*
383              * Only sync if the previous list->cpustate sync succeeded.
384              * Rather than tracking the success/failure state for every
385              * item in the list, we just recheck "does the raw write we must
386              * have made in write_list_to_cpustate() read back OK" here.
387              */
388             uint64_t oldval = cpu->cpreg_values[i];
389 
390             if (oldval == newval) {
391                 continue;
392             }
393 
394             write_raw_cp_reg(&cpu->env, ri, oldval);
395             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
396                 continue;
397             }
398 
399             write_raw_cp_reg(&cpu->env, ri, newval);
400         }
401         cpu->cpreg_values[i] = newval;
402     }
403     return ok;
404 }
405 
406 bool write_list_to_cpustate(ARMCPU *cpu)
407 {
408     int i;
409     bool ok = true;
410 
411     for (i = 0; i < cpu->cpreg_array_len; i++) {
412         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
413         uint64_t v = cpu->cpreg_values[i];
414         const ARMCPRegInfo *ri;
415 
416         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
417         if (!ri) {
418             ok = false;
419             continue;
420         }
421         if (ri->type & ARM_CP_NO_RAW) {
422             continue;
423         }
424         /* Write value and confirm it reads back as written
425          * (to catch read-only registers and partially read-only
426          * registers where the incoming migration value doesn't match)
427          */
428         write_raw_cp_reg(&cpu->env, ri, v);
429         if (read_raw_cp_reg(&cpu->env, ri) != v) {
430             ok = false;
431         }
432     }
433     return ok;
434 }
435 
436 static void add_cpreg_to_list(gpointer key, gpointer opaque)
437 {
438     ARMCPU *cpu = opaque;
439     uint64_t regidx;
440     const ARMCPRegInfo *ri;
441 
442     regidx = *(uint32_t *)key;
443     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
444 
445     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
446         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
447         /* The value array need not be initialized at this point */
448         cpu->cpreg_array_len++;
449     }
450 }
451 
452 static void count_cpreg(gpointer key, gpointer opaque)
453 {
454     ARMCPU *cpu = opaque;
455     uint64_t regidx;
456     const ARMCPRegInfo *ri;
457 
458     regidx = *(uint32_t *)key;
459     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
460 
461     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
462         cpu->cpreg_array_len++;
463     }
464 }
465 
466 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
467 {
468     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
469     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
470 
471     if (aidx > bidx) {
472         return 1;
473     }
474     if (aidx < bidx) {
475         return -1;
476     }
477     return 0;
478 }
479 
480 void init_cpreg_list(ARMCPU *cpu)
481 {
482     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
483      * Note that we require cpreg_tuples[] to be sorted by key ID.
484      */
485     GList *keys;
486     int arraylen;
487 
488     keys = g_hash_table_get_keys(cpu->cp_regs);
489     keys = g_list_sort(keys, cpreg_key_compare);
490 
491     cpu->cpreg_array_len = 0;
492 
493     g_list_foreach(keys, count_cpreg, cpu);
494 
495     arraylen = cpu->cpreg_array_len;
496     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
497     cpu->cpreg_values = g_new(uint64_t, arraylen);
498     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
499     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
500     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
501     cpu->cpreg_array_len = 0;
502 
503     g_list_foreach(keys, add_cpreg_to_list, cpu);
504 
505     assert(cpu->cpreg_array_len == arraylen);
506 
507     g_list_free(keys);
508 }
509 
510 /*
511  * Some registers are not accessible from AArch32 EL3 if SCR.NS == 0.
512  */
513 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
514                                         const ARMCPRegInfo *ri,
515                                         bool isread)
516 {
517     if (!is_a64(env) && arm_current_el(env) == 3 &&
518         arm_is_secure_below_el3(env)) {
519         return CP_ACCESS_TRAP_UNCATEGORIZED;
520     }
521     return CP_ACCESS_OK;
522 }
523 
524 /* Some secure-only AArch32 registers trap to EL3 if used from
525  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
526  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
527  * We assume that the .access field is set to PL1_RW.
528  */
529 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
530                                             const ARMCPRegInfo *ri,
531                                             bool isread)
532 {
533     if (arm_current_el(env) == 3) {
534         return CP_ACCESS_OK;
535     }
536     if (arm_is_secure_below_el3(env)) {
537         if (env->cp15.scr_el3 & SCR_EEL2) {
538             return CP_ACCESS_TRAP_EL2;
539         }
540         return CP_ACCESS_TRAP_EL3;
541     }
542     /* This will be EL1 NS and EL2 NS, which just UNDEF */
543     return CP_ACCESS_TRAP_UNCATEGORIZED;
544 }
545 
546 static uint64_t arm_mdcr_el2_eff(CPUARMState *env)
547 {
548     return arm_is_el2_enabled(env) ? env->cp15.mdcr_el2 : 0;
549 }
550 
551 /* Check for traps to "powerdown debug" registers, which are controlled
552  * by MDCR.TDOSA
553  */
554 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
555                                    bool isread)
556 {
557     int el = arm_current_el(env);
558     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
559     bool mdcr_el2_tdosa = (mdcr_el2 & MDCR_TDOSA) || (mdcr_el2 & MDCR_TDE) ||
560         (arm_hcr_el2_eff(env) & HCR_TGE);
561 
562     if (el < 2 && mdcr_el2_tdosa) {
563         return CP_ACCESS_TRAP_EL2;
564     }
565     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
566         return CP_ACCESS_TRAP_EL3;
567     }
568     return CP_ACCESS_OK;
569 }
570 
571 /* Check for traps to "debug ROM" registers, which are controlled
572  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
573  */
574 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
575                                   bool isread)
576 {
577     int el = arm_current_el(env);
578     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
579     bool mdcr_el2_tdra = (mdcr_el2 & MDCR_TDRA) || (mdcr_el2 & MDCR_TDE) ||
580         (arm_hcr_el2_eff(env) & HCR_TGE);
581 
582     if (el < 2 && mdcr_el2_tdra) {
583         return CP_ACCESS_TRAP_EL2;
584     }
585     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
586         return CP_ACCESS_TRAP_EL3;
587     }
588     return CP_ACCESS_OK;
589 }
590 
591 /* Check for traps to general debug registers, which are controlled
592  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
593  */
594 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
595                                   bool isread)
596 {
597     int el = arm_current_el(env);
598     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
599     bool mdcr_el2_tda = (mdcr_el2 & MDCR_TDA) || (mdcr_el2 & MDCR_TDE) ||
600         (arm_hcr_el2_eff(env) & HCR_TGE);
601 
602     if (el < 2 && mdcr_el2_tda) {
603         return CP_ACCESS_TRAP_EL2;
604     }
605     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
606         return CP_ACCESS_TRAP_EL3;
607     }
608     return CP_ACCESS_OK;
609 }
610 
611 /* Check for traps to performance monitor registers, which are controlled
612  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
613  */
614 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
615                                  bool isread)
616 {
617     int el = arm_current_el(env);
618     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
619 
620     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
621         return CP_ACCESS_TRAP_EL2;
622     }
623     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
624         return CP_ACCESS_TRAP_EL3;
625     }
626     return CP_ACCESS_OK;
627 }
628 
629 /* Check for traps from EL1 due to HCR_EL2.TVM and HCR_EL2.TRVM.  */
630 static CPAccessResult access_tvm_trvm(CPUARMState *env, const ARMCPRegInfo *ri,
631                                       bool isread)
632 {
633     if (arm_current_el(env) == 1) {
634         uint64_t trap = isread ? HCR_TRVM : HCR_TVM;
635         if (arm_hcr_el2_eff(env) & trap) {
636             return CP_ACCESS_TRAP_EL2;
637         }
638     }
639     return CP_ACCESS_OK;
640 }
641 
642 /* Check for traps from EL1 due to HCR_EL2.TSW.  */
643 static CPAccessResult access_tsw(CPUARMState *env, const ARMCPRegInfo *ri,
644                                  bool isread)
645 {
646     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TSW)) {
647         return CP_ACCESS_TRAP_EL2;
648     }
649     return CP_ACCESS_OK;
650 }
651 
652 /* Check for traps from EL1 due to HCR_EL2.TACR.  */
653 static CPAccessResult access_tacr(CPUARMState *env, const ARMCPRegInfo *ri,
654                                   bool isread)
655 {
656     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TACR)) {
657         return CP_ACCESS_TRAP_EL2;
658     }
659     return CP_ACCESS_OK;
660 }
661 
662 /* Check for traps from EL1 due to HCR_EL2.TTLB. */
663 static CPAccessResult access_ttlb(CPUARMState *env, const ARMCPRegInfo *ri,
664                                   bool isread)
665 {
666     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TTLB)) {
667         return CP_ACCESS_TRAP_EL2;
668     }
669     return CP_ACCESS_OK;
670 }
671 
672 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
673 {
674     ARMCPU *cpu = env_archcpu(env);
675 
676     raw_write(env, ri, value);
677     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
678 }
679 
680 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
681 {
682     ARMCPU *cpu = env_archcpu(env);
683 
684     if (raw_read(env, ri) != value) {
685         /* Unlike real hardware the qemu TLB uses virtual addresses,
686          * not modified virtual addresses, so this causes a TLB flush.
687          */
688         tlb_flush(CPU(cpu));
689         raw_write(env, ri, value);
690     }
691 }
692 
693 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
694                              uint64_t value)
695 {
696     ARMCPU *cpu = env_archcpu(env);
697 
698     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
699         && !extended_addresses_enabled(env)) {
700         /* For VMSA (when not using the LPAE long descriptor page table
701          * format) this register includes the ASID, so do a TLB flush.
702          * For PMSA it is purely a process ID and no action is needed.
703          */
704         tlb_flush(CPU(cpu));
705     }
706     raw_write(env, ri, value);
707 }
708 
709 /* IS variants of TLB operations must affect all cores */
710 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
711                              uint64_t value)
712 {
713     CPUState *cs = env_cpu(env);
714 
715     tlb_flush_all_cpus_synced(cs);
716 }
717 
718 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
719                              uint64_t value)
720 {
721     CPUState *cs = env_cpu(env);
722 
723     tlb_flush_all_cpus_synced(cs);
724 }
725 
726 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
727                              uint64_t value)
728 {
729     CPUState *cs = env_cpu(env);
730 
731     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
732 }
733 
734 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
735                              uint64_t value)
736 {
737     CPUState *cs = env_cpu(env);
738 
739     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
740 }
741 
742 /*
743  * Non-IS variants of TLB operations are upgraded to
744  * IS versions if we are at EL1 and HCR_EL2.FB is effectively set to
745  * force broadcast of these operations.
746  */
747 static bool tlb_force_broadcast(CPUARMState *env)
748 {
749     return arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_FB);
750 }
751 
752 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
753                           uint64_t value)
754 {
755     /* Invalidate all (TLBIALL) */
756     CPUState *cs = env_cpu(env);
757 
758     if (tlb_force_broadcast(env)) {
759         tlb_flush_all_cpus_synced(cs);
760     } else {
761         tlb_flush(cs);
762     }
763 }
764 
765 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
766                           uint64_t value)
767 {
768     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
769     CPUState *cs = env_cpu(env);
770 
771     value &= TARGET_PAGE_MASK;
772     if (tlb_force_broadcast(env)) {
773         tlb_flush_page_all_cpus_synced(cs, value);
774     } else {
775         tlb_flush_page(cs, value);
776     }
777 }
778 
779 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
780                            uint64_t value)
781 {
782     /* Invalidate by ASID (TLBIASID) */
783     CPUState *cs = env_cpu(env);
784 
785     if (tlb_force_broadcast(env)) {
786         tlb_flush_all_cpus_synced(cs);
787     } else {
788         tlb_flush(cs);
789     }
790 }
791 
792 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
793                            uint64_t value)
794 {
795     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
796     CPUState *cs = env_cpu(env);
797 
798     value &= TARGET_PAGE_MASK;
799     if (tlb_force_broadcast(env)) {
800         tlb_flush_page_all_cpus_synced(cs, value);
801     } else {
802         tlb_flush_page(cs, value);
803     }
804 }
805 
806 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
807                                uint64_t value)
808 {
809     CPUState *cs = env_cpu(env);
810 
811     tlb_flush_by_mmuidx(cs,
812                         ARMMMUIdxBit_E10_1 |
813                         ARMMMUIdxBit_E10_1_PAN |
814                         ARMMMUIdxBit_E10_0);
815 }
816 
817 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
818                                   uint64_t value)
819 {
820     CPUState *cs = env_cpu(env);
821 
822     tlb_flush_by_mmuidx_all_cpus_synced(cs,
823                                         ARMMMUIdxBit_E10_1 |
824                                         ARMMMUIdxBit_E10_1_PAN |
825                                         ARMMMUIdxBit_E10_0);
826 }
827 
828 
829 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
830                               uint64_t value)
831 {
832     CPUState *cs = env_cpu(env);
833 
834     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_E2);
835 }
836 
837 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
838                                  uint64_t value)
839 {
840     CPUState *cs = env_cpu(env);
841 
842     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_E2);
843 }
844 
845 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
846                               uint64_t value)
847 {
848     CPUState *cs = env_cpu(env);
849     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
850 
851     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_E2);
852 }
853 
854 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
855                                  uint64_t value)
856 {
857     CPUState *cs = env_cpu(env);
858     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
859 
860     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
861                                              ARMMMUIdxBit_E2);
862 }
863 
864 static const ARMCPRegInfo cp_reginfo[] = {
865     /* Define the secure and non-secure FCSE identifier CP registers
866      * separately because there is no secure bank in V8 (no _EL3).  This allows
867      * the secure register to be properly reset and migrated. There is also no
868      * v8 EL1 version of the register so the non-secure instance stands alone.
869      */
870     { .name = "FCSEIDR",
871       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
872       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
873       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
874       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
875     { .name = "FCSEIDR_S",
876       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
877       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
878       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
879       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
880     /* Define the secure and non-secure context identifier CP registers
881      * separately because there is no secure bank in V8 (no _EL3).  This allows
882      * the secure register to be properly reset and migrated.  In the
883      * non-secure case, the 32-bit register will have reset and migration
884      * disabled during registration as it is handled by the 64-bit instance.
885      */
886     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
887       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
888       .access = PL1_RW, .accessfn = access_tvm_trvm,
889       .secure = ARM_CP_SECSTATE_NS,
890       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
891       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
892     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
893       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
894       .access = PL1_RW, .accessfn = access_tvm_trvm,
895       .secure = ARM_CP_SECSTATE_S,
896       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
897       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
898     REGINFO_SENTINEL
899 };
900 
901 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
902     /* NB: Some of these registers exist in v8 but with more precise
903      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
904      */
905     /* MMU Domain access control / MPU write buffer control */
906     { .name = "DACR",
907       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
908       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
909       .writefn = dacr_write, .raw_writefn = raw_write,
910       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
911                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
912     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
913      * For v6 and v5, these mappings are overly broad.
914      */
915     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
916       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
917     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
918       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
919     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
920       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
921     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
922       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
923     /* Cache maintenance ops; some of this space may be overridden later. */
924     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
925       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
926       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
927     REGINFO_SENTINEL
928 };
929 
930 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
931     /* Not all pre-v6 cores implemented this WFI, so this is slightly
932      * over-broad.
933      */
934     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
935       .access = PL1_W, .type = ARM_CP_WFI },
936     REGINFO_SENTINEL
937 };
938 
939 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
940     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
941      * is UNPREDICTABLE; we choose to NOP as most implementations do).
942      */
943     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
944       .access = PL1_W, .type = ARM_CP_WFI },
945     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
946      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
947      * OMAPCP will override this space.
948      */
949     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
950       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
951       .resetvalue = 0 },
952     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
953       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
954       .resetvalue = 0 },
955     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
956     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
957       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
958       .resetvalue = 0 },
959     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
960      * implementing it as RAZ means the "debug architecture version" bits
961      * will read as a reserved value, which should cause Linux to not try
962      * to use the debug hardware.
963      */
964     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
965       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
966     /* MMU TLB control. Note that the wildcarding means we cover not just
967      * the unified TLB ops but also the dside/iside/inner-shareable variants.
968      */
969     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
970       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
971       .type = ARM_CP_NO_RAW },
972     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
973       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
974       .type = ARM_CP_NO_RAW },
975     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
976       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
977       .type = ARM_CP_NO_RAW },
978     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
979       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
980       .type = ARM_CP_NO_RAW },
981     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
982       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
983     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
984       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
985     REGINFO_SENTINEL
986 };
987 
988 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
989                         uint64_t value)
990 {
991     uint32_t mask = 0;
992 
993     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
994     if (!arm_feature(env, ARM_FEATURE_V8)) {
995         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
996          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
997          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
998          */
999         if (cpu_isar_feature(aa32_vfp_simd, env_archcpu(env))) {
1000             /* VFP coprocessor: cp10 & cp11 [23:20] */
1001             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
1002 
1003             if (!arm_feature(env, ARM_FEATURE_NEON)) {
1004                 /* ASEDIS [31] bit is RAO/WI */
1005                 value |= (1 << 31);
1006             }
1007 
1008             /* VFPv3 and upwards with NEON implement 32 double precision
1009              * registers (D0-D31).
1010              */
1011             if (!cpu_isar_feature(aa32_simd_r32, env_archcpu(env))) {
1012                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
1013                 value |= (1 << 30);
1014             }
1015         }
1016         value &= mask;
1017     }
1018 
1019     /*
1020      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
1021      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
1022      */
1023     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
1024         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
1025         value &= ~(0xf << 20);
1026         value |= env->cp15.cpacr_el1 & (0xf << 20);
1027     }
1028 
1029     env->cp15.cpacr_el1 = value;
1030 }
1031 
1032 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1033 {
1034     /*
1035      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
1036      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
1037      */
1038     uint64_t value = env->cp15.cpacr_el1;
1039 
1040     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
1041         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
1042         value &= ~(0xf << 20);
1043     }
1044     return value;
1045 }
1046 
1047 
1048 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1049 {
1050     /* Call cpacr_write() so that we reset with the correct RAO bits set
1051      * for our CPU features.
1052      */
1053     cpacr_write(env, ri, 0);
1054 }
1055 
1056 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1057                                    bool isread)
1058 {
1059     if (arm_feature(env, ARM_FEATURE_V8)) {
1060         /* Check if CPACR accesses are to be trapped to EL2 */
1061         if (arm_current_el(env) == 1 && arm_is_el2_enabled(env) &&
1062             (env->cp15.cptr_el[2] & CPTR_TCPAC)) {
1063             return CP_ACCESS_TRAP_EL2;
1064         /* Check if CPACR accesses are to be trapped to EL3 */
1065         } else if (arm_current_el(env) < 3 &&
1066                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
1067             return CP_ACCESS_TRAP_EL3;
1068         }
1069     }
1070 
1071     return CP_ACCESS_OK;
1072 }
1073 
1074 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1075                                   bool isread)
1076 {
1077     /* Check if CPTR accesses are set to trap to EL3 */
1078     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
1079         return CP_ACCESS_TRAP_EL3;
1080     }
1081 
1082     return CP_ACCESS_OK;
1083 }
1084 
1085 static const ARMCPRegInfo v6_cp_reginfo[] = {
1086     /* prefetch by MVA in v6, NOP in v7 */
1087     { .name = "MVA_prefetch",
1088       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
1089       .access = PL1_W, .type = ARM_CP_NOP },
1090     /* We need to break the TB after ISB to execute self-modifying code
1091      * correctly and also to take any pending interrupts immediately.
1092      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
1093      */
1094     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
1095       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
1096     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
1097       .access = PL0_W, .type = ARM_CP_NOP },
1098     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
1099       .access = PL0_W, .type = ARM_CP_NOP },
1100     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
1101       .access = PL1_RW, .accessfn = access_tvm_trvm,
1102       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
1103                              offsetof(CPUARMState, cp15.ifar_ns) },
1104       .resetvalue = 0, },
1105     /* Watchpoint Fault Address Register : should actually only be present
1106      * for 1136, 1176, 11MPCore.
1107      */
1108     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
1109       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
1110     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
1111       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
1112       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
1113       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
1114     REGINFO_SENTINEL
1115 };
1116 
1117 /* Definitions for the PMU registers */
1118 #define PMCRN_MASK  0xf800
1119 #define PMCRN_SHIFT 11
1120 #define PMCRLC  0x40
1121 #define PMCRDP  0x20
1122 #define PMCRX   0x10
1123 #define PMCRD   0x8
1124 #define PMCRC   0x4
1125 #define PMCRP   0x2
1126 #define PMCRE   0x1
1127 /*
1128  * Mask of PMCR bits writeable by guest (not including WO bits like C, P,
1129  * which can be written as 1 to trigger behaviour but which stay RAZ).
1130  */
1131 #define PMCR_WRITEABLE_MASK (PMCRLC | PMCRDP | PMCRX | PMCRD | PMCRE)
1132 
1133 #define PMXEVTYPER_P          0x80000000
1134 #define PMXEVTYPER_U          0x40000000
1135 #define PMXEVTYPER_NSK        0x20000000
1136 #define PMXEVTYPER_NSU        0x10000000
1137 #define PMXEVTYPER_NSH        0x08000000
1138 #define PMXEVTYPER_M          0x04000000
1139 #define PMXEVTYPER_MT         0x02000000
1140 #define PMXEVTYPER_EVTCOUNT   0x0000ffff
1141 #define PMXEVTYPER_MASK       (PMXEVTYPER_P | PMXEVTYPER_U | PMXEVTYPER_NSK | \
1142                                PMXEVTYPER_NSU | PMXEVTYPER_NSH | \
1143                                PMXEVTYPER_M | PMXEVTYPER_MT | \
1144                                PMXEVTYPER_EVTCOUNT)
1145 
1146 #define PMCCFILTR             0xf8000000
1147 #define PMCCFILTR_M           PMXEVTYPER_M
1148 #define PMCCFILTR_EL0         (PMCCFILTR | PMCCFILTR_M)
1149 
1150 static inline uint32_t pmu_num_counters(CPUARMState *env)
1151 {
1152   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
1153 }
1154 
1155 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1156 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1157 {
1158   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1159 }
1160 
1161 typedef struct pm_event {
1162     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1163     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1164     bool (*supported)(CPUARMState *);
1165     /*
1166      * Retrieve the current count of the underlying event. The programmed
1167      * counters hold a difference from the return value from this function
1168      */
1169     uint64_t (*get_count)(CPUARMState *);
1170     /*
1171      * Return how many nanoseconds it will take (at a minimum) for count events
1172      * to occur. A negative value indicates the counter will never overflow, or
1173      * that the counter has otherwise arranged for the overflow bit to be set
1174      * and the PMU interrupt to be raised on overflow.
1175      */
1176     int64_t (*ns_per_count)(uint64_t);
1177 } pm_event;
1178 
1179 static bool event_always_supported(CPUARMState *env)
1180 {
1181     return true;
1182 }
1183 
1184 static uint64_t swinc_get_count(CPUARMState *env)
1185 {
1186     /*
1187      * SW_INCR events are written directly to the pmevcntr's by writes to
1188      * PMSWINC, so there is no underlying count maintained by the PMU itself
1189      */
1190     return 0;
1191 }
1192 
1193 static int64_t swinc_ns_per(uint64_t ignored)
1194 {
1195     return -1;
1196 }
1197 
1198 /*
1199  * Return the underlying cycle count for the PMU cycle counters. If we're in
1200  * usermode, simply return 0.
1201  */
1202 static uint64_t cycles_get_count(CPUARMState *env)
1203 {
1204 #ifndef CONFIG_USER_ONLY
1205     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1206                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1207 #else
1208     return cpu_get_host_ticks();
1209 #endif
1210 }
1211 
1212 #ifndef CONFIG_USER_ONLY
1213 static int64_t cycles_ns_per(uint64_t cycles)
1214 {
1215     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1216 }
1217 
1218 static bool instructions_supported(CPUARMState *env)
1219 {
1220     return icount_enabled() == 1; /* Precise instruction counting */
1221 }
1222 
1223 static uint64_t instructions_get_count(CPUARMState *env)
1224 {
1225     return (uint64_t)icount_get_raw();
1226 }
1227 
1228 static int64_t instructions_ns_per(uint64_t icount)
1229 {
1230     return icount_to_ns((int64_t)icount);
1231 }
1232 #endif
1233 
1234 static bool pmu_8_1_events_supported(CPUARMState *env)
1235 {
1236     /* For events which are supported in any v8.1 PMU */
1237     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
1238 }
1239 
1240 static bool pmu_8_4_events_supported(CPUARMState *env)
1241 {
1242     /* For events which are supported in any v8.1 PMU */
1243     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
1244 }
1245 
1246 static uint64_t zero_event_get_count(CPUARMState *env)
1247 {
1248     /* For events which on QEMU never fire, so their count is always zero */
1249     return 0;
1250 }
1251 
1252 static int64_t zero_event_ns_per(uint64_t cycles)
1253 {
1254     /* An event which never fires can never overflow */
1255     return -1;
1256 }
1257 
1258 static const pm_event pm_events[] = {
1259     { .number = 0x000, /* SW_INCR */
1260       .supported = event_always_supported,
1261       .get_count = swinc_get_count,
1262       .ns_per_count = swinc_ns_per,
1263     },
1264 #ifndef CONFIG_USER_ONLY
1265     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1266       .supported = instructions_supported,
1267       .get_count = instructions_get_count,
1268       .ns_per_count = instructions_ns_per,
1269     },
1270     { .number = 0x011, /* CPU_CYCLES, Cycle */
1271       .supported = event_always_supported,
1272       .get_count = cycles_get_count,
1273       .ns_per_count = cycles_ns_per,
1274     },
1275 #endif
1276     { .number = 0x023, /* STALL_FRONTEND */
1277       .supported = pmu_8_1_events_supported,
1278       .get_count = zero_event_get_count,
1279       .ns_per_count = zero_event_ns_per,
1280     },
1281     { .number = 0x024, /* STALL_BACKEND */
1282       .supported = pmu_8_1_events_supported,
1283       .get_count = zero_event_get_count,
1284       .ns_per_count = zero_event_ns_per,
1285     },
1286     { .number = 0x03c, /* STALL */
1287       .supported = pmu_8_4_events_supported,
1288       .get_count = zero_event_get_count,
1289       .ns_per_count = zero_event_ns_per,
1290     },
1291 };
1292 
1293 /*
1294  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1295  * events (i.e. the statistical profiling extension), this implementation
1296  * should first be updated to something sparse instead of the current
1297  * supported_event_map[] array.
1298  */
1299 #define MAX_EVENT_ID 0x3c
1300 #define UNSUPPORTED_EVENT UINT16_MAX
1301 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1302 
1303 /*
1304  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1305  * of ARM event numbers to indices in our pm_events array.
1306  *
1307  * Note: Events in the 0x40XX range are not currently supported.
1308  */
1309 void pmu_init(ARMCPU *cpu)
1310 {
1311     unsigned int i;
1312 
1313     /*
1314      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1315      * events to them
1316      */
1317     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1318         supported_event_map[i] = UNSUPPORTED_EVENT;
1319     }
1320     cpu->pmceid0 = 0;
1321     cpu->pmceid1 = 0;
1322 
1323     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1324         const pm_event *cnt = &pm_events[i];
1325         assert(cnt->number <= MAX_EVENT_ID);
1326         /* We do not currently support events in the 0x40xx range */
1327         assert(cnt->number <= 0x3f);
1328 
1329         if (cnt->supported(&cpu->env)) {
1330             supported_event_map[cnt->number] = i;
1331             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1332             if (cnt->number & 0x20) {
1333                 cpu->pmceid1 |= event_mask;
1334             } else {
1335                 cpu->pmceid0 |= event_mask;
1336             }
1337         }
1338     }
1339 }
1340 
1341 /*
1342  * Check at runtime whether a PMU event is supported for the current machine
1343  */
1344 static bool event_supported(uint16_t number)
1345 {
1346     if (number > MAX_EVENT_ID) {
1347         return false;
1348     }
1349     return supported_event_map[number] != UNSUPPORTED_EVENT;
1350 }
1351 
1352 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1353                                    bool isread)
1354 {
1355     /* Performance monitor registers user accessibility is controlled
1356      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1357      * trapping to EL2 or EL3 for other accesses.
1358      */
1359     int el = arm_current_el(env);
1360     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1361 
1362     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1363         return CP_ACCESS_TRAP;
1364     }
1365     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
1366         return CP_ACCESS_TRAP_EL2;
1367     }
1368     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1369         return CP_ACCESS_TRAP_EL3;
1370     }
1371 
1372     return CP_ACCESS_OK;
1373 }
1374 
1375 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1376                                            const ARMCPRegInfo *ri,
1377                                            bool isread)
1378 {
1379     /* ER: event counter read trap control */
1380     if (arm_feature(env, ARM_FEATURE_V8)
1381         && arm_current_el(env) == 0
1382         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1383         && isread) {
1384         return CP_ACCESS_OK;
1385     }
1386 
1387     return pmreg_access(env, ri, isread);
1388 }
1389 
1390 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1391                                          const ARMCPRegInfo *ri,
1392                                          bool isread)
1393 {
1394     /* SW: software increment write trap control */
1395     if (arm_feature(env, ARM_FEATURE_V8)
1396         && arm_current_el(env) == 0
1397         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1398         && !isread) {
1399         return CP_ACCESS_OK;
1400     }
1401 
1402     return pmreg_access(env, ri, isread);
1403 }
1404 
1405 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1406                                         const ARMCPRegInfo *ri,
1407                                         bool isread)
1408 {
1409     /* ER: event counter read trap control */
1410     if (arm_feature(env, ARM_FEATURE_V8)
1411         && arm_current_el(env) == 0
1412         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1413         return CP_ACCESS_OK;
1414     }
1415 
1416     return pmreg_access(env, ri, isread);
1417 }
1418 
1419 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1420                                          const ARMCPRegInfo *ri,
1421                                          bool isread)
1422 {
1423     /* CR: cycle counter read trap control */
1424     if (arm_feature(env, ARM_FEATURE_V8)
1425         && arm_current_el(env) == 0
1426         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1427         && isread) {
1428         return CP_ACCESS_OK;
1429     }
1430 
1431     return pmreg_access(env, ri, isread);
1432 }
1433 
1434 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1435  * the current EL, security state, and register configuration.
1436  */
1437 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1438 {
1439     uint64_t filter;
1440     bool e, p, u, nsk, nsu, nsh, m;
1441     bool enabled, prohibited, filtered;
1442     bool secure = arm_is_secure(env);
1443     int el = arm_current_el(env);
1444     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1445     uint8_t hpmn = mdcr_el2 & MDCR_HPMN;
1446 
1447     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1448         return false;
1449     }
1450 
1451     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1452             (counter < hpmn || counter == 31)) {
1453         e = env->cp15.c9_pmcr & PMCRE;
1454     } else {
1455         e = mdcr_el2 & MDCR_HPME;
1456     }
1457     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1458 
1459     if (!secure) {
1460         if (el == 2 && (counter < hpmn || counter == 31)) {
1461             prohibited = mdcr_el2 & MDCR_HPMD;
1462         } else {
1463             prohibited = false;
1464         }
1465     } else {
1466         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1467            !(env->cp15.mdcr_el3 & MDCR_SPME);
1468     }
1469 
1470     if (prohibited && counter == 31) {
1471         prohibited = env->cp15.c9_pmcr & PMCRDP;
1472     }
1473 
1474     if (counter == 31) {
1475         filter = env->cp15.pmccfiltr_el0;
1476     } else {
1477         filter = env->cp15.c14_pmevtyper[counter];
1478     }
1479 
1480     p   = filter & PMXEVTYPER_P;
1481     u   = filter & PMXEVTYPER_U;
1482     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1483     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1484     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1485     m   = arm_el_is_aa64(env, 1) &&
1486               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1487 
1488     if (el == 0) {
1489         filtered = secure ? u : u != nsu;
1490     } else if (el == 1) {
1491         filtered = secure ? p : p != nsk;
1492     } else if (el == 2) {
1493         filtered = !nsh;
1494     } else { /* EL3 */
1495         filtered = m != p;
1496     }
1497 
1498     if (counter != 31) {
1499         /*
1500          * If not checking PMCCNTR, ensure the counter is setup to an event we
1501          * support
1502          */
1503         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1504         if (!event_supported(event)) {
1505             return false;
1506         }
1507     }
1508 
1509     return enabled && !prohibited && !filtered;
1510 }
1511 
1512 static void pmu_update_irq(CPUARMState *env)
1513 {
1514     ARMCPU *cpu = env_archcpu(env);
1515     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1516             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1517 }
1518 
1519 /*
1520  * Ensure c15_ccnt is the guest-visible count so that operations such as
1521  * enabling/disabling the counter or filtering, modifying the count itself,
1522  * etc. can be done logically. This is essentially a no-op if the counter is
1523  * not enabled at the time of the call.
1524  */
1525 static void pmccntr_op_start(CPUARMState *env)
1526 {
1527     uint64_t cycles = cycles_get_count(env);
1528 
1529     if (pmu_counter_enabled(env, 31)) {
1530         uint64_t eff_cycles = cycles;
1531         if (env->cp15.c9_pmcr & PMCRD) {
1532             /* Increment once every 64 processor clock cycles */
1533             eff_cycles /= 64;
1534         }
1535 
1536         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1537 
1538         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1539                                  1ull << 63 : 1ull << 31;
1540         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1541             env->cp15.c9_pmovsr |= (1 << 31);
1542             pmu_update_irq(env);
1543         }
1544 
1545         env->cp15.c15_ccnt = new_pmccntr;
1546     }
1547     env->cp15.c15_ccnt_delta = cycles;
1548 }
1549 
1550 /*
1551  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1552  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1553  * pmccntr_op_start.
1554  */
1555 static void pmccntr_op_finish(CPUARMState *env)
1556 {
1557     if (pmu_counter_enabled(env, 31)) {
1558 #ifndef CONFIG_USER_ONLY
1559         /* Calculate when the counter will next overflow */
1560         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1561         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1562             remaining_cycles = (uint32_t)remaining_cycles;
1563         }
1564         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1565 
1566         if (overflow_in > 0) {
1567             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1568                 overflow_in;
1569             ARMCPU *cpu = env_archcpu(env);
1570             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1571         }
1572 #endif
1573 
1574         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1575         if (env->cp15.c9_pmcr & PMCRD) {
1576             /* Increment once every 64 processor clock cycles */
1577             prev_cycles /= 64;
1578         }
1579         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1580     }
1581 }
1582 
1583 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1584 {
1585 
1586     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1587     uint64_t count = 0;
1588     if (event_supported(event)) {
1589         uint16_t event_idx = supported_event_map[event];
1590         count = pm_events[event_idx].get_count(env);
1591     }
1592 
1593     if (pmu_counter_enabled(env, counter)) {
1594         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1595 
1596         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1597             env->cp15.c9_pmovsr |= (1 << counter);
1598             pmu_update_irq(env);
1599         }
1600         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1601     }
1602     env->cp15.c14_pmevcntr_delta[counter] = count;
1603 }
1604 
1605 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1606 {
1607     if (pmu_counter_enabled(env, counter)) {
1608 #ifndef CONFIG_USER_ONLY
1609         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1610         uint16_t event_idx = supported_event_map[event];
1611         uint64_t delta = UINT32_MAX -
1612             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1613         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1614 
1615         if (overflow_in > 0) {
1616             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1617                 overflow_in;
1618             ARMCPU *cpu = env_archcpu(env);
1619             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1620         }
1621 #endif
1622 
1623         env->cp15.c14_pmevcntr_delta[counter] -=
1624             env->cp15.c14_pmevcntr[counter];
1625     }
1626 }
1627 
1628 void pmu_op_start(CPUARMState *env)
1629 {
1630     unsigned int i;
1631     pmccntr_op_start(env);
1632     for (i = 0; i < pmu_num_counters(env); i++) {
1633         pmevcntr_op_start(env, i);
1634     }
1635 }
1636 
1637 void pmu_op_finish(CPUARMState *env)
1638 {
1639     unsigned int i;
1640     pmccntr_op_finish(env);
1641     for (i = 0; i < pmu_num_counters(env); i++) {
1642         pmevcntr_op_finish(env, i);
1643     }
1644 }
1645 
1646 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1647 {
1648     pmu_op_start(&cpu->env);
1649 }
1650 
1651 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1652 {
1653     pmu_op_finish(&cpu->env);
1654 }
1655 
1656 void arm_pmu_timer_cb(void *opaque)
1657 {
1658     ARMCPU *cpu = opaque;
1659 
1660     /*
1661      * Update all the counter values based on the current underlying counts,
1662      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1663      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1664      * counter may expire.
1665      */
1666     pmu_op_start(&cpu->env);
1667     pmu_op_finish(&cpu->env);
1668 }
1669 
1670 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1671                        uint64_t value)
1672 {
1673     pmu_op_start(env);
1674 
1675     if (value & PMCRC) {
1676         /* The counter has been reset */
1677         env->cp15.c15_ccnt = 0;
1678     }
1679 
1680     if (value & PMCRP) {
1681         unsigned int i;
1682         for (i = 0; i < pmu_num_counters(env); i++) {
1683             env->cp15.c14_pmevcntr[i] = 0;
1684         }
1685     }
1686 
1687     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1688     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1689 
1690     pmu_op_finish(env);
1691 }
1692 
1693 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1694                           uint64_t value)
1695 {
1696     unsigned int i;
1697     for (i = 0; i < pmu_num_counters(env); i++) {
1698         /* Increment a counter's count iff: */
1699         if ((value & (1 << i)) && /* counter's bit is set */
1700                 /* counter is enabled and not filtered */
1701                 pmu_counter_enabled(env, i) &&
1702                 /* counter is SW_INCR */
1703                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1704             pmevcntr_op_start(env, i);
1705 
1706             /*
1707              * Detect if this write causes an overflow since we can't predict
1708              * PMSWINC overflows like we can for other events
1709              */
1710             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1711 
1712             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1713                 env->cp15.c9_pmovsr |= (1 << i);
1714                 pmu_update_irq(env);
1715             }
1716 
1717             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1718 
1719             pmevcntr_op_finish(env, i);
1720         }
1721     }
1722 }
1723 
1724 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1725 {
1726     uint64_t ret;
1727     pmccntr_op_start(env);
1728     ret = env->cp15.c15_ccnt;
1729     pmccntr_op_finish(env);
1730     return ret;
1731 }
1732 
1733 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1734                          uint64_t value)
1735 {
1736     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1737      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1738      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1739      * accessed.
1740      */
1741     env->cp15.c9_pmselr = value & 0x1f;
1742 }
1743 
1744 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1745                         uint64_t value)
1746 {
1747     pmccntr_op_start(env);
1748     env->cp15.c15_ccnt = value;
1749     pmccntr_op_finish(env);
1750 }
1751 
1752 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1753                             uint64_t value)
1754 {
1755     uint64_t cur_val = pmccntr_read(env, NULL);
1756 
1757     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1758 }
1759 
1760 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1761                             uint64_t value)
1762 {
1763     pmccntr_op_start(env);
1764     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1765     pmccntr_op_finish(env);
1766 }
1767 
1768 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1769                             uint64_t value)
1770 {
1771     pmccntr_op_start(env);
1772     /* M is not accessible from AArch32 */
1773     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1774         (value & PMCCFILTR);
1775     pmccntr_op_finish(env);
1776 }
1777 
1778 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1779 {
1780     /* M is not visible in AArch32 */
1781     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1782 }
1783 
1784 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1785                             uint64_t value)
1786 {
1787     value &= pmu_counter_mask(env);
1788     env->cp15.c9_pmcnten |= value;
1789 }
1790 
1791 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1792                              uint64_t value)
1793 {
1794     value &= pmu_counter_mask(env);
1795     env->cp15.c9_pmcnten &= ~value;
1796 }
1797 
1798 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1799                          uint64_t value)
1800 {
1801     value &= pmu_counter_mask(env);
1802     env->cp15.c9_pmovsr &= ~value;
1803     pmu_update_irq(env);
1804 }
1805 
1806 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1807                          uint64_t value)
1808 {
1809     value &= pmu_counter_mask(env);
1810     env->cp15.c9_pmovsr |= value;
1811     pmu_update_irq(env);
1812 }
1813 
1814 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1815                              uint64_t value, const uint8_t counter)
1816 {
1817     if (counter == 31) {
1818         pmccfiltr_write(env, ri, value);
1819     } else if (counter < pmu_num_counters(env)) {
1820         pmevcntr_op_start(env, counter);
1821 
1822         /*
1823          * If this counter's event type is changing, store the current
1824          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1825          * pmevcntr_op_finish has the correct baseline when it converts back to
1826          * a delta.
1827          */
1828         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1829             PMXEVTYPER_EVTCOUNT;
1830         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1831         if (old_event != new_event) {
1832             uint64_t count = 0;
1833             if (event_supported(new_event)) {
1834                 uint16_t event_idx = supported_event_map[new_event];
1835                 count = pm_events[event_idx].get_count(env);
1836             }
1837             env->cp15.c14_pmevcntr_delta[counter] = count;
1838         }
1839 
1840         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1841         pmevcntr_op_finish(env, counter);
1842     }
1843     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1844      * PMSELR value is equal to or greater than the number of implemented
1845      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1846      */
1847 }
1848 
1849 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1850                                const uint8_t counter)
1851 {
1852     if (counter == 31) {
1853         return env->cp15.pmccfiltr_el0;
1854     } else if (counter < pmu_num_counters(env)) {
1855         return env->cp15.c14_pmevtyper[counter];
1856     } else {
1857       /*
1858        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1859        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1860        */
1861         return 0;
1862     }
1863 }
1864 
1865 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1866                               uint64_t value)
1867 {
1868     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1869     pmevtyper_write(env, ri, value, counter);
1870 }
1871 
1872 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1873                                uint64_t value)
1874 {
1875     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1876     env->cp15.c14_pmevtyper[counter] = value;
1877 
1878     /*
1879      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1880      * pmu_op_finish calls when loading saved state for a migration. Because
1881      * we're potentially updating the type of event here, the value written to
1882      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1883      * different counter type. Therefore, we need to set this value to the
1884      * current count for the counter type we're writing so that pmu_op_finish
1885      * has the correct count for its calculation.
1886      */
1887     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1888     if (event_supported(event)) {
1889         uint16_t event_idx = supported_event_map[event];
1890         env->cp15.c14_pmevcntr_delta[counter] =
1891             pm_events[event_idx].get_count(env);
1892     }
1893 }
1894 
1895 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1896 {
1897     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1898     return pmevtyper_read(env, ri, counter);
1899 }
1900 
1901 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1902                              uint64_t value)
1903 {
1904     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1905 }
1906 
1907 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1908 {
1909     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1910 }
1911 
1912 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1913                              uint64_t value, uint8_t counter)
1914 {
1915     if (counter < pmu_num_counters(env)) {
1916         pmevcntr_op_start(env, counter);
1917         env->cp15.c14_pmevcntr[counter] = value;
1918         pmevcntr_op_finish(env, counter);
1919     }
1920     /*
1921      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1922      * are CONSTRAINED UNPREDICTABLE.
1923      */
1924 }
1925 
1926 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1927                               uint8_t counter)
1928 {
1929     if (counter < pmu_num_counters(env)) {
1930         uint64_t ret;
1931         pmevcntr_op_start(env, counter);
1932         ret = env->cp15.c14_pmevcntr[counter];
1933         pmevcntr_op_finish(env, counter);
1934         return ret;
1935     } else {
1936       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1937        * are CONSTRAINED UNPREDICTABLE. */
1938         return 0;
1939     }
1940 }
1941 
1942 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1943                              uint64_t value)
1944 {
1945     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1946     pmevcntr_write(env, ri, value, counter);
1947 }
1948 
1949 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1950 {
1951     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1952     return pmevcntr_read(env, ri, counter);
1953 }
1954 
1955 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1956                              uint64_t value)
1957 {
1958     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1959     assert(counter < pmu_num_counters(env));
1960     env->cp15.c14_pmevcntr[counter] = value;
1961     pmevcntr_write(env, ri, value, counter);
1962 }
1963 
1964 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1965 {
1966     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1967     assert(counter < pmu_num_counters(env));
1968     return env->cp15.c14_pmevcntr[counter];
1969 }
1970 
1971 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1972                              uint64_t value)
1973 {
1974     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1975 }
1976 
1977 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1978 {
1979     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1980 }
1981 
1982 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1983                             uint64_t value)
1984 {
1985     if (arm_feature(env, ARM_FEATURE_V8)) {
1986         env->cp15.c9_pmuserenr = value & 0xf;
1987     } else {
1988         env->cp15.c9_pmuserenr = value & 1;
1989     }
1990 }
1991 
1992 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1993                              uint64_t value)
1994 {
1995     /* We have no event counters so only the C bit can be changed */
1996     value &= pmu_counter_mask(env);
1997     env->cp15.c9_pminten |= value;
1998     pmu_update_irq(env);
1999 }
2000 
2001 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2002                              uint64_t value)
2003 {
2004     value &= pmu_counter_mask(env);
2005     env->cp15.c9_pminten &= ~value;
2006     pmu_update_irq(env);
2007 }
2008 
2009 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
2010                        uint64_t value)
2011 {
2012     /* Note that even though the AArch64 view of this register has bits
2013      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
2014      * architectural requirements for bits which are RES0 only in some
2015      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
2016      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
2017      */
2018     raw_write(env, ri, value & ~0x1FULL);
2019 }
2020 
2021 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2022 {
2023     /* Begin with base v8.0 state.  */
2024     uint32_t valid_mask = 0x3fff;
2025     ARMCPU *cpu = env_archcpu(env);
2026 
2027     if (ri->state == ARM_CP_STATE_AA64) {
2028         if (arm_feature(env, ARM_FEATURE_AARCH64) &&
2029             !cpu_isar_feature(aa64_aa32_el1, cpu)) {
2030                 value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
2031         }
2032         valid_mask &= ~SCR_NET;
2033 
2034         if (cpu_isar_feature(aa64_lor, cpu)) {
2035             valid_mask |= SCR_TLOR;
2036         }
2037         if (cpu_isar_feature(aa64_pauth, cpu)) {
2038             valid_mask |= SCR_API | SCR_APK;
2039         }
2040         if (cpu_isar_feature(aa64_sel2, cpu)) {
2041             valid_mask |= SCR_EEL2;
2042         }
2043         if (cpu_isar_feature(aa64_mte, cpu)) {
2044             valid_mask |= SCR_ATA;
2045         }
2046     } else {
2047         valid_mask &= ~(SCR_RW | SCR_ST);
2048     }
2049 
2050     if (!arm_feature(env, ARM_FEATURE_EL2)) {
2051         valid_mask &= ~SCR_HCE;
2052 
2053         /* On ARMv7, SMD (or SCD as it is called in v7) is only
2054          * supported if EL2 exists. The bit is UNK/SBZP when
2055          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
2056          * when EL2 is unavailable.
2057          * On ARMv8, this bit is always available.
2058          */
2059         if (arm_feature(env, ARM_FEATURE_V7) &&
2060             !arm_feature(env, ARM_FEATURE_V8)) {
2061             valid_mask &= ~SCR_SMD;
2062         }
2063     }
2064 
2065     /* Clear all-context RES0 bits.  */
2066     value &= valid_mask;
2067     raw_write(env, ri, value);
2068 }
2069 
2070 static void scr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2071 {
2072     /*
2073      * scr_write will set the RES1 bits on an AArch64-only CPU.
2074      * The reset value will be 0x30 on an AArch64-only CPU and 0 otherwise.
2075      */
2076     scr_write(env, ri, 0);
2077 }
2078 
2079 static CPAccessResult access_aa64_tid2(CPUARMState *env,
2080                                        const ARMCPRegInfo *ri,
2081                                        bool isread)
2082 {
2083     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
2084         return CP_ACCESS_TRAP_EL2;
2085     }
2086 
2087     return CP_ACCESS_OK;
2088 }
2089 
2090 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2091 {
2092     ARMCPU *cpu = env_archcpu(env);
2093 
2094     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
2095      * bank
2096      */
2097     uint32_t index = A32_BANKED_REG_GET(env, csselr,
2098                                         ri->secure & ARM_CP_SECSTATE_S);
2099 
2100     return cpu->ccsidr[index];
2101 }
2102 
2103 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2104                          uint64_t value)
2105 {
2106     raw_write(env, ri, value & 0xf);
2107 }
2108 
2109 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2110 {
2111     CPUState *cs = env_cpu(env);
2112     bool el1 = arm_current_el(env) == 1;
2113     uint64_t hcr_el2 = el1 ? arm_hcr_el2_eff(env) : 0;
2114     uint64_t ret = 0;
2115 
2116     if (hcr_el2 & HCR_IMO) {
2117         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
2118             ret |= CPSR_I;
2119         }
2120     } else {
2121         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
2122             ret |= CPSR_I;
2123         }
2124     }
2125 
2126     if (hcr_el2 & HCR_FMO) {
2127         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
2128             ret |= CPSR_F;
2129         }
2130     } else {
2131         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
2132             ret |= CPSR_F;
2133         }
2134     }
2135 
2136     /* External aborts are not possible in QEMU so A bit is always clear */
2137     return ret;
2138 }
2139 
2140 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2141                                        bool isread)
2142 {
2143     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
2144         return CP_ACCESS_TRAP_EL2;
2145     }
2146 
2147     return CP_ACCESS_OK;
2148 }
2149 
2150 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2151                                        bool isread)
2152 {
2153     if (arm_feature(env, ARM_FEATURE_V8)) {
2154         return access_aa64_tid1(env, ri, isread);
2155     }
2156 
2157     return CP_ACCESS_OK;
2158 }
2159 
2160 static const ARMCPRegInfo v7_cp_reginfo[] = {
2161     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
2162     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
2163       .access = PL1_W, .type = ARM_CP_NOP },
2164     /* Performance monitors are implementation defined in v7,
2165      * but with an ARM recommended set of registers, which we
2166      * follow.
2167      *
2168      * Performance registers fall into three categories:
2169      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
2170      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
2171      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
2172      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
2173      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
2174      */
2175     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
2176       .access = PL0_RW, .type = ARM_CP_ALIAS,
2177       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2178       .writefn = pmcntenset_write,
2179       .accessfn = pmreg_access,
2180       .raw_writefn = raw_write },
2181     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
2182       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
2183       .access = PL0_RW, .accessfn = pmreg_access,
2184       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
2185       .writefn = pmcntenset_write, .raw_writefn = raw_write },
2186     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
2187       .access = PL0_RW,
2188       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2189       .accessfn = pmreg_access,
2190       .writefn = pmcntenclr_write,
2191       .type = ARM_CP_ALIAS },
2192     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
2193       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
2194       .access = PL0_RW, .accessfn = pmreg_access,
2195       .type = ARM_CP_ALIAS,
2196       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
2197       .writefn = pmcntenclr_write },
2198     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
2199       .access = PL0_RW, .type = ARM_CP_IO,
2200       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2201       .accessfn = pmreg_access,
2202       .writefn = pmovsr_write,
2203       .raw_writefn = raw_write },
2204     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2205       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2206       .access = PL0_RW, .accessfn = pmreg_access,
2207       .type = ARM_CP_ALIAS | ARM_CP_IO,
2208       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2209       .writefn = pmovsr_write,
2210       .raw_writefn = raw_write },
2211     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2212       .access = PL0_W, .accessfn = pmreg_access_swinc,
2213       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2214       .writefn = pmswinc_write },
2215     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2216       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2217       .access = PL0_W, .accessfn = pmreg_access_swinc,
2218       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2219       .writefn = pmswinc_write },
2220     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2221       .access = PL0_RW, .type = ARM_CP_ALIAS,
2222       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2223       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2224       .raw_writefn = raw_write},
2225     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2226       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2227       .access = PL0_RW, .accessfn = pmreg_access_selr,
2228       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2229       .writefn = pmselr_write, .raw_writefn = raw_write, },
2230     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2231       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2232       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2233       .accessfn = pmreg_access_ccntr },
2234     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2235       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2236       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2237       .type = ARM_CP_IO,
2238       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2239       .readfn = pmccntr_read, .writefn = pmccntr_write,
2240       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2241     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2242       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2243       .access = PL0_RW, .accessfn = pmreg_access,
2244       .type = ARM_CP_ALIAS | ARM_CP_IO,
2245       .resetvalue = 0, },
2246     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2247       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2248       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2249       .access = PL0_RW, .accessfn = pmreg_access,
2250       .type = ARM_CP_IO,
2251       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2252       .resetvalue = 0, },
2253     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2254       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2255       .accessfn = pmreg_access,
2256       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2257     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2258       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2259       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2260       .accessfn = pmreg_access,
2261       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2262     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2263       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2264       .accessfn = pmreg_access_xevcntr,
2265       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2266     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2267       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2268       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2269       .accessfn = pmreg_access_xevcntr,
2270       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2271     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2272       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2273       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2274       .resetvalue = 0,
2275       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2276     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2277       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2278       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2279       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2280       .resetvalue = 0,
2281       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2282     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2283       .access = PL1_RW, .accessfn = access_tpm,
2284       .type = ARM_CP_ALIAS | ARM_CP_IO,
2285       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2286       .resetvalue = 0,
2287       .writefn = pmintenset_write, .raw_writefn = raw_write },
2288     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2289       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2290       .access = PL1_RW, .accessfn = access_tpm,
2291       .type = ARM_CP_IO,
2292       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2293       .writefn = pmintenset_write, .raw_writefn = raw_write,
2294       .resetvalue = 0x0 },
2295     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2296       .access = PL1_RW, .accessfn = access_tpm,
2297       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2298       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2299       .writefn = pmintenclr_write, },
2300     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2301       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2302       .access = PL1_RW, .accessfn = access_tpm,
2303       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2304       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2305       .writefn = pmintenclr_write },
2306     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2307       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2308       .access = PL1_R,
2309       .accessfn = access_aa64_tid2,
2310       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2311     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2312       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2313       .access = PL1_RW,
2314       .accessfn = access_aa64_tid2,
2315       .writefn = csselr_write, .resetvalue = 0,
2316       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2317                              offsetof(CPUARMState, cp15.csselr_ns) } },
2318     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2319      * just RAZ for all cores:
2320      */
2321     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2322       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2323       .access = PL1_R, .type = ARM_CP_CONST,
2324       .accessfn = access_aa64_tid1,
2325       .resetvalue = 0 },
2326     /* Auxiliary fault status registers: these also are IMPDEF, and we
2327      * choose to RAZ/WI for all cores.
2328      */
2329     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2330       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2331       .access = PL1_RW, .accessfn = access_tvm_trvm,
2332       .type = ARM_CP_CONST, .resetvalue = 0 },
2333     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2334       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2335       .access = PL1_RW, .accessfn = access_tvm_trvm,
2336       .type = ARM_CP_CONST, .resetvalue = 0 },
2337     /* MAIR can just read-as-written because we don't implement caches
2338      * and so don't need to care about memory attributes.
2339      */
2340     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2341       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2342       .access = PL1_RW, .accessfn = access_tvm_trvm,
2343       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2344       .resetvalue = 0 },
2345     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2346       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2347       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2348       .resetvalue = 0 },
2349     /* For non-long-descriptor page tables these are PRRR and NMRR;
2350      * regardless they still act as reads-as-written for QEMU.
2351      */
2352      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2353       * allows them to assign the correct fieldoffset based on the endianness
2354       * handled in the field definitions.
2355       */
2356     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2357       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2358       .access = PL1_RW, .accessfn = access_tvm_trvm,
2359       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2360                              offsetof(CPUARMState, cp15.mair0_ns) },
2361       .resetfn = arm_cp_reset_ignore },
2362     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2363       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2364       .access = PL1_RW, .accessfn = access_tvm_trvm,
2365       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2366                              offsetof(CPUARMState, cp15.mair1_ns) },
2367       .resetfn = arm_cp_reset_ignore },
2368     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2369       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2370       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2371     /* 32 bit ITLB invalidates */
2372     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2373       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2374       .writefn = tlbiall_write },
2375     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2376       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2377       .writefn = tlbimva_write },
2378     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2379       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2380       .writefn = tlbiasid_write },
2381     /* 32 bit DTLB invalidates */
2382     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2383       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2384       .writefn = tlbiall_write },
2385     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2386       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2387       .writefn = tlbimva_write },
2388     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2389       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2390       .writefn = tlbiasid_write },
2391     /* 32 bit TLB invalidates */
2392     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2393       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2394       .writefn = tlbiall_write },
2395     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2396       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2397       .writefn = tlbimva_write },
2398     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2399       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2400       .writefn = tlbiasid_write },
2401     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2402       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2403       .writefn = tlbimvaa_write },
2404     REGINFO_SENTINEL
2405 };
2406 
2407 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2408     /* 32 bit TLB invalidates, Inner Shareable */
2409     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2410       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2411       .writefn = tlbiall_is_write },
2412     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2413       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2414       .writefn = tlbimva_is_write },
2415     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2416       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2417       .writefn = tlbiasid_is_write },
2418     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2419       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2420       .writefn = tlbimvaa_is_write },
2421     REGINFO_SENTINEL
2422 };
2423 
2424 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2425     /* PMOVSSET is not implemented in v7 before v7ve */
2426     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2427       .access = PL0_RW, .accessfn = pmreg_access,
2428       .type = ARM_CP_ALIAS | ARM_CP_IO,
2429       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2430       .writefn = pmovsset_write,
2431       .raw_writefn = raw_write },
2432     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2433       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2434       .access = PL0_RW, .accessfn = pmreg_access,
2435       .type = ARM_CP_ALIAS | ARM_CP_IO,
2436       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2437       .writefn = pmovsset_write,
2438       .raw_writefn = raw_write },
2439     REGINFO_SENTINEL
2440 };
2441 
2442 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2443                         uint64_t value)
2444 {
2445     value &= 1;
2446     env->teecr = value;
2447 }
2448 
2449 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2450                                     bool isread)
2451 {
2452     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2453         return CP_ACCESS_TRAP;
2454     }
2455     return CP_ACCESS_OK;
2456 }
2457 
2458 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2459     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2460       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2461       .resetvalue = 0,
2462       .writefn = teecr_write },
2463     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2464       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2465       .accessfn = teehbr_access, .resetvalue = 0 },
2466     REGINFO_SENTINEL
2467 };
2468 
2469 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2470     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2471       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2472       .access = PL0_RW,
2473       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2474     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2475       .access = PL0_RW,
2476       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2477                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2478       .resetfn = arm_cp_reset_ignore },
2479     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2480       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2481       .access = PL0_R|PL1_W,
2482       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2483       .resetvalue = 0},
2484     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2485       .access = PL0_R|PL1_W,
2486       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2487                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2488       .resetfn = arm_cp_reset_ignore },
2489     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2490       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2491       .access = PL1_RW,
2492       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2493     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2494       .access = PL1_RW,
2495       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2496                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2497       .resetvalue = 0 },
2498     REGINFO_SENTINEL
2499 };
2500 
2501 #ifndef CONFIG_USER_ONLY
2502 
2503 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2504                                        bool isread)
2505 {
2506     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2507      * Writable only at the highest implemented exception level.
2508      */
2509     int el = arm_current_el(env);
2510     uint64_t hcr;
2511     uint32_t cntkctl;
2512 
2513     switch (el) {
2514     case 0:
2515         hcr = arm_hcr_el2_eff(env);
2516         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2517             cntkctl = env->cp15.cnthctl_el2;
2518         } else {
2519             cntkctl = env->cp15.c14_cntkctl;
2520         }
2521         if (!extract32(cntkctl, 0, 2)) {
2522             return CP_ACCESS_TRAP;
2523         }
2524         break;
2525     case 1:
2526         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2527             arm_is_secure_below_el3(env)) {
2528             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2529             return CP_ACCESS_TRAP_UNCATEGORIZED;
2530         }
2531         break;
2532     case 2:
2533     case 3:
2534         break;
2535     }
2536 
2537     if (!isread && el < arm_highest_el(env)) {
2538         return CP_ACCESS_TRAP_UNCATEGORIZED;
2539     }
2540 
2541     return CP_ACCESS_OK;
2542 }
2543 
2544 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2545                                         bool isread)
2546 {
2547     unsigned int cur_el = arm_current_el(env);
2548     bool has_el2 = arm_is_el2_enabled(env);
2549     uint64_t hcr = arm_hcr_el2_eff(env);
2550 
2551     switch (cur_el) {
2552     case 0:
2553         /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2554         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2555             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2556                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2557         }
2558 
2559         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2560         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2561             return CP_ACCESS_TRAP;
2562         }
2563 
2564         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2565         if (hcr & HCR_E2H) {
2566             if (timeridx == GTIMER_PHYS &&
2567                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2568                 return CP_ACCESS_TRAP_EL2;
2569             }
2570         } else {
2571             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2572             if (has_el2 && timeridx == GTIMER_PHYS &&
2573                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2574                 return CP_ACCESS_TRAP_EL2;
2575             }
2576         }
2577         break;
2578 
2579     case 1:
2580         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2581         if (has_el2 && timeridx == GTIMER_PHYS &&
2582             (hcr & HCR_E2H
2583              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2584              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2585             return CP_ACCESS_TRAP_EL2;
2586         }
2587         break;
2588     }
2589     return CP_ACCESS_OK;
2590 }
2591 
2592 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2593                                       bool isread)
2594 {
2595     unsigned int cur_el = arm_current_el(env);
2596     bool has_el2 = arm_is_el2_enabled(env);
2597     uint64_t hcr = arm_hcr_el2_eff(env);
2598 
2599     switch (cur_el) {
2600     case 0:
2601         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2602             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2603             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2604                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2605         }
2606 
2607         /*
2608          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2609          * EL0 if EL0[PV]TEN is zero.
2610          */
2611         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2612             return CP_ACCESS_TRAP;
2613         }
2614         /* fall through */
2615 
2616     case 1:
2617         if (has_el2 && timeridx == GTIMER_PHYS) {
2618             if (hcr & HCR_E2H) {
2619                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2620                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2621                     return CP_ACCESS_TRAP_EL2;
2622                 }
2623             } else {
2624                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2625                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2626                     return CP_ACCESS_TRAP_EL2;
2627                 }
2628             }
2629         }
2630         break;
2631     }
2632     return CP_ACCESS_OK;
2633 }
2634 
2635 static CPAccessResult gt_pct_access(CPUARMState *env,
2636                                     const ARMCPRegInfo *ri,
2637                                     bool isread)
2638 {
2639     return gt_counter_access(env, GTIMER_PHYS, isread);
2640 }
2641 
2642 static CPAccessResult gt_vct_access(CPUARMState *env,
2643                                     const ARMCPRegInfo *ri,
2644                                     bool isread)
2645 {
2646     return gt_counter_access(env, GTIMER_VIRT, isread);
2647 }
2648 
2649 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2650                                        bool isread)
2651 {
2652     return gt_timer_access(env, GTIMER_PHYS, isread);
2653 }
2654 
2655 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2656                                        bool isread)
2657 {
2658     return gt_timer_access(env, GTIMER_VIRT, isread);
2659 }
2660 
2661 static CPAccessResult gt_stimer_access(CPUARMState *env,
2662                                        const ARMCPRegInfo *ri,
2663                                        bool isread)
2664 {
2665     /* The AArch64 register view of the secure physical timer is
2666      * always accessible from EL3, and configurably accessible from
2667      * Secure EL1.
2668      */
2669     switch (arm_current_el(env)) {
2670     case 1:
2671         if (!arm_is_secure(env)) {
2672             return CP_ACCESS_TRAP;
2673         }
2674         if (!(env->cp15.scr_el3 & SCR_ST)) {
2675             return CP_ACCESS_TRAP_EL3;
2676         }
2677         return CP_ACCESS_OK;
2678     case 0:
2679     case 2:
2680         return CP_ACCESS_TRAP;
2681     case 3:
2682         return CP_ACCESS_OK;
2683     default:
2684         g_assert_not_reached();
2685     }
2686 }
2687 
2688 static uint64_t gt_get_countervalue(CPUARMState *env)
2689 {
2690     ARMCPU *cpu = env_archcpu(env);
2691 
2692     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2693 }
2694 
2695 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2696 {
2697     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2698 
2699     if (gt->ctl & 1) {
2700         /* Timer enabled: calculate and set current ISTATUS, irq, and
2701          * reset timer to when ISTATUS next has to change
2702          */
2703         uint64_t offset = timeridx == GTIMER_VIRT ?
2704                                       cpu->env.cp15.cntvoff_el2 : 0;
2705         uint64_t count = gt_get_countervalue(&cpu->env);
2706         /* Note that this must be unsigned 64 bit arithmetic: */
2707         int istatus = count - offset >= gt->cval;
2708         uint64_t nexttick;
2709         int irqstate;
2710 
2711         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2712 
2713         irqstate = (istatus && !(gt->ctl & 2));
2714         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2715 
2716         if (istatus) {
2717             /* Next transition is when count rolls back over to zero */
2718             nexttick = UINT64_MAX;
2719         } else {
2720             /* Next transition is when we hit cval */
2721             nexttick = gt->cval + offset;
2722         }
2723         /* Note that the desired next expiry time might be beyond the
2724          * signed-64-bit range of a QEMUTimer -- in this case we just
2725          * set the timer for as far in the future as possible. When the
2726          * timer expires we will reset the timer for any remaining period.
2727          */
2728         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2729             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2730         } else {
2731             timer_mod(cpu->gt_timer[timeridx], nexttick);
2732         }
2733         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2734     } else {
2735         /* Timer disabled: ISTATUS and timer output always clear */
2736         gt->ctl &= ~4;
2737         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2738         timer_del(cpu->gt_timer[timeridx]);
2739         trace_arm_gt_recalc_disabled(timeridx);
2740     }
2741 }
2742 
2743 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2744                            int timeridx)
2745 {
2746     ARMCPU *cpu = env_archcpu(env);
2747 
2748     timer_del(cpu->gt_timer[timeridx]);
2749 }
2750 
2751 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2752 {
2753     return gt_get_countervalue(env);
2754 }
2755 
2756 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2757 {
2758     uint64_t hcr;
2759 
2760     switch (arm_current_el(env)) {
2761     case 2:
2762         hcr = arm_hcr_el2_eff(env);
2763         if (hcr & HCR_E2H) {
2764             return 0;
2765         }
2766         break;
2767     case 0:
2768         hcr = arm_hcr_el2_eff(env);
2769         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2770             return 0;
2771         }
2772         break;
2773     }
2774 
2775     return env->cp15.cntvoff_el2;
2776 }
2777 
2778 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2779 {
2780     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2781 }
2782 
2783 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2784                           int timeridx,
2785                           uint64_t value)
2786 {
2787     trace_arm_gt_cval_write(timeridx, value);
2788     env->cp15.c14_timer[timeridx].cval = value;
2789     gt_recalc_timer(env_archcpu(env), timeridx);
2790 }
2791 
2792 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2793                              int timeridx)
2794 {
2795     uint64_t offset = 0;
2796 
2797     switch (timeridx) {
2798     case GTIMER_VIRT:
2799     case GTIMER_HYPVIRT:
2800         offset = gt_virt_cnt_offset(env);
2801         break;
2802     }
2803 
2804     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2805                       (gt_get_countervalue(env) - offset));
2806 }
2807 
2808 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2809                           int timeridx,
2810                           uint64_t value)
2811 {
2812     uint64_t offset = 0;
2813 
2814     switch (timeridx) {
2815     case GTIMER_VIRT:
2816     case GTIMER_HYPVIRT:
2817         offset = gt_virt_cnt_offset(env);
2818         break;
2819     }
2820 
2821     trace_arm_gt_tval_write(timeridx, value);
2822     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2823                                          sextract64(value, 0, 32);
2824     gt_recalc_timer(env_archcpu(env), timeridx);
2825 }
2826 
2827 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2828                          int timeridx,
2829                          uint64_t value)
2830 {
2831     ARMCPU *cpu = env_archcpu(env);
2832     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2833 
2834     trace_arm_gt_ctl_write(timeridx, value);
2835     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2836     if ((oldval ^ value) & 1) {
2837         /* Enable toggled */
2838         gt_recalc_timer(cpu, timeridx);
2839     } else if ((oldval ^ value) & 2) {
2840         /* IMASK toggled: don't need to recalculate,
2841          * just set the interrupt line based on ISTATUS
2842          */
2843         int irqstate = (oldval & 4) && !(value & 2);
2844 
2845         trace_arm_gt_imask_toggle(timeridx, irqstate);
2846         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2847     }
2848 }
2849 
2850 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2851 {
2852     gt_timer_reset(env, ri, GTIMER_PHYS);
2853 }
2854 
2855 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2856                                uint64_t value)
2857 {
2858     gt_cval_write(env, ri, GTIMER_PHYS, value);
2859 }
2860 
2861 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2862 {
2863     return gt_tval_read(env, ri, GTIMER_PHYS);
2864 }
2865 
2866 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2867                                uint64_t value)
2868 {
2869     gt_tval_write(env, ri, GTIMER_PHYS, value);
2870 }
2871 
2872 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2873                               uint64_t value)
2874 {
2875     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2876 }
2877 
2878 static int gt_phys_redir_timeridx(CPUARMState *env)
2879 {
2880     switch (arm_mmu_idx(env)) {
2881     case ARMMMUIdx_E20_0:
2882     case ARMMMUIdx_E20_2:
2883     case ARMMMUIdx_E20_2_PAN:
2884     case ARMMMUIdx_SE20_0:
2885     case ARMMMUIdx_SE20_2:
2886     case ARMMMUIdx_SE20_2_PAN:
2887         return GTIMER_HYP;
2888     default:
2889         return GTIMER_PHYS;
2890     }
2891 }
2892 
2893 static int gt_virt_redir_timeridx(CPUARMState *env)
2894 {
2895     switch (arm_mmu_idx(env)) {
2896     case ARMMMUIdx_E20_0:
2897     case ARMMMUIdx_E20_2:
2898     case ARMMMUIdx_E20_2_PAN:
2899     case ARMMMUIdx_SE20_0:
2900     case ARMMMUIdx_SE20_2:
2901     case ARMMMUIdx_SE20_2_PAN:
2902         return GTIMER_HYPVIRT;
2903     default:
2904         return GTIMER_VIRT;
2905     }
2906 }
2907 
2908 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2909                                         const ARMCPRegInfo *ri)
2910 {
2911     int timeridx = gt_phys_redir_timeridx(env);
2912     return env->cp15.c14_timer[timeridx].cval;
2913 }
2914 
2915 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2916                                      uint64_t value)
2917 {
2918     int timeridx = gt_phys_redir_timeridx(env);
2919     gt_cval_write(env, ri, timeridx, value);
2920 }
2921 
2922 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2923                                         const ARMCPRegInfo *ri)
2924 {
2925     int timeridx = gt_phys_redir_timeridx(env);
2926     return gt_tval_read(env, ri, timeridx);
2927 }
2928 
2929 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2930                                      uint64_t value)
2931 {
2932     int timeridx = gt_phys_redir_timeridx(env);
2933     gt_tval_write(env, ri, timeridx, value);
2934 }
2935 
2936 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2937                                        const ARMCPRegInfo *ri)
2938 {
2939     int timeridx = gt_phys_redir_timeridx(env);
2940     return env->cp15.c14_timer[timeridx].ctl;
2941 }
2942 
2943 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2944                                     uint64_t value)
2945 {
2946     int timeridx = gt_phys_redir_timeridx(env);
2947     gt_ctl_write(env, ri, timeridx, value);
2948 }
2949 
2950 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2951 {
2952     gt_timer_reset(env, ri, GTIMER_VIRT);
2953 }
2954 
2955 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2956                                uint64_t value)
2957 {
2958     gt_cval_write(env, ri, GTIMER_VIRT, value);
2959 }
2960 
2961 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2962 {
2963     return gt_tval_read(env, ri, GTIMER_VIRT);
2964 }
2965 
2966 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2967                                uint64_t value)
2968 {
2969     gt_tval_write(env, ri, GTIMER_VIRT, value);
2970 }
2971 
2972 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2973                               uint64_t value)
2974 {
2975     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2976 }
2977 
2978 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2979                               uint64_t value)
2980 {
2981     ARMCPU *cpu = env_archcpu(env);
2982 
2983     trace_arm_gt_cntvoff_write(value);
2984     raw_write(env, ri, value);
2985     gt_recalc_timer(cpu, GTIMER_VIRT);
2986 }
2987 
2988 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
2989                                         const ARMCPRegInfo *ri)
2990 {
2991     int timeridx = gt_virt_redir_timeridx(env);
2992     return env->cp15.c14_timer[timeridx].cval;
2993 }
2994 
2995 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2996                                      uint64_t value)
2997 {
2998     int timeridx = gt_virt_redir_timeridx(env);
2999     gt_cval_write(env, ri, timeridx, value);
3000 }
3001 
3002 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
3003                                         const ARMCPRegInfo *ri)
3004 {
3005     int timeridx = gt_virt_redir_timeridx(env);
3006     return gt_tval_read(env, ri, timeridx);
3007 }
3008 
3009 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3010                                      uint64_t value)
3011 {
3012     int timeridx = gt_virt_redir_timeridx(env);
3013     gt_tval_write(env, ri, timeridx, value);
3014 }
3015 
3016 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
3017                                        const ARMCPRegInfo *ri)
3018 {
3019     int timeridx = gt_virt_redir_timeridx(env);
3020     return env->cp15.c14_timer[timeridx].ctl;
3021 }
3022 
3023 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3024                                     uint64_t value)
3025 {
3026     int timeridx = gt_virt_redir_timeridx(env);
3027     gt_ctl_write(env, ri, timeridx, value);
3028 }
3029 
3030 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3031 {
3032     gt_timer_reset(env, ri, GTIMER_HYP);
3033 }
3034 
3035 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3036                               uint64_t value)
3037 {
3038     gt_cval_write(env, ri, GTIMER_HYP, value);
3039 }
3040 
3041 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3042 {
3043     return gt_tval_read(env, ri, GTIMER_HYP);
3044 }
3045 
3046 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3047                               uint64_t value)
3048 {
3049     gt_tval_write(env, ri, GTIMER_HYP, value);
3050 }
3051 
3052 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3053                               uint64_t value)
3054 {
3055     gt_ctl_write(env, ri, GTIMER_HYP, value);
3056 }
3057 
3058 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3059 {
3060     gt_timer_reset(env, ri, GTIMER_SEC);
3061 }
3062 
3063 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3064                               uint64_t value)
3065 {
3066     gt_cval_write(env, ri, GTIMER_SEC, value);
3067 }
3068 
3069 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3070 {
3071     return gt_tval_read(env, ri, GTIMER_SEC);
3072 }
3073 
3074 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3075                               uint64_t value)
3076 {
3077     gt_tval_write(env, ri, GTIMER_SEC, value);
3078 }
3079 
3080 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3081                               uint64_t value)
3082 {
3083     gt_ctl_write(env, ri, GTIMER_SEC, value);
3084 }
3085 
3086 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3087 {
3088     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
3089 }
3090 
3091 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3092                              uint64_t value)
3093 {
3094     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
3095 }
3096 
3097 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3098 {
3099     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
3100 }
3101 
3102 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3103                              uint64_t value)
3104 {
3105     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
3106 }
3107 
3108 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3109                             uint64_t value)
3110 {
3111     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
3112 }
3113 
3114 void arm_gt_ptimer_cb(void *opaque)
3115 {
3116     ARMCPU *cpu = opaque;
3117 
3118     gt_recalc_timer(cpu, GTIMER_PHYS);
3119 }
3120 
3121 void arm_gt_vtimer_cb(void *opaque)
3122 {
3123     ARMCPU *cpu = opaque;
3124 
3125     gt_recalc_timer(cpu, GTIMER_VIRT);
3126 }
3127 
3128 void arm_gt_htimer_cb(void *opaque)
3129 {
3130     ARMCPU *cpu = opaque;
3131 
3132     gt_recalc_timer(cpu, GTIMER_HYP);
3133 }
3134 
3135 void arm_gt_stimer_cb(void *opaque)
3136 {
3137     ARMCPU *cpu = opaque;
3138 
3139     gt_recalc_timer(cpu, GTIMER_SEC);
3140 }
3141 
3142 void arm_gt_hvtimer_cb(void *opaque)
3143 {
3144     ARMCPU *cpu = opaque;
3145 
3146     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
3147 }
3148 
3149 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
3150 {
3151     ARMCPU *cpu = env_archcpu(env);
3152 
3153     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
3154 }
3155 
3156 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3157     /* Note that CNTFRQ is purely reads-as-written for the benefit
3158      * of software; writing it doesn't actually change the timer frequency.
3159      * Our reset value matches the fixed frequency we implement the timer at.
3160      */
3161     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
3162       .type = ARM_CP_ALIAS,
3163       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3164       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
3165     },
3166     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3167       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3168       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3169       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3170       .resetfn = arm_gt_cntfrq_reset,
3171     },
3172     /* overall control: mostly access permissions */
3173     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
3174       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
3175       .access = PL1_RW,
3176       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
3177       .resetvalue = 0,
3178     },
3179     /* per-timer control */
3180     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3181       .secure = ARM_CP_SECSTATE_NS,
3182       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3183       .accessfn = gt_ptimer_access,
3184       .fieldoffset = offsetoflow32(CPUARMState,
3185                                    cp15.c14_timer[GTIMER_PHYS].ctl),
3186       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3187       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3188     },
3189     { .name = "CNTP_CTL_S",
3190       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3191       .secure = ARM_CP_SECSTATE_S,
3192       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3193       .accessfn = gt_ptimer_access,
3194       .fieldoffset = offsetoflow32(CPUARMState,
3195                                    cp15.c14_timer[GTIMER_SEC].ctl),
3196       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3197     },
3198     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
3199       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
3200       .type = ARM_CP_IO, .access = PL0_RW,
3201       .accessfn = gt_ptimer_access,
3202       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
3203       .resetvalue = 0,
3204       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3205       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3206     },
3207     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
3208       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3209       .accessfn = gt_vtimer_access,
3210       .fieldoffset = offsetoflow32(CPUARMState,
3211                                    cp15.c14_timer[GTIMER_VIRT].ctl),
3212       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3213       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3214     },
3215     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
3216       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
3217       .type = ARM_CP_IO, .access = PL0_RW,
3218       .accessfn = gt_vtimer_access,
3219       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
3220       .resetvalue = 0,
3221       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3222       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3223     },
3224     /* TimerValue views: a 32 bit downcounting view of the underlying state */
3225     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3226       .secure = ARM_CP_SECSTATE_NS,
3227       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3228       .accessfn = gt_ptimer_access,
3229       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3230     },
3231     { .name = "CNTP_TVAL_S",
3232       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3233       .secure = ARM_CP_SECSTATE_S,
3234       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3235       .accessfn = gt_ptimer_access,
3236       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
3237     },
3238     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3239       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
3240       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3241       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
3242       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3243     },
3244     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
3245       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3246       .accessfn = gt_vtimer_access,
3247       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3248     },
3249     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3250       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
3251       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3252       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
3253       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3254     },
3255     /* The counter itself */
3256     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
3257       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3258       .accessfn = gt_pct_access,
3259       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
3260     },
3261     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
3262       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
3263       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3264       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
3265     },
3266     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3267       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3268       .accessfn = gt_vct_access,
3269       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3270     },
3271     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3272       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3273       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3274       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3275     },
3276     /* Comparison value, indicating when the timer goes off */
3277     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3278       .secure = ARM_CP_SECSTATE_NS,
3279       .access = PL0_RW,
3280       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3281       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3282       .accessfn = gt_ptimer_access,
3283       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3284       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3285     },
3286     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3287       .secure = ARM_CP_SECSTATE_S,
3288       .access = PL0_RW,
3289       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3290       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3291       .accessfn = gt_ptimer_access,
3292       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3293     },
3294     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3295       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3296       .access = PL0_RW,
3297       .type = ARM_CP_IO,
3298       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3299       .resetvalue = 0, .accessfn = gt_ptimer_access,
3300       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3301       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3302     },
3303     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3304       .access = PL0_RW,
3305       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3306       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3307       .accessfn = gt_vtimer_access,
3308       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3309       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3310     },
3311     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3312       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3313       .access = PL0_RW,
3314       .type = ARM_CP_IO,
3315       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3316       .resetvalue = 0, .accessfn = gt_vtimer_access,
3317       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3318       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3319     },
3320     /* Secure timer -- this is actually restricted to only EL3
3321      * and configurably Secure-EL1 via the accessfn.
3322      */
3323     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3324       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3325       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3326       .accessfn = gt_stimer_access,
3327       .readfn = gt_sec_tval_read,
3328       .writefn = gt_sec_tval_write,
3329       .resetfn = gt_sec_timer_reset,
3330     },
3331     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3332       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3333       .type = ARM_CP_IO, .access = PL1_RW,
3334       .accessfn = gt_stimer_access,
3335       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3336       .resetvalue = 0,
3337       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3338     },
3339     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3340       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3341       .type = ARM_CP_IO, .access = PL1_RW,
3342       .accessfn = gt_stimer_access,
3343       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3344       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3345     },
3346     REGINFO_SENTINEL
3347 };
3348 
3349 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3350                                  bool isread)
3351 {
3352     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3353         return CP_ACCESS_TRAP;
3354     }
3355     return CP_ACCESS_OK;
3356 }
3357 
3358 #else
3359 
3360 /* In user-mode most of the generic timer registers are inaccessible
3361  * however modern kernels (4.12+) allow access to cntvct_el0
3362  */
3363 
3364 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3365 {
3366     ARMCPU *cpu = env_archcpu(env);
3367 
3368     /* Currently we have no support for QEMUTimer in linux-user so we
3369      * can't call gt_get_countervalue(env), instead we directly
3370      * call the lower level functions.
3371      */
3372     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3373 }
3374 
3375 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3376     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3377       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3378       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3379       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3380       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3381     },
3382     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3383       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3384       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3385       .readfn = gt_virt_cnt_read,
3386     },
3387     REGINFO_SENTINEL
3388 };
3389 
3390 #endif
3391 
3392 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3393 {
3394     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3395         raw_write(env, ri, value);
3396     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3397         raw_write(env, ri, value & 0xfffff6ff);
3398     } else {
3399         raw_write(env, ri, value & 0xfffff1ff);
3400     }
3401 }
3402 
3403 #ifndef CONFIG_USER_ONLY
3404 /* get_phys_addr() isn't present for user-mode-only targets */
3405 
3406 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3407                                  bool isread)
3408 {
3409     if (ri->opc2 & 4) {
3410         /* The ATS12NSO* operations must trap to EL3 or EL2 if executed in
3411          * Secure EL1 (which can only happen if EL3 is AArch64).
3412          * They are simply UNDEF if executed from NS EL1.
3413          * They function normally from EL2 or EL3.
3414          */
3415         if (arm_current_el(env) == 1) {
3416             if (arm_is_secure_below_el3(env)) {
3417                 if (env->cp15.scr_el3 & SCR_EEL2) {
3418                     return CP_ACCESS_TRAP_UNCATEGORIZED_EL2;
3419                 }
3420                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3421             }
3422             return CP_ACCESS_TRAP_UNCATEGORIZED;
3423         }
3424     }
3425     return CP_ACCESS_OK;
3426 }
3427 
3428 #ifdef CONFIG_TCG
3429 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3430                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3431 {
3432     hwaddr phys_addr;
3433     target_ulong page_size;
3434     int prot;
3435     bool ret;
3436     uint64_t par64;
3437     bool format64 = false;
3438     MemTxAttrs attrs = {};
3439     ARMMMUFaultInfo fi = {};
3440     ARMCacheAttrs cacheattrs = {};
3441 
3442     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3443                         &prot, &page_size, &fi, &cacheattrs);
3444 
3445     if (ret) {
3446         /*
3447          * Some kinds of translation fault must cause exceptions rather
3448          * than being reported in the PAR.
3449          */
3450         int current_el = arm_current_el(env);
3451         int target_el;
3452         uint32_t syn, fsr, fsc;
3453         bool take_exc = false;
3454 
3455         if (fi.s1ptw && current_el == 1
3456             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3457             /*
3458              * Synchronous stage 2 fault on an access made as part of the
3459              * translation table walk for AT S1E0* or AT S1E1* insn
3460              * executed from NS EL1. If this is a synchronous external abort
3461              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3462              * to EL3. Otherwise the fault is taken as an exception to EL2,
3463              * and HPFAR_EL2 holds the faulting IPA.
3464              */
3465             if (fi.type == ARMFault_SyncExternalOnWalk &&
3466                 (env->cp15.scr_el3 & SCR_EA)) {
3467                 target_el = 3;
3468             } else {
3469                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3470                 if (arm_is_secure_below_el3(env) && fi.s1ns) {
3471                     env->cp15.hpfar_el2 |= HPFAR_NS;
3472                 }
3473                 target_el = 2;
3474             }
3475             take_exc = true;
3476         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3477             /*
3478              * Synchronous external aborts during a translation table walk
3479              * are taken as Data Abort exceptions.
3480              */
3481             if (fi.stage2) {
3482                 if (current_el == 3) {
3483                     target_el = 3;
3484                 } else {
3485                     target_el = 2;
3486                 }
3487             } else {
3488                 target_el = exception_target_el(env);
3489             }
3490             take_exc = true;
3491         }
3492 
3493         if (take_exc) {
3494             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3495             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3496                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3497                 fsr = arm_fi_to_lfsc(&fi);
3498                 fsc = extract32(fsr, 0, 6);
3499             } else {
3500                 fsr = arm_fi_to_sfsc(&fi);
3501                 fsc = 0x3f;
3502             }
3503             /*
3504              * Report exception with ESR indicating a fault due to a
3505              * translation table walk for a cache maintenance instruction.
3506              */
3507             syn = syn_data_abort_no_iss(current_el == target_el, 0,
3508                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3509             env->exception.vaddress = value;
3510             env->exception.fsr = fsr;
3511             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3512         }
3513     }
3514 
3515     if (is_a64(env)) {
3516         format64 = true;
3517     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3518         /*
3519          * ATS1Cxx:
3520          * * TTBCR.EAE determines whether the result is returned using the
3521          *   32-bit or the 64-bit PAR format
3522          * * Instructions executed in Hyp mode always use the 64bit format
3523          *
3524          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3525          * * The Non-secure TTBCR.EAE bit is set to 1
3526          * * The implementation includes EL2, and the value of HCR.VM is 1
3527          *
3528          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3529          *
3530          * ATS1Hx always uses the 64bit format.
3531          */
3532         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3533 
3534         if (arm_feature(env, ARM_FEATURE_EL2)) {
3535             if (mmu_idx == ARMMMUIdx_E10_0 ||
3536                 mmu_idx == ARMMMUIdx_E10_1 ||
3537                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3538                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3539             } else {
3540                 format64 |= arm_current_el(env) == 2;
3541             }
3542         }
3543     }
3544 
3545     if (format64) {
3546         /* Create a 64-bit PAR */
3547         par64 = (1 << 11); /* LPAE bit always set */
3548         if (!ret) {
3549             par64 |= phys_addr & ~0xfffULL;
3550             if (!attrs.secure) {
3551                 par64 |= (1 << 9); /* NS */
3552             }
3553             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3554             par64 |= cacheattrs.shareability << 7; /* SH */
3555         } else {
3556             uint32_t fsr = arm_fi_to_lfsc(&fi);
3557 
3558             par64 |= 1; /* F */
3559             par64 |= (fsr & 0x3f) << 1; /* FS */
3560             if (fi.stage2) {
3561                 par64 |= (1 << 9); /* S */
3562             }
3563             if (fi.s1ptw) {
3564                 par64 |= (1 << 8); /* PTW */
3565             }
3566         }
3567     } else {
3568         /* fsr is a DFSR/IFSR value for the short descriptor
3569          * translation table format (with WnR always clear).
3570          * Convert it to a 32-bit PAR.
3571          */
3572         if (!ret) {
3573             /* We do not set any attribute bits in the PAR */
3574             if (page_size == (1 << 24)
3575                 && arm_feature(env, ARM_FEATURE_V7)) {
3576                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3577             } else {
3578                 par64 = phys_addr & 0xfffff000;
3579             }
3580             if (!attrs.secure) {
3581                 par64 |= (1 << 9); /* NS */
3582             }
3583         } else {
3584             uint32_t fsr = arm_fi_to_sfsc(&fi);
3585 
3586             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3587                     ((fsr & 0xf) << 1) | 1;
3588         }
3589     }
3590     return par64;
3591 }
3592 #endif /* CONFIG_TCG */
3593 
3594 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3595 {
3596 #ifdef CONFIG_TCG
3597     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3598     uint64_t par64;
3599     ARMMMUIdx mmu_idx;
3600     int el = arm_current_el(env);
3601     bool secure = arm_is_secure_below_el3(env);
3602 
3603     switch (ri->opc2 & 6) {
3604     case 0:
3605         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3606         switch (el) {
3607         case 3:
3608             mmu_idx = ARMMMUIdx_SE3;
3609             break;
3610         case 2:
3611             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3612             /* fall through */
3613         case 1:
3614             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3615                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3616                            : ARMMMUIdx_Stage1_E1_PAN);
3617             } else {
3618                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3619             }
3620             break;
3621         default:
3622             g_assert_not_reached();
3623         }
3624         break;
3625     case 2:
3626         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3627         switch (el) {
3628         case 3:
3629             mmu_idx = ARMMMUIdx_SE10_0;
3630             break;
3631         case 2:
3632             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3633             mmu_idx = ARMMMUIdx_Stage1_E0;
3634             break;
3635         case 1:
3636             mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3637             break;
3638         default:
3639             g_assert_not_reached();
3640         }
3641         break;
3642     case 4:
3643         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3644         mmu_idx = ARMMMUIdx_E10_1;
3645         break;
3646     case 6:
3647         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3648         mmu_idx = ARMMMUIdx_E10_0;
3649         break;
3650     default:
3651         g_assert_not_reached();
3652     }
3653 
3654     par64 = do_ats_write(env, value, access_type, mmu_idx);
3655 
3656     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3657 #else
3658     /* Handled by hardware accelerator. */
3659     g_assert_not_reached();
3660 #endif /* CONFIG_TCG */
3661 }
3662 
3663 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3664                         uint64_t value)
3665 {
3666 #ifdef CONFIG_TCG
3667     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3668     uint64_t par64;
3669 
3670     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3671 
3672     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3673 #else
3674     /* Handled by hardware accelerator. */
3675     g_assert_not_reached();
3676 #endif /* CONFIG_TCG */
3677 }
3678 
3679 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3680                                      bool isread)
3681 {
3682     if (arm_current_el(env) == 3 &&
3683         !(env->cp15.scr_el3 & (SCR_NS | SCR_EEL2))) {
3684         return CP_ACCESS_TRAP;
3685     }
3686     return CP_ACCESS_OK;
3687 }
3688 
3689 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3690                         uint64_t value)
3691 {
3692 #ifdef CONFIG_TCG
3693     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3694     ARMMMUIdx mmu_idx;
3695     int secure = arm_is_secure_below_el3(env);
3696 
3697     switch (ri->opc2 & 6) {
3698     case 0:
3699         switch (ri->opc1) {
3700         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3701             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3702                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3703                            : ARMMMUIdx_Stage1_E1_PAN);
3704             } else {
3705                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3706             }
3707             break;
3708         case 4: /* AT S1E2R, AT S1E2W */
3709             mmu_idx = secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2;
3710             break;
3711         case 6: /* AT S1E3R, AT S1E3W */
3712             mmu_idx = ARMMMUIdx_SE3;
3713             break;
3714         default:
3715             g_assert_not_reached();
3716         }
3717         break;
3718     case 2: /* AT S1E0R, AT S1E0W */
3719         mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3720         break;
3721     case 4: /* AT S12E1R, AT S12E1W */
3722         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3723         break;
3724     case 6: /* AT S12E0R, AT S12E0W */
3725         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3726         break;
3727     default:
3728         g_assert_not_reached();
3729     }
3730 
3731     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3732 #else
3733     /* Handled by hardware accelerator. */
3734     g_assert_not_reached();
3735 #endif /* CONFIG_TCG */
3736 }
3737 #endif
3738 
3739 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3740     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3741       .access = PL1_RW, .resetvalue = 0,
3742       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3743                              offsetoflow32(CPUARMState, cp15.par_ns) },
3744       .writefn = par_write },
3745 #ifndef CONFIG_USER_ONLY
3746     /* This underdecoding is safe because the reginfo is NO_RAW. */
3747     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3748       .access = PL1_W, .accessfn = ats_access,
3749       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3750 #endif
3751     REGINFO_SENTINEL
3752 };
3753 
3754 /* Return basic MPU access permission bits.  */
3755 static uint32_t simple_mpu_ap_bits(uint32_t val)
3756 {
3757     uint32_t ret;
3758     uint32_t mask;
3759     int i;
3760     ret = 0;
3761     mask = 3;
3762     for (i = 0; i < 16; i += 2) {
3763         ret |= (val >> i) & mask;
3764         mask <<= 2;
3765     }
3766     return ret;
3767 }
3768 
3769 /* Pad basic MPU access permission bits to extended format.  */
3770 static uint32_t extended_mpu_ap_bits(uint32_t val)
3771 {
3772     uint32_t ret;
3773     uint32_t mask;
3774     int i;
3775     ret = 0;
3776     mask = 3;
3777     for (i = 0; i < 16; i += 2) {
3778         ret |= (val & mask) << i;
3779         mask <<= 2;
3780     }
3781     return ret;
3782 }
3783 
3784 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3785                                  uint64_t value)
3786 {
3787     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3788 }
3789 
3790 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3791 {
3792     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3793 }
3794 
3795 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3796                                  uint64_t value)
3797 {
3798     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3799 }
3800 
3801 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3802 {
3803     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3804 }
3805 
3806 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3807 {
3808     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3809 
3810     if (!u32p) {
3811         return 0;
3812     }
3813 
3814     u32p += env->pmsav7.rnr[M_REG_NS];
3815     return *u32p;
3816 }
3817 
3818 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3819                          uint64_t value)
3820 {
3821     ARMCPU *cpu = env_archcpu(env);
3822     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3823 
3824     if (!u32p) {
3825         return;
3826     }
3827 
3828     u32p += env->pmsav7.rnr[M_REG_NS];
3829     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3830     *u32p = value;
3831 }
3832 
3833 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3834                               uint64_t value)
3835 {
3836     ARMCPU *cpu = env_archcpu(env);
3837     uint32_t nrgs = cpu->pmsav7_dregion;
3838 
3839     if (value >= nrgs) {
3840         qemu_log_mask(LOG_GUEST_ERROR,
3841                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3842                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3843         return;
3844     }
3845 
3846     raw_write(env, ri, value);
3847 }
3848 
3849 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3850     /* Reset for all these registers is handled in arm_cpu_reset(),
3851      * because the PMSAv7 is also used by M-profile CPUs, which do
3852      * not register cpregs but still need the state to be reset.
3853      */
3854     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3855       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3856       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3857       .readfn = pmsav7_read, .writefn = pmsav7_write,
3858       .resetfn = arm_cp_reset_ignore },
3859     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3860       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3861       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3862       .readfn = pmsav7_read, .writefn = pmsav7_write,
3863       .resetfn = arm_cp_reset_ignore },
3864     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3865       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3866       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3867       .readfn = pmsav7_read, .writefn = pmsav7_write,
3868       .resetfn = arm_cp_reset_ignore },
3869     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3870       .access = PL1_RW,
3871       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3872       .writefn = pmsav7_rgnr_write,
3873       .resetfn = arm_cp_reset_ignore },
3874     REGINFO_SENTINEL
3875 };
3876 
3877 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3878     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3879       .access = PL1_RW, .type = ARM_CP_ALIAS,
3880       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3881       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3882     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3883       .access = PL1_RW, .type = ARM_CP_ALIAS,
3884       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3885       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3886     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3887       .access = PL1_RW,
3888       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3889       .resetvalue = 0, },
3890     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3891       .access = PL1_RW,
3892       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3893       .resetvalue = 0, },
3894     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3895       .access = PL1_RW,
3896       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3897     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3898       .access = PL1_RW,
3899       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3900     /* Protection region base and size registers */
3901     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3902       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3903       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3904     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3905       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3906       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3907     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3908       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3909       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3910     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3911       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3912       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3913     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3914       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3915       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3916     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3917       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3918       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3919     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3920       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3921       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3922     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3923       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3924       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3925     REGINFO_SENTINEL
3926 };
3927 
3928 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3929                                  uint64_t value)
3930 {
3931     TCR *tcr = raw_ptr(env, ri);
3932     int maskshift = extract32(value, 0, 3);
3933 
3934     if (!arm_feature(env, ARM_FEATURE_V8)) {
3935         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3936             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3937              * using Long-desciptor translation table format */
3938             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3939         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3940             /* In an implementation that includes the Security Extensions
3941              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3942              * Short-descriptor translation table format.
3943              */
3944             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3945         } else {
3946             value &= TTBCR_N;
3947         }
3948     }
3949 
3950     /* Update the masks corresponding to the TCR bank being written
3951      * Note that we always calculate mask and base_mask, but
3952      * they are only used for short-descriptor tables (ie if EAE is 0);
3953      * for long-descriptor tables the TCR fields are used differently
3954      * and the mask and base_mask values are meaningless.
3955      */
3956     tcr->raw_tcr = value;
3957     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3958     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3959 }
3960 
3961 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3962                              uint64_t value)
3963 {
3964     ARMCPU *cpu = env_archcpu(env);
3965     TCR *tcr = raw_ptr(env, ri);
3966 
3967     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3968         /* With LPAE the TTBCR could result in a change of ASID
3969          * via the TTBCR.A1 bit, so do a TLB flush.
3970          */
3971         tlb_flush(CPU(cpu));
3972     }
3973     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3974     value = deposit64(tcr->raw_tcr, 0, 32, value);
3975     vmsa_ttbcr_raw_write(env, ri, value);
3976 }
3977 
3978 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3979 {
3980     TCR *tcr = raw_ptr(env, ri);
3981 
3982     /* Reset both the TCR as well as the masks corresponding to the bank of
3983      * the TCR being reset.
3984      */
3985     tcr->raw_tcr = 0;
3986     tcr->mask = 0;
3987     tcr->base_mask = 0xffffc000u;
3988 }
3989 
3990 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3991                                uint64_t value)
3992 {
3993     ARMCPU *cpu = env_archcpu(env);
3994     TCR *tcr = raw_ptr(env, ri);
3995 
3996     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3997     tlb_flush(CPU(cpu));
3998     tcr->raw_tcr = value;
3999 }
4000 
4001 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4002                             uint64_t value)
4003 {
4004     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
4005     if (cpreg_field_is_64bit(ri) &&
4006         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
4007         ARMCPU *cpu = env_archcpu(env);
4008         tlb_flush(CPU(cpu));
4009     }
4010     raw_write(env, ri, value);
4011 }
4012 
4013 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4014                                     uint64_t value)
4015 {
4016     /*
4017      * If we are running with E2&0 regime, then an ASID is active.
4018      * Flush if that might be changing.  Note we're not checking
4019      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
4020      * holds the active ASID, only checking the field that might.
4021      */
4022     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
4023         (arm_hcr_el2_eff(env) & HCR_E2H)) {
4024         uint16_t mask = ARMMMUIdxBit_E20_2 |
4025                         ARMMMUIdxBit_E20_2_PAN |
4026                         ARMMMUIdxBit_E20_0;
4027 
4028         if (arm_is_secure_below_el3(env)) {
4029             mask >>= ARM_MMU_IDX_A_NS;
4030         }
4031 
4032         tlb_flush_by_mmuidx(env_cpu(env), mask);
4033     }
4034     raw_write(env, ri, value);
4035 }
4036 
4037 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4038                         uint64_t value)
4039 {
4040     ARMCPU *cpu = env_archcpu(env);
4041     CPUState *cs = CPU(cpu);
4042 
4043     /*
4044      * A change in VMID to the stage2 page table (Stage2) invalidates
4045      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
4046      */
4047     if (raw_read(env, ri) != value) {
4048         uint16_t mask = ARMMMUIdxBit_E10_1 |
4049                         ARMMMUIdxBit_E10_1_PAN |
4050                         ARMMMUIdxBit_E10_0;
4051 
4052         if (arm_is_secure_below_el3(env)) {
4053             mask >>= ARM_MMU_IDX_A_NS;
4054         }
4055 
4056         tlb_flush_by_mmuidx(cs, mask);
4057         raw_write(env, ri, value);
4058     }
4059 }
4060 
4061 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
4062     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
4063       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
4064       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
4065                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
4066     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
4067       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4068       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
4069                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
4070     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
4071       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4072       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
4073                              offsetof(CPUARMState, cp15.dfar_ns) } },
4074     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
4075       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
4076       .access = PL1_RW, .accessfn = access_tvm_trvm,
4077       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
4078       .resetvalue = 0, },
4079     REGINFO_SENTINEL
4080 };
4081 
4082 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
4083     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
4084       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
4085       .access = PL1_RW, .accessfn = access_tvm_trvm,
4086       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
4087     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
4088       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
4089       .access = PL1_RW, .accessfn = access_tvm_trvm,
4090       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4091       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4092                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
4093     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
4094       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
4095       .access = PL1_RW, .accessfn = access_tvm_trvm,
4096       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4097       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4098                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
4099     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
4100       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4101       .access = PL1_RW, .accessfn = access_tvm_trvm,
4102       .writefn = vmsa_tcr_el12_write,
4103       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
4104       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
4105     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4106       .access = PL1_RW, .accessfn = access_tvm_trvm,
4107       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
4108       .raw_writefn = vmsa_ttbcr_raw_write,
4109       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
4110                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
4111     REGINFO_SENTINEL
4112 };
4113 
4114 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
4115  * qemu tlbs nor adjusting cached masks.
4116  */
4117 static const ARMCPRegInfo ttbcr2_reginfo = {
4118     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
4119     .access = PL1_RW, .accessfn = access_tvm_trvm,
4120     .type = ARM_CP_ALIAS,
4121     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
4122                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
4123 };
4124 
4125 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
4126                                 uint64_t value)
4127 {
4128     env->cp15.c15_ticonfig = value & 0xe7;
4129     /* The OS_TYPE bit in this register changes the reported CPUID! */
4130     env->cp15.c0_cpuid = (value & (1 << 5)) ?
4131         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
4132 }
4133 
4134 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
4135                                 uint64_t value)
4136 {
4137     env->cp15.c15_threadid = value & 0xffff;
4138 }
4139 
4140 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
4141                            uint64_t value)
4142 {
4143     /* Wait-for-interrupt (deprecated) */
4144     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
4145 }
4146 
4147 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
4148                                   uint64_t value)
4149 {
4150     /* On OMAP there are registers indicating the max/min index of dcache lines
4151      * containing a dirty line; cache flush operations have to reset these.
4152      */
4153     env->cp15.c15_i_max = 0x000;
4154     env->cp15.c15_i_min = 0xff0;
4155 }
4156 
4157 static const ARMCPRegInfo omap_cp_reginfo[] = {
4158     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
4159       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
4160       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
4161       .resetvalue = 0, },
4162     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
4163       .access = PL1_RW, .type = ARM_CP_NOP },
4164     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
4165       .access = PL1_RW,
4166       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
4167       .writefn = omap_ticonfig_write },
4168     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
4169       .access = PL1_RW,
4170       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
4171     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
4172       .access = PL1_RW, .resetvalue = 0xff0,
4173       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
4174     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
4175       .access = PL1_RW,
4176       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
4177       .writefn = omap_threadid_write },
4178     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
4179       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4180       .type = ARM_CP_NO_RAW,
4181       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
4182     /* TODO: Peripheral port remap register:
4183      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
4184      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
4185      * when MMU is off.
4186      */
4187     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
4188       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
4189       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
4190       .writefn = omap_cachemaint_write },
4191     { .name = "C9", .cp = 15, .crn = 9,
4192       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
4193       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
4194     REGINFO_SENTINEL
4195 };
4196 
4197 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4198                               uint64_t value)
4199 {
4200     env->cp15.c15_cpar = value & 0x3fff;
4201 }
4202 
4203 static const ARMCPRegInfo xscale_cp_reginfo[] = {
4204     { .name = "XSCALE_CPAR",
4205       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4206       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
4207       .writefn = xscale_cpar_write, },
4208     { .name = "XSCALE_AUXCR",
4209       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
4210       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
4211       .resetvalue = 0, },
4212     /* XScale specific cache-lockdown: since we have no cache we NOP these
4213      * and hope the guest does not really rely on cache behaviour.
4214      */
4215     { .name = "XSCALE_LOCK_ICACHE_LINE",
4216       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
4217       .access = PL1_W, .type = ARM_CP_NOP },
4218     { .name = "XSCALE_UNLOCK_ICACHE",
4219       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
4220       .access = PL1_W, .type = ARM_CP_NOP },
4221     { .name = "XSCALE_DCACHE_LOCK",
4222       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
4223       .access = PL1_RW, .type = ARM_CP_NOP },
4224     { .name = "XSCALE_UNLOCK_DCACHE",
4225       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
4226       .access = PL1_W, .type = ARM_CP_NOP },
4227     REGINFO_SENTINEL
4228 };
4229 
4230 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
4231     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
4232      * implementation of this implementation-defined space.
4233      * Ideally this should eventually disappear in favour of actually
4234      * implementing the correct behaviour for all cores.
4235      */
4236     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
4237       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4238       .access = PL1_RW,
4239       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
4240       .resetvalue = 0 },
4241     REGINFO_SENTINEL
4242 };
4243 
4244 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
4245     /* Cache status: RAZ because we have no cache so it's always clean */
4246     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
4247       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4248       .resetvalue = 0 },
4249     REGINFO_SENTINEL
4250 };
4251 
4252 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
4253     /* We never have a a block transfer operation in progress */
4254     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
4255       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4256       .resetvalue = 0 },
4257     /* The cache ops themselves: these all NOP for QEMU */
4258     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
4259       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4260     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
4261       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4262     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
4263       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4264     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4265       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4266     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4267       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4268     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4269       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4270     REGINFO_SENTINEL
4271 };
4272 
4273 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4274     /* The cache test-and-clean instructions always return (1 << 30)
4275      * to indicate that there are no dirty cache lines.
4276      */
4277     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4278       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4279       .resetvalue = (1 << 30) },
4280     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4281       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4282       .resetvalue = (1 << 30) },
4283     REGINFO_SENTINEL
4284 };
4285 
4286 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4287     /* Ignore ReadBuffer accesses */
4288     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4289       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4290       .access = PL1_RW, .resetvalue = 0,
4291       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4292     REGINFO_SENTINEL
4293 };
4294 
4295 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4296 {
4297     unsigned int cur_el = arm_current_el(env);
4298 
4299     if (arm_is_el2_enabled(env) && cur_el == 1) {
4300         return env->cp15.vpidr_el2;
4301     }
4302     return raw_read(env, ri);
4303 }
4304 
4305 static uint64_t mpidr_read_val(CPUARMState *env)
4306 {
4307     ARMCPU *cpu = env_archcpu(env);
4308     uint64_t mpidr = cpu->mp_affinity;
4309 
4310     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4311         mpidr |= (1U << 31);
4312         /* Cores which are uniprocessor (non-coherent)
4313          * but still implement the MP extensions set
4314          * bit 30. (For instance, Cortex-R5).
4315          */
4316         if (cpu->mp_is_up) {
4317             mpidr |= (1u << 30);
4318         }
4319     }
4320     return mpidr;
4321 }
4322 
4323 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4324 {
4325     unsigned int cur_el = arm_current_el(env);
4326 
4327     if (arm_is_el2_enabled(env) && cur_el == 1) {
4328         return env->cp15.vmpidr_el2;
4329     }
4330     return mpidr_read_val(env);
4331 }
4332 
4333 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4334     /* NOP AMAIR0/1 */
4335     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4336       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4337       .access = PL1_RW, .accessfn = access_tvm_trvm,
4338       .type = ARM_CP_CONST, .resetvalue = 0 },
4339     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4340     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4341       .access = PL1_RW, .accessfn = access_tvm_trvm,
4342       .type = ARM_CP_CONST, .resetvalue = 0 },
4343     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4344       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4345       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4346                              offsetof(CPUARMState, cp15.par_ns)} },
4347     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4348       .access = PL1_RW, .accessfn = access_tvm_trvm,
4349       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4350       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4351                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4352       .writefn = vmsa_ttbr_write, },
4353     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4354       .access = PL1_RW, .accessfn = access_tvm_trvm,
4355       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4356       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4357                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4358       .writefn = vmsa_ttbr_write, },
4359     REGINFO_SENTINEL
4360 };
4361 
4362 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4363 {
4364     return vfp_get_fpcr(env);
4365 }
4366 
4367 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4368                             uint64_t value)
4369 {
4370     vfp_set_fpcr(env, value);
4371 }
4372 
4373 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4374 {
4375     return vfp_get_fpsr(env);
4376 }
4377 
4378 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4379                             uint64_t value)
4380 {
4381     vfp_set_fpsr(env, value);
4382 }
4383 
4384 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4385                                        bool isread)
4386 {
4387     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4388         return CP_ACCESS_TRAP;
4389     }
4390     return CP_ACCESS_OK;
4391 }
4392 
4393 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4394                             uint64_t value)
4395 {
4396     env->daif = value & PSTATE_DAIF;
4397 }
4398 
4399 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4400 {
4401     return env->pstate & PSTATE_PAN;
4402 }
4403 
4404 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4405                            uint64_t value)
4406 {
4407     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4408 }
4409 
4410 static const ARMCPRegInfo pan_reginfo = {
4411     .name = "PAN", .state = ARM_CP_STATE_AA64,
4412     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4413     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4414     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4415 };
4416 
4417 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4418 {
4419     return env->pstate & PSTATE_UAO;
4420 }
4421 
4422 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4423                            uint64_t value)
4424 {
4425     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4426 }
4427 
4428 static const ARMCPRegInfo uao_reginfo = {
4429     .name = "UAO", .state = ARM_CP_STATE_AA64,
4430     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4431     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4432     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4433 };
4434 
4435 static uint64_t aa64_dit_read(CPUARMState *env, const ARMCPRegInfo *ri)
4436 {
4437     return env->pstate & PSTATE_DIT;
4438 }
4439 
4440 static void aa64_dit_write(CPUARMState *env, const ARMCPRegInfo *ri,
4441                            uint64_t value)
4442 {
4443     env->pstate = (env->pstate & ~PSTATE_DIT) | (value & PSTATE_DIT);
4444 }
4445 
4446 static const ARMCPRegInfo dit_reginfo = {
4447     .name = "DIT", .state = ARM_CP_STATE_AA64,
4448     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 5,
4449     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4450     .readfn = aa64_dit_read, .writefn = aa64_dit_write
4451 };
4452 
4453 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4454                                               const ARMCPRegInfo *ri,
4455                                               bool isread)
4456 {
4457     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4458     switch (arm_current_el(env)) {
4459     case 0:
4460         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4461         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4462             return CP_ACCESS_TRAP;
4463         }
4464         /* fall through */
4465     case 1:
4466         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4467         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4468             return CP_ACCESS_TRAP_EL2;
4469         }
4470         break;
4471     }
4472     return CP_ACCESS_OK;
4473 }
4474 
4475 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4476                                               const ARMCPRegInfo *ri,
4477                                               bool isread)
4478 {
4479     /* Cache invalidate/clean to Point of Unification... */
4480     switch (arm_current_el(env)) {
4481     case 0:
4482         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4483         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4484             return CP_ACCESS_TRAP;
4485         }
4486         /* fall through */
4487     case 1:
4488         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4489         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4490             return CP_ACCESS_TRAP_EL2;
4491         }
4492         break;
4493     }
4494     return CP_ACCESS_OK;
4495 }
4496 
4497 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4498  * Page D4-1736 (DDI0487A.b)
4499  */
4500 
4501 static int vae1_tlbmask(CPUARMState *env)
4502 {
4503     uint64_t hcr = arm_hcr_el2_eff(env);
4504     uint16_t mask;
4505 
4506     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4507         mask = ARMMMUIdxBit_E20_2 |
4508                ARMMMUIdxBit_E20_2_PAN |
4509                ARMMMUIdxBit_E20_0;
4510     } else {
4511         mask = ARMMMUIdxBit_E10_1 |
4512                ARMMMUIdxBit_E10_1_PAN |
4513                ARMMMUIdxBit_E10_0;
4514     }
4515 
4516     if (arm_is_secure_below_el3(env)) {
4517         mask >>= ARM_MMU_IDX_A_NS;
4518     }
4519 
4520     return mask;
4521 }
4522 
4523 /* Return 56 if TBI is enabled, 64 otherwise. */
4524 static int tlbbits_for_regime(CPUARMState *env, ARMMMUIdx mmu_idx,
4525                               uint64_t addr)
4526 {
4527     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
4528     int tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
4529     int select = extract64(addr, 55, 1);
4530 
4531     return (tbi >> select) & 1 ? 56 : 64;
4532 }
4533 
4534 static int vae1_tlbbits(CPUARMState *env, uint64_t addr)
4535 {
4536     uint64_t hcr = arm_hcr_el2_eff(env);
4537     ARMMMUIdx mmu_idx;
4538 
4539     /* Only the regime of the mmu_idx below is significant. */
4540     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4541         mmu_idx = ARMMMUIdx_E20_0;
4542     } else {
4543         mmu_idx = ARMMMUIdx_E10_0;
4544     }
4545 
4546     if (arm_is_secure_below_el3(env)) {
4547         mmu_idx &= ~ARM_MMU_IDX_A_NS;
4548     }
4549 
4550     return tlbbits_for_regime(env, mmu_idx, addr);
4551 }
4552 
4553 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4554                                       uint64_t value)
4555 {
4556     CPUState *cs = env_cpu(env);
4557     int mask = vae1_tlbmask(env);
4558 
4559     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4560 }
4561 
4562 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4563                                     uint64_t value)
4564 {
4565     CPUState *cs = env_cpu(env);
4566     int mask = vae1_tlbmask(env);
4567 
4568     if (tlb_force_broadcast(env)) {
4569         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4570     } else {
4571         tlb_flush_by_mmuidx(cs, mask);
4572     }
4573 }
4574 
4575 static int alle1_tlbmask(CPUARMState *env)
4576 {
4577     /*
4578      * Note that the 'ALL' scope must invalidate both stage 1 and
4579      * stage 2 translations, whereas most other scopes only invalidate
4580      * stage 1 translations.
4581      */
4582     if (arm_is_secure_below_el3(env)) {
4583         return ARMMMUIdxBit_SE10_1 |
4584                ARMMMUIdxBit_SE10_1_PAN |
4585                ARMMMUIdxBit_SE10_0;
4586     } else {
4587         return ARMMMUIdxBit_E10_1 |
4588                ARMMMUIdxBit_E10_1_PAN |
4589                ARMMMUIdxBit_E10_0;
4590     }
4591 }
4592 
4593 static int e2_tlbmask(CPUARMState *env)
4594 {
4595     if (arm_is_secure_below_el3(env)) {
4596         return ARMMMUIdxBit_SE20_0 |
4597                ARMMMUIdxBit_SE20_2 |
4598                ARMMMUIdxBit_SE20_2_PAN |
4599                ARMMMUIdxBit_SE2;
4600     } else {
4601         return ARMMMUIdxBit_E20_0 |
4602                ARMMMUIdxBit_E20_2 |
4603                ARMMMUIdxBit_E20_2_PAN |
4604                ARMMMUIdxBit_E2;
4605     }
4606 }
4607 
4608 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4609                                   uint64_t value)
4610 {
4611     CPUState *cs = env_cpu(env);
4612     int mask = alle1_tlbmask(env);
4613 
4614     tlb_flush_by_mmuidx(cs, mask);
4615 }
4616 
4617 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4618                                   uint64_t value)
4619 {
4620     CPUState *cs = env_cpu(env);
4621     int mask = e2_tlbmask(env);
4622 
4623     tlb_flush_by_mmuidx(cs, mask);
4624 }
4625 
4626 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4627                                   uint64_t value)
4628 {
4629     ARMCPU *cpu = env_archcpu(env);
4630     CPUState *cs = CPU(cpu);
4631 
4632     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4633 }
4634 
4635 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4636                                     uint64_t value)
4637 {
4638     CPUState *cs = env_cpu(env);
4639     int mask = alle1_tlbmask(env);
4640 
4641     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4642 }
4643 
4644 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4645                                     uint64_t value)
4646 {
4647     CPUState *cs = env_cpu(env);
4648     int mask = e2_tlbmask(env);
4649 
4650     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4651 }
4652 
4653 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4654                                     uint64_t value)
4655 {
4656     CPUState *cs = env_cpu(env);
4657 
4658     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4659 }
4660 
4661 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4662                                  uint64_t value)
4663 {
4664     /* Invalidate by VA, EL2
4665      * Currently handles both VAE2 and VALE2, since we don't support
4666      * flush-last-level-only.
4667      */
4668     CPUState *cs = env_cpu(env);
4669     int mask = e2_tlbmask(env);
4670     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4671 
4672     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4673 }
4674 
4675 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4676                                  uint64_t value)
4677 {
4678     /* Invalidate by VA, EL3
4679      * Currently handles both VAE3 and VALE3, since we don't support
4680      * flush-last-level-only.
4681      */
4682     ARMCPU *cpu = env_archcpu(env);
4683     CPUState *cs = CPU(cpu);
4684     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4685 
4686     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4687 }
4688 
4689 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4690                                    uint64_t value)
4691 {
4692     CPUState *cs = env_cpu(env);
4693     int mask = vae1_tlbmask(env);
4694     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4695     int bits = vae1_tlbbits(env, pageaddr);
4696 
4697     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4698 }
4699 
4700 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4701                                  uint64_t value)
4702 {
4703     /* Invalidate by VA, EL1&0 (AArch64 version).
4704      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4705      * since we don't support flush-for-specific-ASID-only or
4706      * flush-last-level-only.
4707      */
4708     CPUState *cs = env_cpu(env);
4709     int mask = vae1_tlbmask(env);
4710     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4711     int bits = vae1_tlbbits(env, pageaddr);
4712 
4713     if (tlb_force_broadcast(env)) {
4714         tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4715     } else {
4716         tlb_flush_page_bits_by_mmuidx(cs, pageaddr, mask, bits);
4717     }
4718 }
4719 
4720 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4721                                    uint64_t value)
4722 {
4723     CPUState *cs = env_cpu(env);
4724     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4725     bool secure = arm_is_secure_below_el3(env);
4726     int mask = secure ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2;
4727     int bits = tlbbits_for_regime(env, secure ? ARMMMUIdx_E2 : ARMMMUIdx_SE2,
4728                                   pageaddr);
4729 
4730     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4731 }
4732 
4733 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4734                                    uint64_t value)
4735 {
4736     CPUState *cs = env_cpu(env);
4737     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4738     int bits = tlbbits_for_regime(env, ARMMMUIdx_SE3, pageaddr);
4739 
4740     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr,
4741                                                   ARMMMUIdxBit_SE3, bits);
4742 }
4743 
4744 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4745                                       bool isread)
4746 {
4747     int cur_el = arm_current_el(env);
4748 
4749     if (cur_el < 2) {
4750         uint64_t hcr = arm_hcr_el2_eff(env);
4751 
4752         if (cur_el == 0) {
4753             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4754                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4755                     return CP_ACCESS_TRAP_EL2;
4756                 }
4757             } else {
4758                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4759                     return CP_ACCESS_TRAP;
4760                 }
4761                 if (hcr & HCR_TDZ) {
4762                     return CP_ACCESS_TRAP_EL2;
4763                 }
4764             }
4765         } else if (hcr & HCR_TDZ) {
4766             return CP_ACCESS_TRAP_EL2;
4767         }
4768     }
4769     return CP_ACCESS_OK;
4770 }
4771 
4772 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4773 {
4774     ARMCPU *cpu = env_archcpu(env);
4775     int dzp_bit = 1 << 4;
4776 
4777     /* DZP indicates whether DC ZVA access is allowed */
4778     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4779         dzp_bit = 0;
4780     }
4781     return cpu->dcz_blocksize | dzp_bit;
4782 }
4783 
4784 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4785                                     bool isread)
4786 {
4787     if (!(env->pstate & PSTATE_SP)) {
4788         /* Access to SP_EL0 is undefined if it's being used as
4789          * the stack pointer.
4790          */
4791         return CP_ACCESS_TRAP_UNCATEGORIZED;
4792     }
4793     return CP_ACCESS_OK;
4794 }
4795 
4796 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4797 {
4798     return env->pstate & PSTATE_SP;
4799 }
4800 
4801 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4802 {
4803     update_spsel(env, val);
4804 }
4805 
4806 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4807                         uint64_t value)
4808 {
4809     ARMCPU *cpu = env_archcpu(env);
4810 
4811     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4812         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4813         value &= ~SCTLR_M;
4814     }
4815 
4816     /* ??? Lots of these bits are not implemented.  */
4817 
4818     if (ri->state == ARM_CP_STATE_AA64 && !cpu_isar_feature(aa64_mte, cpu)) {
4819         if (ri->opc1 == 6) { /* SCTLR_EL3 */
4820             value &= ~(SCTLR_ITFSB | SCTLR_TCF | SCTLR_ATA);
4821         } else {
4822             value &= ~(SCTLR_ITFSB | SCTLR_TCF0 | SCTLR_TCF |
4823                        SCTLR_ATA0 | SCTLR_ATA);
4824         }
4825     }
4826 
4827     if (raw_read(env, ri) == value) {
4828         /* Skip the TLB flush if nothing actually changed; Linux likes
4829          * to do a lot of pointless SCTLR writes.
4830          */
4831         return;
4832     }
4833 
4834     raw_write(env, ri, value);
4835 
4836     /* This may enable/disable the MMU, so do a TLB flush.  */
4837     tlb_flush(CPU(cpu));
4838 
4839     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4840         /*
4841          * Normally we would always end the TB on an SCTLR write; see the
4842          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4843          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4844          * of hflags from the translator, so do it here.
4845          */
4846         arm_rebuild_hflags(env);
4847     }
4848 }
4849 
4850 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4851                                      bool isread)
4852 {
4853     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4854         return CP_ACCESS_TRAP_FP_EL2;
4855     }
4856     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4857         return CP_ACCESS_TRAP_FP_EL3;
4858     }
4859     return CP_ACCESS_OK;
4860 }
4861 
4862 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4863                        uint64_t value)
4864 {
4865     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4866 }
4867 
4868 static const ARMCPRegInfo v8_cp_reginfo[] = {
4869     /* Minimal set of EL0-visible registers. This will need to be expanded
4870      * significantly for system emulation of AArch64 CPUs.
4871      */
4872     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4873       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4874       .access = PL0_RW, .type = ARM_CP_NZCV },
4875     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4876       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4877       .type = ARM_CP_NO_RAW,
4878       .access = PL0_RW, .accessfn = aa64_daif_access,
4879       .fieldoffset = offsetof(CPUARMState, daif),
4880       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4881     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4882       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4883       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4884       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4885     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4886       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4887       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4888       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4889     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4890       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4891       .access = PL0_R, .type = ARM_CP_NO_RAW,
4892       .readfn = aa64_dczid_read },
4893     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4894       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4895       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4896 #ifndef CONFIG_USER_ONLY
4897       /* Avoid overhead of an access check that always passes in user-mode */
4898       .accessfn = aa64_zva_access,
4899 #endif
4900     },
4901     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4902       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4903       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4904     /* Cache ops: all NOPs since we don't emulate caches */
4905     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4906       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4907       .access = PL1_W, .type = ARM_CP_NOP,
4908       .accessfn = aa64_cacheop_pou_access },
4909     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4910       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4911       .access = PL1_W, .type = ARM_CP_NOP,
4912       .accessfn = aa64_cacheop_pou_access },
4913     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4914       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4915       .access = PL0_W, .type = ARM_CP_NOP,
4916       .accessfn = aa64_cacheop_pou_access },
4917     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4918       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4919       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4920       .type = ARM_CP_NOP },
4921     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4922       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4923       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4924     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4925       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4926       .access = PL0_W, .type = ARM_CP_NOP,
4927       .accessfn = aa64_cacheop_poc_access },
4928     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4929       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4930       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4931     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4932       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4933       .access = PL0_W, .type = ARM_CP_NOP,
4934       .accessfn = aa64_cacheop_pou_access },
4935     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4936       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4937       .access = PL0_W, .type = ARM_CP_NOP,
4938       .accessfn = aa64_cacheop_poc_access },
4939     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4940       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4941       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4942     /* TLBI operations */
4943     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4944       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4945       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4946       .writefn = tlbi_aa64_vmalle1is_write },
4947     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4948       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4949       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4950       .writefn = tlbi_aa64_vae1is_write },
4951     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4952       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4953       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4954       .writefn = tlbi_aa64_vmalle1is_write },
4955     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4956       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4957       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4958       .writefn = tlbi_aa64_vae1is_write },
4959     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4960       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4961       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4962       .writefn = tlbi_aa64_vae1is_write },
4963     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4964       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4965       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4966       .writefn = tlbi_aa64_vae1is_write },
4967     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4968       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4969       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4970       .writefn = tlbi_aa64_vmalle1_write },
4971     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4972       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4973       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4974       .writefn = tlbi_aa64_vae1_write },
4975     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4976       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4977       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4978       .writefn = tlbi_aa64_vmalle1_write },
4979     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4980       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4981       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4982       .writefn = tlbi_aa64_vae1_write },
4983     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4984       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4985       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4986       .writefn = tlbi_aa64_vae1_write },
4987     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4988       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4989       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4990       .writefn = tlbi_aa64_vae1_write },
4991     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4992       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4993       .access = PL2_W, .type = ARM_CP_NOP },
4994     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4995       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4996       .access = PL2_W, .type = ARM_CP_NOP },
4997     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4998       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4999       .access = PL2_W, .type = ARM_CP_NO_RAW,
5000       .writefn = tlbi_aa64_alle1is_write },
5001     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
5002       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
5003       .access = PL2_W, .type = ARM_CP_NO_RAW,
5004       .writefn = tlbi_aa64_alle1is_write },
5005     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
5006       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5007       .access = PL2_W, .type = ARM_CP_NOP },
5008     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
5009       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5010       .access = PL2_W, .type = ARM_CP_NOP },
5011     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
5012       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5013       .access = PL2_W, .type = ARM_CP_NO_RAW,
5014       .writefn = tlbi_aa64_alle1_write },
5015     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
5016       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
5017       .access = PL2_W, .type = ARM_CP_NO_RAW,
5018       .writefn = tlbi_aa64_alle1is_write },
5019 #ifndef CONFIG_USER_ONLY
5020     /* 64 bit address translation operations */
5021     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
5022       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
5023       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5024       .writefn = ats_write64 },
5025     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
5026       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
5027       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5028       .writefn = ats_write64 },
5029     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
5030       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
5031       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5032       .writefn = ats_write64 },
5033     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
5034       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
5035       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5036       .writefn = ats_write64 },
5037     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
5038       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
5039       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5040       .writefn = ats_write64 },
5041     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
5042       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
5043       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5044       .writefn = ats_write64 },
5045     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
5046       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
5047       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5048       .writefn = ats_write64 },
5049     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
5050       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
5051       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5052       .writefn = ats_write64 },
5053     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
5054     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
5055       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
5056       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5057       .writefn = ats_write64 },
5058     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
5059       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
5060       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5061       .writefn = ats_write64 },
5062     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
5063       .type = ARM_CP_ALIAS,
5064       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
5065       .access = PL1_RW, .resetvalue = 0,
5066       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
5067       .writefn = par_write },
5068 #endif
5069     /* TLB invalidate last level of translation table walk */
5070     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
5071       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5072       .writefn = tlbimva_is_write },
5073     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
5074       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5075       .writefn = tlbimvaa_is_write },
5076     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
5077       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5078       .writefn = tlbimva_write },
5079     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
5080       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5081       .writefn = tlbimvaa_write },
5082     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5083       .type = ARM_CP_NO_RAW, .access = PL2_W,
5084       .writefn = tlbimva_hyp_write },
5085     { .name = "TLBIMVALHIS",
5086       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5087       .type = ARM_CP_NO_RAW, .access = PL2_W,
5088       .writefn = tlbimva_hyp_is_write },
5089     { .name = "TLBIIPAS2",
5090       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5091       .type = ARM_CP_NOP, .access = PL2_W },
5092     { .name = "TLBIIPAS2IS",
5093       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5094       .type = ARM_CP_NOP, .access = PL2_W },
5095     { .name = "TLBIIPAS2L",
5096       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5097       .type = ARM_CP_NOP, .access = PL2_W },
5098     { .name = "TLBIIPAS2LIS",
5099       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5100       .type = ARM_CP_NOP, .access = PL2_W },
5101     /* 32 bit cache operations */
5102     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5103       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5104     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5105       .type = ARM_CP_NOP, .access = PL1_W },
5106     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5107       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5108     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5109       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5110     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5111       .type = ARM_CP_NOP, .access = PL1_W },
5112     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5113       .type = ARM_CP_NOP, .access = PL1_W },
5114     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5115       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5116     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5117       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5118     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5119       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5120     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5121       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5122     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5123       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5124     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5125       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5126     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5127       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5128     /* MMU Domain access control / MPU write buffer control */
5129     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5130       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5131       .writefn = dacr_write, .raw_writefn = raw_write,
5132       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5133                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5134     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5135       .type = ARM_CP_ALIAS,
5136       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5137       .access = PL1_RW,
5138       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5139     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5140       .type = ARM_CP_ALIAS,
5141       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5142       .access = PL1_RW,
5143       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5144     /* We rely on the access checks not allowing the guest to write to the
5145      * state field when SPSel indicates that it's being used as the stack
5146      * pointer.
5147      */
5148     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5149       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5150       .access = PL1_RW, .accessfn = sp_el0_access,
5151       .type = ARM_CP_ALIAS,
5152       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5153     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5154       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5155       .access = PL2_RW, .type = ARM_CP_ALIAS,
5156       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5157     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5158       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5159       .type = ARM_CP_NO_RAW,
5160       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5161     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5162       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5163       .type = ARM_CP_ALIAS,
5164       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
5165       .access = PL2_RW, .accessfn = fpexc32_access },
5166     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5167       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5168       .access = PL2_RW, .resetvalue = 0,
5169       .writefn = dacr_write, .raw_writefn = raw_write,
5170       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5171     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5172       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5173       .access = PL2_RW, .resetvalue = 0,
5174       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5175     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5176       .type = ARM_CP_ALIAS,
5177       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5178       .access = PL2_RW,
5179       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5180     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5181       .type = ARM_CP_ALIAS,
5182       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5183       .access = PL2_RW,
5184       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5185     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5186       .type = ARM_CP_ALIAS,
5187       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5188       .access = PL2_RW,
5189       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5190     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5191       .type = ARM_CP_ALIAS,
5192       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5193       .access = PL2_RW,
5194       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5195     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5196       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5197       .resetvalue = 0,
5198       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5199     { .name = "SDCR", .type = ARM_CP_ALIAS,
5200       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5201       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5202       .writefn = sdcr_write,
5203       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5204     REGINFO_SENTINEL
5205 };
5206 
5207 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
5208 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
5209     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5210       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5211       .access = PL2_RW,
5212       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
5213     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
5214       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5215       .access = PL2_RW,
5216       .type = ARM_CP_CONST, .resetvalue = 0 },
5217     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5218       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5219       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5220     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5221       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5222       .access = PL2_RW,
5223       .type = ARM_CP_CONST, .resetvalue = 0 },
5224     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5225       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5226       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5227     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5228       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5229       .access = PL2_RW, .type = ARM_CP_CONST,
5230       .resetvalue = 0 },
5231     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5232       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5233       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5234     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5235       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5236       .access = PL2_RW, .type = ARM_CP_CONST,
5237       .resetvalue = 0 },
5238     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5239       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5240       .access = PL2_RW, .type = ARM_CP_CONST,
5241       .resetvalue = 0 },
5242     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5243       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5244       .access = PL2_RW, .type = ARM_CP_CONST,
5245       .resetvalue = 0 },
5246     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5247       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5248       .access = PL2_RW, .type = ARM_CP_CONST,
5249       .resetvalue = 0 },
5250     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5251       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5252       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5253     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
5254       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5255       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5256       .type = ARM_CP_CONST, .resetvalue = 0 },
5257     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5258       .cp = 15, .opc1 = 6, .crm = 2,
5259       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5260       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
5261     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5262       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5263       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5264     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5265       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5266       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5267     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5268       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5269       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5270     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5271       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5272       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5273     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5274       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5275       .resetvalue = 0 },
5276     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5277       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5278       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5279     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5280       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5281       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5282     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5283       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5284       .resetvalue = 0 },
5285     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5286       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5287       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5288     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5289       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5290       .resetvalue = 0 },
5291     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5292       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5293       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5294     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5295       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5296       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5297     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5298       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5299       .access = PL2_RW, .accessfn = access_tda,
5300       .type = ARM_CP_CONST, .resetvalue = 0 },
5301     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
5302       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5303       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5304       .type = ARM_CP_CONST, .resetvalue = 0 },
5305     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5306       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5307       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5308     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5309       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5310       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5311     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5312       .type = ARM_CP_CONST,
5313       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5314       .access = PL2_RW, .resetvalue = 0 },
5315     REGINFO_SENTINEL
5316 };
5317 
5318 /* Ditto, but for registers which exist in ARMv8 but not v7 */
5319 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
5320     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5321       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5322       .access = PL2_RW,
5323       .type = ARM_CP_CONST, .resetvalue = 0 },
5324     REGINFO_SENTINEL
5325 };
5326 
5327 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5328 {
5329     ARMCPU *cpu = env_archcpu(env);
5330 
5331     if (arm_feature(env, ARM_FEATURE_V8)) {
5332         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5333     } else {
5334         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5335     }
5336 
5337     if (arm_feature(env, ARM_FEATURE_EL3)) {
5338         valid_mask &= ~HCR_HCD;
5339     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5340         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5341          * However, if we're using the SMC PSCI conduit then QEMU is
5342          * effectively acting like EL3 firmware and so the guest at
5343          * EL2 should retain the ability to prevent EL1 from being
5344          * able to make SMC calls into the ersatz firmware, so in
5345          * that case HCR.TSC should be read/write.
5346          */
5347         valid_mask &= ~HCR_TSC;
5348     }
5349 
5350     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5351         if (cpu_isar_feature(aa64_vh, cpu)) {
5352             valid_mask |= HCR_E2H;
5353         }
5354         if (cpu_isar_feature(aa64_lor, cpu)) {
5355             valid_mask |= HCR_TLOR;
5356         }
5357         if (cpu_isar_feature(aa64_pauth, cpu)) {
5358             valid_mask |= HCR_API | HCR_APK;
5359         }
5360         if (cpu_isar_feature(aa64_mte, cpu)) {
5361             valid_mask |= HCR_ATA | HCR_DCT | HCR_TID5;
5362         }
5363     }
5364 
5365     /* Clear RES0 bits.  */
5366     value &= valid_mask;
5367 
5368     /*
5369      * These bits change the MMU setup:
5370      * HCR_VM enables stage 2 translation
5371      * HCR_PTW forbids certain page-table setups
5372      * HCR_DC disables stage1 and enables stage2 translation
5373      * HCR_DCT enables tagging on (disabled) stage1 translation
5374      */
5375     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC | HCR_DCT)) {
5376         tlb_flush(CPU(cpu));
5377     }
5378     env->cp15.hcr_el2 = value;
5379 
5380     /*
5381      * Updates to VI and VF require us to update the status of
5382      * virtual interrupts, which are the logical OR of these bits
5383      * and the state of the input lines from the GIC. (This requires
5384      * that we have the iothread lock, which is done by marking the
5385      * reginfo structs as ARM_CP_IO.)
5386      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5387      * possible for it to be taken immediately, because VIRQ and
5388      * VFIQ are masked unless running at EL0 or EL1, and HCR
5389      * can only be written at EL2.
5390      */
5391     g_assert(qemu_mutex_iothread_locked());
5392     arm_cpu_update_virq(cpu);
5393     arm_cpu_update_vfiq(cpu);
5394 }
5395 
5396 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5397 {
5398     do_hcr_write(env, value, 0);
5399 }
5400 
5401 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5402                           uint64_t value)
5403 {
5404     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5405     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5406     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5407 }
5408 
5409 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5410                          uint64_t value)
5411 {
5412     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5413     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5414     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5415 }
5416 
5417 /*
5418  * Return the effective value of HCR_EL2.
5419  * Bits that are not included here:
5420  * RW       (read from SCR_EL3.RW as needed)
5421  */
5422 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5423 {
5424     uint64_t ret = env->cp15.hcr_el2;
5425 
5426     if (!arm_is_el2_enabled(env)) {
5427         /*
5428          * "This register has no effect if EL2 is not enabled in the
5429          * current Security state".  This is ARMv8.4-SecEL2 speak for
5430          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5431          *
5432          * Prior to that, the language was "In an implementation that
5433          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5434          * as if this field is 0 for all purposes other than a direct
5435          * read or write access of HCR_EL2".  With lots of enumeration
5436          * on a per-field basis.  In current QEMU, this is condition
5437          * is arm_is_secure_below_el3.
5438          *
5439          * Since the v8.4 language applies to the entire register, and
5440          * appears to be backward compatible, use that.
5441          */
5442         return 0;
5443     }
5444 
5445     /*
5446      * For a cpu that supports both aarch64 and aarch32, we can set bits
5447      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5448      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5449      */
5450     if (!arm_el_is_aa64(env, 2)) {
5451         uint64_t aa32_valid;
5452 
5453         /*
5454          * These bits are up-to-date as of ARMv8.6.
5455          * For HCR, it's easiest to list just the 2 bits that are invalid.
5456          * For HCR2, list those that are valid.
5457          */
5458         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5459         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5460                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5461         ret &= aa32_valid;
5462     }
5463 
5464     if (ret & HCR_TGE) {
5465         /* These bits are up-to-date as of ARMv8.6.  */
5466         if (ret & HCR_E2H) {
5467             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5468                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5469                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5470                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5471                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5472                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5473         } else {
5474             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5475         }
5476         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5477                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5478                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5479                  HCR_TLOR);
5480     }
5481 
5482     return ret;
5483 }
5484 
5485 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5486                            uint64_t value)
5487 {
5488     /*
5489      * For A-profile AArch32 EL3, if NSACR.CP10
5490      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5491      */
5492     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5493         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5494         value &= ~(0x3 << 10);
5495         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5496     }
5497     env->cp15.cptr_el[2] = value;
5498 }
5499 
5500 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5501 {
5502     /*
5503      * For A-profile AArch32 EL3, if NSACR.CP10
5504      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5505      */
5506     uint64_t value = env->cp15.cptr_el[2];
5507 
5508     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5509         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5510         value |= 0x3 << 10;
5511     }
5512     return value;
5513 }
5514 
5515 static const ARMCPRegInfo el2_cp_reginfo[] = {
5516     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5517       .type = ARM_CP_IO,
5518       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5519       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5520       .writefn = hcr_write },
5521     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5522       .type = ARM_CP_ALIAS | ARM_CP_IO,
5523       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5524       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5525       .writefn = hcr_writelow },
5526     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5527       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5528       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5529     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5530       .type = ARM_CP_ALIAS,
5531       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5532       .access = PL2_RW,
5533       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5534     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5535       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5536       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5537     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5538       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5539       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5540     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5541       .type = ARM_CP_ALIAS,
5542       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5543       .access = PL2_RW,
5544       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5545     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5546       .type = ARM_CP_ALIAS,
5547       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5548       .access = PL2_RW,
5549       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5550     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5551       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5552       .access = PL2_RW, .writefn = vbar_write,
5553       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5554       .resetvalue = 0 },
5555     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5556       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5557       .access = PL3_RW, .type = ARM_CP_ALIAS,
5558       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5559     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5560       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5561       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5562       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5563       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5564     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5565       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5566       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5567       .resetvalue = 0 },
5568     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5569       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5570       .access = PL2_RW, .type = ARM_CP_ALIAS,
5571       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5572     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5573       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5574       .access = PL2_RW, .type = ARM_CP_CONST,
5575       .resetvalue = 0 },
5576     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5577     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5578       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5579       .access = PL2_RW, .type = ARM_CP_CONST,
5580       .resetvalue = 0 },
5581     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5582       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5583       .access = PL2_RW, .type = ARM_CP_CONST,
5584       .resetvalue = 0 },
5585     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5586       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5587       .access = PL2_RW, .type = ARM_CP_CONST,
5588       .resetvalue = 0 },
5589     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5590       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5591       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5592       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5593       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5594     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5595       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5596       .type = ARM_CP_ALIAS,
5597       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5598       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5599     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5600       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5601       .access = PL2_RW,
5602       /* no .writefn needed as this can't cause an ASID change;
5603        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5604        */
5605       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5606     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5607       .cp = 15, .opc1 = 6, .crm = 2,
5608       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5609       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5610       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5611       .writefn = vttbr_write },
5612     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5613       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5614       .access = PL2_RW, .writefn = vttbr_write,
5615       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5616     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5617       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5618       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5619       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5620     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5621       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5622       .access = PL2_RW, .resetvalue = 0,
5623       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5624     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5625       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5626       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5627       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5628     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5629       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5630       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5631     { .name = "TLBIALLNSNH",
5632       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5633       .type = ARM_CP_NO_RAW, .access = PL2_W,
5634       .writefn = tlbiall_nsnh_write },
5635     { .name = "TLBIALLNSNHIS",
5636       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5637       .type = ARM_CP_NO_RAW, .access = PL2_W,
5638       .writefn = tlbiall_nsnh_is_write },
5639     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5640       .type = ARM_CP_NO_RAW, .access = PL2_W,
5641       .writefn = tlbiall_hyp_write },
5642     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5643       .type = ARM_CP_NO_RAW, .access = PL2_W,
5644       .writefn = tlbiall_hyp_is_write },
5645     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5646       .type = ARM_CP_NO_RAW, .access = PL2_W,
5647       .writefn = tlbimva_hyp_write },
5648     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5649       .type = ARM_CP_NO_RAW, .access = PL2_W,
5650       .writefn = tlbimva_hyp_is_write },
5651     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5652       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5653       .type = ARM_CP_NO_RAW, .access = PL2_W,
5654       .writefn = tlbi_aa64_alle2_write },
5655     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5656       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5657       .type = ARM_CP_NO_RAW, .access = PL2_W,
5658       .writefn = tlbi_aa64_vae2_write },
5659     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5660       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5661       .access = PL2_W, .type = ARM_CP_NO_RAW,
5662       .writefn = tlbi_aa64_vae2_write },
5663     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5664       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5665       .access = PL2_W, .type = ARM_CP_NO_RAW,
5666       .writefn = tlbi_aa64_alle2is_write },
5667     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5668       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5669       .type = ARM_CP_NO_RAW, .access = PL2_W,
5670       .writefn = tlbi_aa64_vae2is_write },
5671     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5672       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5673       .access = PL2_W, .type = ARM_CP_NO_RAW,
5674       .writefn = tlbi_aa64_vae2is_write },
5675 #ifndef CONFIG_USER_ONLY
5676     /* Unlike the other EL2-related AT operations, these must
5677      * UNDEF from EL3 if EL2 is not implemented, which is why we
5678      * define them here rather than with the rest of the AT ops.
5679      */
5680     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5681       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5682       .access = PL2_W, .accessfn = at_s1e2_access,
5683       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5684     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5685       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5686       .access = PL2_W, .accessfn = at_s1e2_access,
5687       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5688     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5689      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5690      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5691      * to behave as if SCR.NS was 1.
5692      */
5693     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5694       .access = PL2_W,
5695       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5696     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5697       .access = PL2_W,
5698       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5699     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5700       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5701       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5702        * reset values as IMPDEF. We choose to reset to 3 to comply with
5703        * both ARMv7 and ARMv8.
5704        */
5705       .access = PL2_RW, .resetvalue = 3,
5706       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5707     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5708       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5709       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5710       .writefn = gt_cntvoff_write,
5711       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5712     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5713       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5714       .writefn = gt_cntvoff_write,
5715       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5716     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5717       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5718       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5719       .type = ARM_CP_IO, .access = PL2_RW,
5720       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5721     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5722       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5723       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5724       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5725     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5726       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5727       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5728       .resetfn = gt_hyp_timer_reset,
5729       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5730     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5731       .type = ARM_CP_IO,
5732       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5733       .access = PL2_RW,
5734       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5735       .resetvalue = 0,
5736       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5737 #endif
5738     /* The only field of MDCR_EL2 that has a defined architectural reset value
5739      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N.
5740      */
5741     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5742       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5743       .access = PL2_RW, .resetvalue = PMCR_NUM_COUNTERS,
5744       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5745     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5746       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5747       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5748       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5749     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5750       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5751       .access = PL2_RW,
5752       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5753     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5754       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5755       .access = PL2_RW,
5756       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5757     REGINFO_SENTINEL
5758 };
5759 
5760 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5761     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5762       .type = ARM_CP_ALIAS | ARM_CP_IO,
5763       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5764       .access = PL2_RW,
5765       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5766       .writefn = hcr_writehigh },
5767     REGINFO_SENTINEL
5768 };
5769 
5770 static CPAccessResult sel2_access(CPUARMState *env, const ARMCPRegInfo *ri,
5771                                   bool isread)
5772 {
5773     if (arm_current_el(env) == 3 || arm_is_secure_below_el3(env)) {
5774         return CP_ACCESS_OK;
5775     }
5776     return CP_ACCESS_TRAP_UNCATEGORIZED;
5777 }
5778 
5779 static const ARMCPRegInfo el2_sec_cp_reginfo[] = {
5780     { .name = "VSTTBR_EL2", .state = ARM_CP_STATE_AA64,
5781       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 0,
5782       .access = PL2_RW, .accessfn = sel2_access,
5783       .fieldoffset = offsetof(CPUARMState, cp15.vsttbr_el2) },
5784     { .name = "VSTCR_EL2", .state = ARM_CP_STATE_AA64,
5785       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 2,
5786       .access = PL2_RW, .accessfn = sel2_access,
5787       .fieldoffset = offsetof(CPUARMState, cp15.vstcr_el2) },
5788     REGINFO_SENTINEL
5789 };
5790 
5791 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5792                                    bool isread)
5793 {
5794     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5795      * At Secure EL1 it traps to EL3 or EL2.
5796      */
5797     if (arm_current_el(env) == 3) {
5798         return CP_ACCESS_OK;
5799     }
5800     if (arm_is_secure_below_el3(env)) {
5801         if (env->cp15.scr_el3 & SCR_EEL2) {
5802             return CP_ACCESS_TRAP_EL2;
5803         }
5804         return CP_ACCESS_TRAP_EL3;
5805     }
5806     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5807     if (isread) {
5808         return CP_ACCESS_OK;
5809     }
5810     return CP_ACCESS_TRAP_UNCATEGORIZED;
5811 }
5812 
5813 static const ARMCPRegInfo el3_cp_reginfo[] = {
5814     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5815       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5816       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5817       .resetfn = scr_reset, .writefn = scr_write },
5818     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5819       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5820       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5821       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5822       .writefn = scr_write },
5823     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5824       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5825       .access = PL3_RW, .resetvalue = 0,
5826       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5827     { .name = "SDER",
5828       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5829       .access = PL3_RW, .resetvalue = 0,
5830       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5831     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5832       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5833       .writefn = vbar_write, .resetvalue = 0,
5834       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5835     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5836       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5837       .access = PL3_RW, .resetvalue = 0,
5838       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5839     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5840       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5841       .access = PL3_RW,
5842       /* no .writefn needed as this can't cause an ASID change;
5843        * we must provide a .raw_writefn and .resetfn because we handle
5844        * reset and migration for the AArch32 TTBCR(S), which might be
5845        * using mask and base_mask.
5846        */
5847       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5848       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5849     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5850       .type = ARM_CP_ALIAS,
5851       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5852       .access = PL3_RW,
5853       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5854     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5855       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5856       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5857     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5858       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5859       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5860     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5861       .type = ARM_CP_ALIAS,
5862       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5863       .access = PL3_RW,
5864       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5865     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5866       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5867       .access = PL3_RW, .writefn = vbar_write,
5868       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5869       .resetvalue = 0 },
5870     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5871       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5872       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5873       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5874     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5875       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5876       .access = PL3_RW, .resetvalue = 0,
5877       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5878     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5879       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5880       .access = PL3_RW, .type = ARM_CP_CONST,
5881       .resetvalue = 0 },
5882     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5883       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5884       .access = PL3_RW, .type = ARM_CP_CONST,
5885       .resetvalue = 0 },
5886     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5887       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5888       .access = PL3_RW, .type = ARM_CP_CONST,
5889       .resetvalue = 0 },
5890     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5891       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5892       .access = PL3_W, .type = ARM_CP_NO_RAW,
5893       .writefn = tlbi_aa64_alle3is_write },
5894     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5895       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5896       .access = PL3_W, .type = ARM_CP_NO_RAW,
5897       .writefn = tlbi_aa64_vae3is_write },
5898     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5899       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5900       .access = PL3_W, .type = ARM_CP_NO_RAW,
5901       .writefn = tlbi_aa64_vae3is_write },
5902     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5903       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5904       .access = PL3_W, .type = ARM_CP_NO_RAW,
5905       .writefn = tlbi_aa64_alle3_write },
5906     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5907       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5908       .access = PL3_W, .type = ARM_CP_NO_RAW,
5909       .writefn = tlbi_aa64_vae3_write },
5910     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5911       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5912       .access = PL3_W, .type = ARM_CP_NO_RAW,
5913       .writefn = tlbi_aa64_vae3_write },
5914     REGINFO_SENTINEL
5915 };
5916 
5917 #ifndef CONFIG_USER_ONLY
5918 /* Test if system register redirection is to occur in the current state.  */
5919 static bool redirect_for_e2h(CPUARMState *env)
5920 {
5921     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5922 }
5923 
5924 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5925 {
5926     CPReadFn *readfn;
5927 
5928     if (redirect_for_e2h(env)) {
5929         /* Switch to the saved EL2 version of the register.  */
5930         ri = ri->opaque;
5931         readfn = ri->readfn;
5932     } else {
5933         readfn = ri->orig_readfn;
5934     }
5935     if (readfn == NULL) {
5936         readfn = raw_read;
5937     }
5938     return readfn(env, ri);
5939 }
5940 
5941 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5942                           uint64_t value)
5943 {
5944     CPWriteFn *writefn;
5945 
5946     if (redirect_for_e2h(env)) {
5947         /* Switch to the saved EL2 version of the register.  */
5948         ri = ri->opaque;
5949         writefn = ri->writefn;
5950     } else {
5951         writefn = ri->orig_writefn;
5952     }
5953     if (writefn == NULL) {
5954         writefn = raw_write;
5955     }
5956     writefn(env, ri, value);
5957 }
5958 
5959 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5960 {
5961     struct E2HAlias {
5962         uint32_t src_key, dst_key, new_key;
5963         const char *src_name, *dst_name, *new_name;
5964         bool (*feature)(const ARMISARegisters *id);
5965     };
5966 
5967 #define K(op0, op1, crn, crm, op2) \
5968     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5969 
5970     static const struct E2HAlias aliases[] = {
5971         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5972           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5973         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5974           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5975         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5976           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5977         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5978           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5979         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5980           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5981         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5982           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5983         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5984           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5985         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5986           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5987         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5988           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5989         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5990           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5991         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5992           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5993         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5994           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5995         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5996           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5997         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5998           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5999         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
6000           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
6001         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
6002           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
6003 
6004         /*
6005          * Note that redirection of ZCR is mentioned in the description
6006          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
6007          * not in the summary table.
6008          */
6009         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
6010           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
6011 
6012         { K(3, 0,  5, 6, 0), K(3, 4,  5, 6, 0), K(3, 5, 5, 6, 0),
6013           "TFSR_EL1", "TFSR_EL2", "TFSR_EL12", isar_feature_aa64_mte },
6014 
6015         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
6016         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
6017     };
6018 #undef K
6019 
6020     size_t i;
6021 
6022     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
6023         const struct E2HAlias *a = &aliases[i];
6024         ARMCPRegInfo *src_reg, *dst_reg;
6025 
6026         if (a->feature && !a->feature(&cpu->isar)) {
6027             continue;
6028         }
6029 
6030         src_reg = g_hash_table_lookup(cpu->cp_regs, &a->src_key);
6031         dst_reg = g_hash_table_lookup(cpu->cp_regs, &a->dst_key);
6032         g_assert(src_reg != NULL);
6033         g_assert(dst_reg != NULL);
6034 
6035         /* Cross-compare names to detect typos in the keys.  */
6036         g_assert(strcmp(src_reg->name, a->src_name) == 0);
6037         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
6038 
6039         /* None of the core system registers use opaque; we will.  */
6040         g_assert(src_reg->opaque == NULL);
6041 
6042         /* Create alias before redirection so we dup the right data. */
6043         if (a->new_key) {
6044             ARMCPRegInfo *new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
6045             uint32_t *new_key = g_memdup(&a->new_key, sizeof(uint32_t));
6046             bool ok;
6047 
6048             new_reg->name = a->new_name;
6049             new_reg->type |= ARM_CP_ALIAS;
6050             /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
6051             new_reg->access &= PL2_RW | PL3_RW;
6052 
6053             ok = g_hash_table_insert(cpu->cp_regs, new_key, new_reg);
6054             g_assert(ok);
6055         }
6056 
6057         src_reg->opaque = dst_reg;
6058         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
6059         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
6060         if (!src_reg->raw_readfn) {
6061             src_reg->raw_readfn = raw_read;
6062         }
6063         if (!src_reg->raw_writefn) {
6064             src_reg->raw_writefn = raw_write;
6065         }
6066         src_reg->readfn = el2_e2h_read;
6067         src_reg->writefn = el2_e2h_write;
6068     }
6069 }
6070 #endif
6071 
6072 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
6073                                      bool isread)
6074 {
6075     int cur_el = arm_current_el(env);
6076 
6077     if (cur_el < 2) {
6078         uint64_t hcr = arm_hcr_el2_eff(env);
6079 
6080         if (cur_el == 0) {
6081             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
6082                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
6083                     return CP_ACCESS_TRAP_EL2;
6084                 }
6085             } else {
6086                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
6087                     return CP_ACCESS_TRAP;
6088                 }
6089                 if (hcr & HCR_TID2) {
6090                     return CP_ACCESS_TRAP_EL2;
6091                 }
6092             }
6093         } else if (hcr & HCR_TID2) {
6094             return CP_ACCESS_TRAP_EL2;
6095         }
6096     }
6097 
6098     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
6099         return CP_ACCESS_TRAP_EL2;
6100     }
6101 
6102     return CP_ACCESS_OK;
6103 }
6104 
6105 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
6106                         uint64_t value)
6107 {
6108     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
6109      * read via a bit in OSLSR_EL1.
6110      */
6111     int oslock;
6112 
6113     if (ri->state == ARM_CP_STATE_AA32) {
6114         oslock = (value == 0xC5ACCE55);
6115     } else {
6116         oslock = value & 1;
6117     }
6118 
6119     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
6120 }
6121 
6122 static const ARMCPRegInfo debug_cp_reginfo[] = {
6123     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
6124      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
6125      * unlike DBGDRAR it is never accessible from EL0.
6126      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
6127      * accessor.
6128      */
6129     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
6130       .access = PL0_R, .accessfn = access_tdra,
6131       .type = ARM_CP_CONST, .resetvalue = 0 },
6132     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
6133       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6134       .access = PL1_R, .accessfn = access_tdra,
6135       .type = ARM_CP_CONST, .resetvalue = 0 },
6136     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
6137       .access = PL0_R, .accessfn = access_tdra,
6138       .type = ARM_CP_CONST, .resetvalue = 0 },
6139     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
6140     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
6141       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
6142       .access = PL1_RW, .accessfn = access_tda,
6143       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
6144       .resetvalue = 0 },
6145     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
6146      * We don't implement the configurable EL0 access.
6147      */
6148     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
6149       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6150       .type = ARM_CP_ALIAS,
6151       .access = PL1_R, .accessfn = access_tda,
6152       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
6153     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
6154       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
6155       .access = PL1_W, .type = ARM_CP_NO_RAW,
6156       .accessfn = access_tdosa,
6157       .writefn = oslar_write },
6158     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
6159       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
6160       .access = PL1_R, .resetvalue = 10,
6161       .accessfn = access_tdosa,
6162       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
6163     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
6164     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
6165       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
6166       .access = PL1_RW, .accessfn = access_tdosa,
6167       .type = ARM_CP_NOP },
6168     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
6169      * implement vector catch debug events yet.
6170      */
6171     { .name = "DBGVCR",
6172       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6173       .access = PL1_RW, .accessfn = access_tda,
6174       .type = ARM_CP_NOP },
6175     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
6176      * to save and restore a 32-bit guest's DBGVCR)
6177      */
6178     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
6179       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
6180       .access = PL2_RW, .accessfn = access_tda,
6181       .type = ARM_CP_NOP },
6182     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6183      * Channel but Linux may try to access this register. The 32-bit
6184      * alias is DBGDCCINT.
6185      */
6186     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6187       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6188       .access = PL1_RW, .accessfn = access_tda,
6189       .type = ARM_CP_NOP },
6190     REGINFO_SENTINEL
6191 };
6192 
6193 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6194     /* 64 bit access versions of the (dummy) debug registers */
6195     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6196       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6197     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6198       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6199     REGINFO_SENTINEL
6200 };
6201 
6202 /* Return the exception level to which exceptions should be taken
6203  * via SVEAccessTrap.  If an exception should be routed through
6204  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6205  * take care of raising that exception.
6206  * C.f. the ARM pseudocode function CheckSVEEnabled.
6207  */
6208 int sve_exception_el(CPUARMState *env, int el)
6209 {
6210 #ifndef CONFIG_USER_ONLY
6211     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6212 
6213     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6214         bool disabled = false;
6215 
6216         /* The CPACR.ZEN controls traps to EL1:
6217          * 0, 2 : trap EL0 and EL1 accesses
6218          * 1    : trap only EL0 accesses
6219          * 3    : trap no accesses
6220          */
6221         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
6222             disabled = true;
6223         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
6224             disabled = el == 0;
6225         }
6226         if (disabled) {
6227             /* route_to_el2 */
6228             return hcr_el2 & HCR_TGE ? 2 : 1;
6229         }
6230 
6231         /* Check CPACR.FPEN.  */
6232         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
6233             disabled = true;
6234         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
6235             disabled = el == 0;
6236         }
6237         if (disabled) {
6238             return 0;
6239         }
6240     }
6241 
6242     /* CPTR_EL2.  Since TZ and TFP are positive,
6243      * they will be zero when EL2 is not present.
6244      */
6245     if (el <= 2 && arm_is_el2_enabled(env)) {
6246         if (env->cp15.cptr_el[2] & CPTR_TZ) {
6247             return 2;
6248         }
6249         if (env->cp15.cptr_el[2] & CPTR_TFP) {
6250             return 0;
6251         }
6252     }
6253 
6254     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6255     if (arm_feature(env, ARM_FEATURE_EL3)
6256         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6257         return 3;
6258     }
6259 #endif
6260     return 0;
6261 }
6262 
6263 static uint32_t sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6264 {
6265     uint32_t end_len;
6266 
6267     end_len = start_len &= 0xf;
6268     if (!test_bit(start_len, cpu->sve_vq_map)) {
6269         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6270         assert(end_len < start_len);
6271     }
6272     return end_len;
6273 }
6274 
6275 /*
6276  * Given that SVE is enabled, return the vector length for EL.
6277  */
6278 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6279 {
6280     ARMCPU *cpu = env_archcpu(env);
6281     uint32_t zcr_len = cpu->sve_max_vq - 1;
6282 
6283     if (el <= 1) {
6284         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6285     }
6286     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6287         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6288     }
6289     if (arm_feature(env, ARM_FEATURE_EL3)) {
6290         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6291     }
6292 
6293     return sve_zcr_get_valid_len(cpu, zcr_len);
6294 }
6295 
6296 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6297                       uint64_t value)
6298 {
6299     int cur_el = arm_current_el(env);
6300     int old_len = sve_zcr_len_for_el(env, cur_el);
6301     int new_len;
6302 
6303     /* Bits other than [3:0] are RAZ/WI.  */
6304     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6305     raw_write(env, ri, value & 0xf);
6306 
6307     /*
6308      * Because we arrived here, we know both FP and SVE are enabled;
6309      * otherwise we would have trapped access to the ZCR_ELn register.
6310      */
6311     new_len = sve_zcr_len_for_el(env, cur_el);
6312     if (new_len < old_len) {
6313         aarch64_sve_narrow_vq(env, new_len + 1);
6314     }
6315 }
6316 
6317 static const ARMCPRegInfo zcr_el1_reginfo = {
6318     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6319     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6320     .access = PL1_RW, .type = ARM_CP_SVE,
6321     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6322     .writefn = zcr_write, .raw_writefn = raw_write
6323 };
6324 
6325 static const ARMCPRegInfo zcr_el2_reginfo = {
6326     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6327     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6328     .access = PL2_RW, .type = ARM_CP_SVE,
6329     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6330     .writefn = zcr_write, .raw_writefn = raw_write
6331 };
6332 
6333 static const ARMCPRegInfo zcr_no_el2_reginfo = {
6334     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6335     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6336     .access = PL2_RW, .type = ARM_CP_SVE,
6337     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
6338 };
6339 
6340 static const ARMCPRegInfo zcr_el3_reginfo = {
6341     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6342     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6343     .access = PL3_RW, .type = ARM_CP_SVE,
6344     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6345     .writefn = zcr_write, .raw_writefn = raw_write
6346 };
6347 
6348 void hw_watchpoint_update(ARMCPU *cpu, int n)
6349 {
6350     CPUARMState *env = &cpu->env;
6351     vaddr len = 0;
6352     vaddr wvr = env->cp15.dbgwvr[n];
6353     uint64_t wcr = env->cp15.dbgwcr[n];
6354     int mask;
6355     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6356 
6357     if (env->cpu_watchpoint[n]) {
6358         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6359         env->cpu_watchpoint[n] = NULL;
6360     }
6361 
6362     if (!extract64(wcr, 0, 1)) {
6363         /* E bit clear : watchpoint disabled */
6364         return;
6365     }
6366 
6367     switch (extract64(wcr, 3, 2)) {
6368     case 0:
6369         /* LSC 00 is reserved and must behave as if the wp is disabled */
6370         return;
6371     case 1:
6372         flags |= BP_MEM_READ;
6373         break;
6374     case 2:
6375         flags |= BP_MEM_WRITE;
6376         break;
6377     case 3:
6378         flags |= BP_MEM_ACCESS;
6379         break;
6380     }
6381 
6382     /* Attempts to use both MASK and BAS fields simultaneously are
6383      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6384      * thus generating a watchpoint for every byte in the masked region.
6385      */
6386     mask = extract64(wcr, 24, 4);
6387     if (mask == 1 || mask == 2) {
6388         /* Reserved values of MASK; we must act as if the mask value was
6389          * some non-reserved value, or as if the watchpoint were disabled.
6390          * We choose the latter.
6391          */
6392         return;
6393     } else if (mask) {
6394         /* Watchpoint covers an aligned area up to 2GB in size */
6395         len = 1ULL << mask;
6396         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6397          * whether the watchpoint fires when the unmasked bits match; we opt
6398          * to generate the exceptions.
6399          */
6400         wvr &= ~(len - 1);
6401     } else {
6402         /* Watchpoint covers bytes defined by the byte address select bits */
6403         int bas = extract64(wcr, 5, 8);
6404         int basstart;
6405 
6406         if (extract64(wvr, 2, 1)) {
6407             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6408              * ignored, and BAS[3:0] define which bytes to watch.
6409              */
6410             bas &= 0xf;
6411         }
6412 
6413         if (bas == 0) {
6414             /* This must act as if the watchpoint is disabled */
6415             return;
6416         }
6417 
6418         /* The BAS bits are supposed to be programmed to indicate a contiguous
6419          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6420          * we fire for each byte in the word/doubleword addressed by the WVR.
6421          * We choose to ignore any non-zero bits after the first range of 1s.
6422          */
6423         basstart = ctz32(bas);
6424         len = cto32(bas >> basstart);
6425         wvr += basstart;
6426     }
6427 
6428     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6429                           &env->cpu_watchpoint[n]);
6430 }
6431 
6432 void hw_watchpoint_update_all(ARMCPU *cpu)
6433 {
6434     int i;
6435     CPUARMState *env = &cpu->env;
6436 
6437     /* Completely clear out existing QEMU watchpoints and our array, to
6438      * avoid possible stale entries following migration load.
6439      */
6440     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6441     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6442 
6443     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6444         hw_watchpoint_update(cpu, i);
6445     }
6446 }
6447 
6448 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6449                          uint64_t value)
6450 {
6451     ARMCPU *cpu = env_archcpu(env);
6452     int i = ri->crm;
6453 
6454     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
6455      * register reads and behaves as if values written are sign extended.
6456      * Bits [1:0] are RES0.
6457      */
6458     value = sextract64(value, 0, 49) & ~3ULL;
6459 
6460     raw_write(env, ri, value);
6461     hw_watchpoint_update(cpu, i);
6462 }
6463 
6464 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6465                          uint64_t value)
6466 {
6467     ARMCPU *cpu = env_archcpu(env);
6468     int i = ri->crm;
6469 
6470     raw_write(env, ri, value);
6471     hw_watchpoint_update(cpu, i);
6472 }
6473 
6474 void hw_breakpoint_update(ARMCPU *cpu, int n)
6475 {
6476     CPUARMState *env = &cpu->env;
6477     uint64_t bvr = env->cp15.dbgbvr[n];
6478     uint64_t bcr = env->cp15.dbgbcr[n];
6479     vaddr addr;
6480     int bt;
6481     int flags = BP_CPU;
6482 
6483     if (env->cpu_breakpoint[n]) {
6484         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6485         env->cpu_breakpoint[n] = NULL;
6486     }
6487 
6488     if (!extract64(bcr, 0, 1)) {
6489         /* E bit clear : watchpoint disabled */
6490         return;
6491     }
6492 
6493     bt = extract64(bcr, 20, 4);
6494 
6495     switch (bt) {
6496     case 4: /* unlinked address mismatch (reserved if AArch64) */
6497     case 5: /* linked address mismatch (reserved if AArch64) */
6498         qemu_log_mask(LOG_UNIMP,
6499                       "arm: address mismatch breakpoint types not implemented\n");
6500         return;
6501     case 0: /* unlinked address match */
6502     case 1: /* linked address match */
6503     {
6504         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
6505          * we behave as if the register was sign extended. Bits [1:0] are
6506          * RES0. The BAS field is used to allow setting breakpoints on 16
6507          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6508          * a bp will fire if the addresses covered by the bp and the addresses
6509          * covered by the insn overlap but the insn doesn't start at the
6510          * start of the bp address range. We choose to require the insn and
6511          * the bp to have the same address. The constraints on writing to
6512          * BAS enforced in dbgbcr_write mean we have only four cases:
6513          *  0b0000  => no breakpoint
6514          *  0b0011  => breakpoint on addr
6515          *  0b1100  => breakpoint on addr + 2
6516          *  0b1111  => breakpoint on addr
6517          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6518          */
6519         int bas = extract64(bcr, 5, 4);
6520         addr = sextract64(bvr, 0, 49) & ~3ULL;
6521         if (bas == 0) {
6522             return;
6523         }
6524         if (bas == 0xc) {
6525             addr += 2;
6526         }
6527         break;
6528     }
6529     case 2: /* unlinked context ID match */
6530     case 8: /* unlinked VMID match (reserved if no EL2) */
6531     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6532         qemu_log_mask(LOG_UNIMP,
6533                       "arm: unlinked context breakpoint types not implemented\n");
6534         return;
6535     case 9: /* linked VMID match (reserved if no EL2) */
6536     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6537     case 3: /* linked context ID match */
6538     default:
6539         /* We must generate no events for Linked context matches (unless
6540          * they are linked to by some other bp/wp, which is handled in
6541          * updates for the linking bp/wp). We choose to also generate no events
6542          * for reserved values.
6543          */
6544         return;
6545     }
6546 
6547     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6548 }
6549 
6550 void hw_breakpoint_update_all(ARMCPU *cpu)
6551 {
6552     int i;
6553     CPUARMState *env = &cpu->env;
6554 
6555     /* Completely clear out existing QEMU breakpoints and our array, to
6556      * avoid possible stale entries following migration load.
6557      */
6558     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6559     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6560 
6561     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6562         hw_breakpoint_update(cpu, i);
6563     }
6564 }
6565 
6566 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6567                          uint64_t value)
6568 {
6569     ARMCPU *cpu = env_archcpu(env);
6570     int i = ri->crm;
6571 
6572     raw_write(env, ri, value);
6573     hw_breakpoint_update(cpu, i);
6574 }
6575 
6576 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6577                          uint64_t value)
6578 {
6579     ARMCPU *cpu = env_archcpu(env);
6580     int i = ri->crm;
6581 
6582     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6583      * copy of BAS[0].
6584      */
6585     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6586     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6587 
6588     raw_write(env, ri, value);
6589     hw_breakpoint_update(cpu, i);
6590 }
6591 
6592 static void define_debug_regs(ARMCPU *cpu)
6593 {
6594     /* Define v7 and v8 architectural debug registers.
6595      * These are just dummy implementations for now.
6596      */
6597     int i;
6598     int wrps, brps, ctx_cmps;
6599 
6600     /*
6601      * The Arm ARM says DBGDIDR is optional and deprecated if EL1 cannot
6602      * use AArch32.  Given that bit 15 is RES1, if the value is 0 then
6603      * the register must not exist for this cpu.
6604      */
6605     if (cpu->isar.dbgdidr != 0) {
6606         ARMCPRegInfo dbgdidr = {
6607             .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0,
6608             .opc1 = 0, .opc2 = 0,
6609             .access = PL0_R, .accessfn = access_tda,
6610             .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6611         };
6612         define_one_arm_cp_reg(cpu, &dbgdidr);
6613     }
6614 
6615     /* Note that all these register fields hold "number of Xs minus 1". */
6616     brps = arm_num_brps(cpu);
6617     wrps = arm_num_wrps(cpu);
6618     ctx_cmps = arm_num_ctx_cmps(cpu);
6619 
6620     assert(ctx_cmps <= brps);
6621 
6622     define_arm_cp_regs(cpu, debug_cp_reginfo);
6623 
6624     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6625         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6626     }
6627 
6628     for (i = 0; i < brps; i++) {
6629         ARMCPRegInfo dbgregs[] = {
6630             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6631               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6632               .access = PL1_RW, .accessfn = access_tda,
6633               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6634               .writefn = dbgbvr_write, .raw_writefn = raw_write
6635             },
6636             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6637               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6638               .access = PL1_RW, .accessfn = access_tda,
6639               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6640               .writefn = dbgbcr_write, .raw_writefn = raw_write
6641             },
6642             REGINFO_SENTINEL
6643         };
6644         define_arm_cp_regs(cpu, dbgregs);
6645     }
6646 
6647     for (i = 0; i < wrps; i++) {
6648         ARMCPRegInfo dbgregs[] = {
6649             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6650               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6651               .access = PL1_RW, .accessfn = access_tda,
6652               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6653               .writefn = dbgwvr_write, .raw_writefn = raw_write
6654             },
6655             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6656               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6657               .access = PL1_RW, .accessfn = access_tda,
6658               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6659               .writefn = dbgwcr_write, .raw_writefn = raw_write
6660             },
6661             REGINFO_SENTINEL
6662         };
6663         define_arm_cp_regs(cpu, dbgregs);
6664     }
6665 }
6666 
6667 static void define_pmu_regs(ARMCPU *cpu)
6668 {
6669     /*
6670      * v7 performance monitor control register: same implementor
6671      * field as main ID register, and we implement four counters in
6672      * addition to the cycle count register.
6673      */
6674     unsigned int i, pmcrn = PMCR_NUM_COUNTERS;
6675     ARMCPRegInfo pmcr = {
6676         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6677         .access = PL0_RW,
6678         .type = ARM_CP_IO | ARM_CP_ALIAS,
6679         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6680         .accessfn = pmreg_access, .writefn = pmcr_write,
6681         .raw_writefn = raw_write,
6682     };
6683     ARMCPRegInfo pmcr64 = {
6684         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6685         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6686         .access = PL0_RW, .accessfn = pmreg_access,
6687         .type = ARM_CP_IO,
6688         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6689         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6690                       PMCRLC,
6691         .writefn = pmcr_write, .raw_writefn = raw_write,
6692     };
6693     define_one_arm_cp_reg(cpu, &pmcr);
6694     define_one_arm_cp_reg(cpu, &pmcr64);
6695     for (i = 0; i < pmcrn; i++) {
6696         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6697         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6698         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6699         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6700         ARMCPRegInfo pmev_regs[] = {
6701             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6702               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6703               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6704               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6705               .accessfn = pmreg_access },
6706             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6707               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6708               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6709               .type = ARM_CP_IO,
6710               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6711               .raw_readfn = pmevcntr_rawread,
6712               .raw_writefn = pmevcntr_rawwrite },
6713             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6714               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6715               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6716               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6717               .accessfn = pmreg_access },
6718             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6719               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6720               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6721               .type = ARM_CP_IO,
6722               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6723               .raw_writefn = pmevtyper_rawwrite },
6724             REGINFO_SENTINEL
6725         };
6726         define_arm_cp_regs(cpu, pmev_regs);
6727         g_free(pmevcntr_name);
6728         g_free(pmevcntr_el0_name);
6729         g_free(pmevtyper_name);
6730         g_free(pmevtyper_el0_name);
6731     }
6732     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6733         ARMCPRegInfo v81_pmu_regs[] = {
6734             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6735               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6736               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6737               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6738             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6739               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6740               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6741               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6742             REGINFO_SENTINEL
6743         };
6744         define_arm_cp_regs(cpu, v81_pmu_regs);
6745     }
6746     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6747         static const ARMCPRegInfo v84_pmmir = {
6748             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6749             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6750             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6751             .resetvalue = 0
6752         };
6753         define_one_arm_cp_reg(cpu, &v84_pmmir);
6754     }
6755 }
6756 
6757 /* We don't know until after realize whether there's a GICv3
6758  * attached, and that is what registers the gicv3 sysregs.
6759  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6760  * at runtime.
6761  */
6762 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6763 {
6764     ARMCPU *cpu = env_archcpu(env);
6765     uint64_t pfr1 = cpu->isar.id_pfr1;
6766 
6767     if (env->gicv3state) {
6768         pfr1 |= 1 << 28;
6769     }
6770     return pfr1;
6771 }
6772 
6773 #ifndef CONFIG_USER_ONLY
6774 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6775 {
6776     ARMCPU *cpu = env_archcpu(env);
6777     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6778 
6779     if (env->gicv3state) {
6780         pfr0 |= 1 << 24;
6781     }
6782     return pfr0;
6783 }
6784 #endif
6785 
6786 /* Shared logic between LORID and the rest of the LOR* registers.
6787  * Secure state exclusion has already been dealt with.
6788  */
6789 static CPAccessResult access_lor_ns(CPUARMState *env,
6790                                     const ARMCPRegInfo *ri, bool isread)
6791 {
6792     int el = arm_current_el(env);
6793 
6794     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6795         return CP_ACCESS_TRAP_EL2;
6796     }
6797     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6798         return CP_ACCESS_TRAP_EL3;
6799     }
6800     return CP_ACCESS_OK;
6801 }
6802 
6803 static CPAccessResult access_lor_other(CPUARMState *env,
6804                                        const ARMCPRegInfo *ri, bool isread)
6805 {
6806     if (arm_is_secure_below_el3(env)) {
6807         /* Access denied in secure mode.  */
6808         return CP_ACCESS_TRAP;
6809     }
6810     return access_lor_ns(env, ri, isread);
6811 }
6812 
6813 /*
6814  * A trivial implementation of ARMv8.1-LOR leaves all of these
6815  * registers fixed at 0, which indicates that there are zero
6816  * supported Limited Ordering regions.
6817  */
6818 static const ARMCPRegInfo lor_reginfo[] = {
6819     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6820       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6821       .access = PL1_RW, .accessfn = access_lor_other,
6822       .type = ARM_CP_CONST, .resetvalue = 0 },
6823     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6824       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6825       .access = PL1_RW, .accessfn = access_lor_other,
6826       .type = ARM_CP_CONST, .resetvalue = 0 },
6827     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6828       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6829       .access = PL1_RW, .accessfn = access_lor_other,
6830       .type = ARM_CP_CONST, .resetvalue = 0 },
6831     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6832       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6833       .access = PL1_RW, .accessfn = access_lor_other,
6834       .type = ARM_CP_CONST, .resetvalue = 0 },
6835     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6836       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6837       .access = PL1_R, .accessfn = access_lor_ns,
6838       .type = ARM_CP_CONST, .resetvalue = 0 },
6839     REGINFO_SENTINEL
6840 };
6841 
6842 #ifdef TARGET_AARCH64
6843 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6844                                    bool isread)
6845 {
6846     int el = arm_current_el(env);
6847 
6848     if (el < 2 &&
6849         arm_feature(env, ARM_FEATURE_EL2) &&
6850         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6851         return CP_ACCESS_TRAP_EL2;
6852     }
6853     if (el < 3 &&
6854         arm_feature(env, ARM_FEATURE_EL3) &&
6855         !(env->cp15.scr_el3 & SCR_APK)) {
6856         return CP_ACCESS_TRAP_EL3;
6857     }
6858     return CP_ACCESS_OK;
6859 }
6860 
6861 static const ARMCPRegInfo pauth_reginfo[] = {
6862     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6863       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6864       .access = PL1_RW, .accessfn = access_pauth,
6865       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6866     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6867       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6868       .access = PL1_RW, .accessfn = access_pauth,
6869       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6870     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6871       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6872       .access = PL1_RW, .accessfn = access_pauth,
6873       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6874     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6875       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6876       .access = PL1_RW, .accessfn = access_pauth,
6877       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6878     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6879       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6880       .access = PL1_RW, .accessfn = access_pauth,
6881       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6882     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6883       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6884       .access = PL1_RW, .accessfn = access_pauth,
6885       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6886     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6887       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6888       .access = PL1_RW, .accessfn = access_pauth,
6889       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6890     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6891       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6892       .access = PL1_RW, .accessfn = access_pauth,
6893       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6894     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6895       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6896       .access = PL1_RW, .accessfn = access_pauth,
6897       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6898     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6899       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6900       .access = PL1_RW, .accessfn = access_pauth,
6901       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6902     REGINFO_SENTINEL
6903 };
6904 
6905 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
6906 {
6907     Error *err = NULL;
6908     uint64_t ret;
6909 
6910     /* Success sets NZCV = 0000.  */
6911     env->NF = env->CF = env->VF = 0, env->ZF = 1;
6912 
6913     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
6914         /*
6915          * ??? Failed, for unknown reasons in the crypto subsystem.
6916          * The best we can do is log the reason and return the
6917          * timed-out indication to the guest.  There is no reason
6918          * we know to expect this failure to be transitory, so the
6919          * guest may well hang retrying the operation.
6920          */
6921         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
6922                       ri->name, error_get_pretty(err));
6923         error_free(err);
6924 
6925         env->ZF = 0; /* NZCF = 0100 */
6926         return 0;
6927     }
6928     return ret;
6929 }
6930 
6931 /* We do not support re-seeding, so the two registers operate the same.  */
6932 static const ARMCPRegInfo rndr_reginfo[] = {
6933     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
6934       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6935       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
6936       .access = PL0_R, .readfn = rndr_readfn },
6937     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
6938       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6939       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
6940       .access = PL0_R, .readfn = rndr_readfn },
6941     REGINFO_SENTINEL
6942 };
6943 
6944 #ifndef CONFIG_USER_ONLY
6945 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
6946                           uint64_t value)
6947 {
6948     ARMCPU *cpu = env_archcpu(env);
6949     /* CTR_EL0 System register -> DminLine, bits [19:16] */
6950     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
6951     uint64_t vaddr_in = (uint64_t) value;
6952     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
6953     void *haddr;
6954     int mem_idx = cpu_mmu_index(env, false);
6955 
6956     /* This won't be crossing page boundaries */
6957     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
6958     if (haddr) {
6959 
6960         ram_addr_t offset;
6961         MemoryRegion *mr;
6962 
6963         /* RCU lock is already being held */
6964         mr = memory_region_from_host(haddr, &offset);
6965 
6966         if (mr) {
6967             memory_region_writeback(mr, offset, dline_size);
6968         }
6969     }
6970 }
6971 
6972 static const ARMCPRegInfo dcpop_reg[] = {
6973     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
6974       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
6975       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6976       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6977     REGINFO_SENTINEL
6978 };
6979 
6980 static const ARMCPRegInfo dcpodp_reg[] = {
6981     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
6982       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
6983       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6984       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6985     REGINFO_SENTINEL
6986 };
6987 #endif /*CONFIG_USER_ONLY*/
6988 
6989 static CPAccessResult access_aa64_tid5(CPUARMState *env, const ARMCPRegInfo *ri,
6990                                        bool isread)
6991 {
6992     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID5)) {
6993         return CP_ACCESS_TRAP_EL2;
6994     }
6995 
6996     return CP_ACCESS_OK;
6997 }
6998 
6999 static CPAccessResult access_mte(CPUARMState *env, const ARMCPRegInfo *ri,
7000                                  bool isread)
7001 {
7002     int el = arm_current_el(env);
7003 
7004     if (el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
7005         uint64_t hcr = arm_hcr_el2_eff(env);
7006         if (!(hcr & HCR_ATA) && (!(hcr & HCR_E2H) || !(hcr & HCR_TGE))) {
7007             return CP_ACCESS_TRAP_EL2;
7008         }
7009     }
7010     if (el < 3 &&
7011         arm_feature(env, ARM_FEATURE_EL3) &&
7012         !(env->cp15.scr_el3 & SCR_ATA)) {
7013         return CP_ACCESS_TRAP_EL3;
7014     }
7015     return CP_ACCESS_OK;
7016 }
7017 
7018 static uint64_t tco_read(CPUARMState *env, const ARMCPRegInfo *ri)
7019 {
7020     return env->pstate & PSTATE_TCO;
7021 }
7022 
7023 static void tco_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
7024 {
7025     env->pstate = (env->pstate & ~PSTATE_TCO) | (val & PSTATE_TCO);
7026 }
7027 
7028 static const ARMCPRegInfo mte_reginfo[] = {
7029     { .name = "TFSRE0_EL1", .state = ARM_CP_STATE_AA64,
7030       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 1,
7031       .access = PL1_RW, .accessfn = access_mte,
7032       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[0]) },
7033     { .name = "TFSR_EL1", .state = ARM_CP_STATE_AA64,
7034       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 0,
7035       .access = PL1_RW, .accessfn = access_mte,
7036       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[1]) },
7037     { .name = "TFSR_EL2", .state = ARM_CP_STATE_AA64,
7038       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 6, .opc2 = 0,
7039       .access = PL2_RW, .accessfn = access_mte,
7040       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[2]) },
7041     { .name = "TFSR_EL3", .state = ARM_CP_STATE_AA64,
7042       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 6, .opc2 = 0,
7043       .access = PL3_RW,
7044       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[3]) },
7045     { .name = "RGSR_EL1", .state = ARM_CP_STATE_AA64,
7046       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 5,
7047       .access = PL1_RW, .accessfn = access_mte,
7048       .fieldoffset = offsetof(CPUARMState, cp15.rgsr_el1) },
7049     { .name = "GCR_EL1", .state = ARM_CP_STATE_AA64,
7050       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 6,
7051       .access = PL1_RW, .accessfn = access_mte,
7052       .fieldoffset = offsetof(CPUARMState, cp15.gcr_el1) },
7053     { .name = "GMID_EL1", .state = ARM_CP_STATE_AA64,
7054       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 4,
7055       .access = PL1_R, .accessfn = access_aa64_tid5,
7056       .type = ARM_CP_CONST, .resetvalue = GMID_EL1_BS },
7057     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7058       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7059       .type = ARM_CP_NO_RAW,
7060       .access = PL0_RW, .readfn = tco_read, .writefn = tco_write },
7061     { .name = "DC_IGVAC", .state = ARM_CP_STATE_AA64,
7062       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 3,
7063       .type = ARM_CP_NOP, .access = PL1_W,
7064       .accessfn = aa64_cacheop_poc_access },
7065     { .name = "DC_IGSW", .state = ARM_CP_STATE_AA64,
7066       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 4,
7067       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7068     { .name = "DC_IGDVAC", .state = ARM_CP_STATE_AA64,
7069       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 5,
7070       .type = ARM_CP_NOP, .access = PL1_W,
7071       .accessfn = aa64_cacheop_poc_access },
7072     { .name = "DC_IGDSW", .state = ARM_CP_STATE_AA64,
7073       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 6,
7074       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7075     { .name = "DC_CGSW", .state = ARM_CP_STATE_AA64,
7076       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 4,
7077       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7078     { .name = "DC_CGDSW", .state = ARM_CP_STATE_AA64,
7079       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 6,
7080       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7081     { .name = "DC_CIGSW", .state = ARM_CP_STATE_AA64,
7082       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 4,
7083       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7084     { .name = "DC_CIGDSW", .state = ARM_CP_STATE_AA64,
7085       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 6,
7086       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7087     REGINFO_SENTINEL
7088 };
7089 
7090 static const ARMCPRegInfo mte_tco_ro_reginfo[] = {
7091     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7092       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7093       .type = ARM_CP_CONST, .access = PL0_RW, },
7094     REGINFO_SENTINEL
7095 };
7096 
7097 static const ARMCPRegInfo mte_el0_cacheop_reginfo[] = {
7098     { .name = "DC_CGVAC", .state = ARM_CP_STATE_AA64,
7099       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 3,
7100       .type = ARM_CP_NOP, .access = PL0_W,
7101       .accessfn = aa64_cacheop_poc_access },
7102     { .name = "DC_CGDVAC", .state = ARM_CP_STATE_AA64,
7103       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 5,
7104       .type = ARM_CP_NOP, .access = PL0_W,
7105       .accessfn = aa64_cacheop_poc_access },
7106     { .name = "DC_CGVAP", .state = ARM_CP_STATE_AA64,
7107       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 3,
7108       .type = ARM_CP_NOP, .access = PL0_W,
7109       .accessfn = aa64_cacheop_poc_access },
7110     { .name = "DC_CGDVAP", .state = ARM_CP_STATE_AA64,
7111       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 5,
7112       .type = ARM_CP_NOP, .access = PL0_W,
7113       .accessfn = aa64_cacheop_poc_access },
7114     { .name = "DC_CGVADP", .state = ARM_CP_STATE_AA64,
7115       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 3,
7116       .type = ARM_CP_NOP, .access = PL0_W,
7117       .accessfn = aa64_cacheop_poc_access },
7118     { .name = "DC_CGDVADP", .state = ARM_CP_STATE_AA64,
7119       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 5,
7120       .type = ARM_CP_NOP, .access = PL0_W,
7121       .accessfn = aa64_cacheop_poc_access },
7122     { .name = "DC_CIGVAC", .state = ARM_CP_STATE_AA64,
7123       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 3,
7124       .type = ARM_CP_NOP, .access = PL0_W,
7125       .accessfn = aa64_cacheop_poc_access },
7126     { .name = "DC_CIGDVAC", .state = ARM_CP_STATE_AA64,
7127       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 5,
7128       .type = ARM_CP_NOP, .access = PL0_W,
7129       .accessfn = aa64_cacheop_poc_access },
7130     { .name = "DC_GVA", .state = ARM_CP_STATE_AA64,
7131       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 3,
7132       .access = PL0_W, .type = ARM_CP_DC_GVA,
7133 #ifndef CONFIG_USER_ONLY
7134       /* Avoid overhead of an access check that always passes in user-mode */
7135       .accessfn = aa64_zva_access,
7136 #endif
7137     },
7138     { .name = "DC_GZVA", .state = ARM_CP_STATE_AA64,
7139       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 4,
7140       .access = PL0_W, .type = ARM_CP_DC_GZVA,
7141 #ifndef CONFIG_USER_ONLY
7142       /* Avoid overhead of an access check that always passes in user-mode */
7143       .accessfn = aa64_zva_access,
7144 #endif
7145     },
7146     REGINFO_SENTINEL
7147 };
7148 
7149 #endif
7150 
7151 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
7152                                      bool isread)
7153 {
7154     int el = arm_current_el(env);
7155 
7156     if (el == 0) {
7157         uint64_t sctlr = arm_sctlr(env, el);
7158         if (!(sctlr & SCTLR_EnRCTX)) {
7159             return CP_ACCESS_TRAP;
7160         }
7161     } else if (el == 1) {
7162         uint64_t hcr = arm_hcr_el2_eff(env);
7163         if (hcr & HCR_NV) {
7164             return CP_ACCESS_TRAP_EL2;
7165         }
7166     }
7167     return CP_ACCESS_OK;
7168 }
7169 
7170 static const ARMCPRegInfo predinv_reginfo[] = {
7171     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
7172       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
7173       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7174     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
7175       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
7176       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7177     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
7178       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
7179       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7180     /*
7181      * Note the AArch32 opcodes have a different OPC1.
7182      */
7183     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
7184       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
7185       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7186     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
7187       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
7188       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7189     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
7190       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
7191       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7192     REGINFO_SENTINEL
7193 };
7194 
7195 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
7196 {
7197     /* Read the high 32 bits of the current CCSIDR */
7198     return extract64(ccsidr_read(env, ri), 32, 32);
7199 }
7200 
7201 static const ARMCPRegInfo ccsidr2_reginfo[] = {
7202     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
7203       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
7204       .access = PL1_R,
7205       .accessfn = access_aa64_tid2,
7206       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7207     REGINFO_SENTINEL
7208 };
7209 
7210 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7211                                        bool isread)
7212 {
7213     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7214         return CP_ACCESS_TRAP_EL2;
7215     }
7216 
7217     return CP_ACCESS_OK;
7218 }
7219 
7220 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7221                                        bool isread)
7222 {
7223     if (arm_feature(env, ARM_FEATURE_V8)) {
7224         return access_aa64_tid3(env, ri, isread);
7225     }
7226 
7227     return CP_ACCESS_OK;
7228 }
7229 
7230 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7231                                      bool isread)
7232 {
7233     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7234         return CP_ACCESS_TRAP_EL2;
7235     }
7236 
7237     return CP_ACCESS_OK;
7238 }
7239 
7240 static const ARMCPRegInfo jazelle_regs[] = {
7241     { .name = "JIDR",
7242       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7243       .access = PL1_R, .accessfn = access_jazelle,
7244       .type = ARM_CP_CONST, .resetvalue = 0 },
7245     { .name = "JOSCR",
7246       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7247       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7248     { .name = "JMCR",
7249       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7250       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7251     REGINFO_SENTINEL
7252 };
7253 
7254 static const ARMCPRegInfo vhe_reginfo[] = {
7255     { .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7256       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7257       .access = PL2_RW,
7258       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2]) },
7259     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7260       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7261       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7262       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7263 #ifndef CONFIG_USER_ONLY
7264     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7265       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7266       .fieldoffset =
7267         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7268       .type = ARM_CP_IO, .access = PL2_RW,
7269       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7270     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7271       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7272       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7273       .resetfn = gt_hv_timer_reset,
7274       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7275     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7276       .type = ARM_CP_IO,
7277       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7278       .access = PL2_RW,
7279       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7280       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7281     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7282       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7283       .type = ARM_CP_IO | ARM_CP_ALIAS,
7284       .access = PL2_RW, .accessfn = e2h_access,
7285       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7286       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7287     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7288       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7289       .type = ARM_CP_IO | ARM_CP_ALIAS,
7290       .access = PL2_RW, .accessfn = e2h_access,
7291       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7292       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7293     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7294       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7295       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7296       .access = PL2_RW, .accessfn = e2h_access,
7297       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7298     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7299       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7300       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7301       .access = PL2_RW, .accessfn = e2h_access,
7302       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7303     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7304       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7305       .type = ARM_CP_IO | ARM_CP_ALIAS,
7306       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7307       .access = PL2_RW, .accessfn = e2h_access,
7308       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7309     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7310       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7311       .type = ARM_CP_IO | ARM_CP_ALIAS,
7312       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7313       .access = PL2_RW, .accessfn = e2h_access,
7314       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7315 #endif
7316     REGINFO_SENTINEL
7317 };
7318 
7319 #ifndef CONFIG_USER_ONLY
7320 static const ARMCPRegInfo ats1e1_reginfo[] = {
7321     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7322       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7323       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7324       .writefn = ats_write64 },
7325     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7326       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7327       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7328       .writefn = ats_write64 },
7329     REGINFO_SENTINEL
7330 };
7331 
7332 static const ARMCPRegInfo ats1cp_reginfo[] = {
7333     { .name = "ATS1CPRP",
7334       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7335       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7336       .writefn = ats_write },
7337     { .name = "ATS1CPWP",
7338       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7339       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7340       .writefn = ats_write },
7341     REGINFO_SENTINEL
7342 };
7343 #endif
7344 
7345 /*
7346  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7347  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7348  * is non-zero, which is never for ARMv7, optionally in ARMv8
7349  * and mandatorily for ARMv8.2 and up.
7350  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7351  * implementation is RAZ/WI we can ignore this detail, as we
7352  * do for ACTLR.
7353  */
7354 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7355     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7356       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7357       .access = PL1_RW, .accessfn = access_tacr,
7358       .type = ARM_CP_CONST, .resetvalue = 0 },
7359     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7360       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7361       .access = PL2_RW, .type = ARM_CP_CONST,
7362       .resetvalue = 0 },
7363     REGINFO_SENTINEL
7364 };
7365 
7366 void register_cp_regs_for_features(ARMCPU *cpu)
7367 {
7368     /* Register all the coprocessor registers based on feature bits */
7369     CPUARMState *env = &cpu->env;
7370     if (arm_feature(env, ARM_FEATURE_M)) {
7371         /* M profile has no coprocessor registers */
7372         return;
7373     }
7374 
7375     define_arm_cp_regs(cpu, cp_reginfo);
7376     if (!arm_feature(env, ARM_FEATURE_V8)) {
7377         /* Must go early as it is full of wildcards that may be
7378          * overridden by later definitions.
7379          */
7380         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7381     }
7382 
7383     if (arm_feature(env, ARM_FEATURE_V6)) {
7384         /* The ID registers all have impdef reset values */
7385         ARMCPRegInfo v6_idregs[] = {
7386             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7387               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7388               .access = PL1_R, .type = ARM_CP_CONST,
7389               .accessfn = access_aa32_tid3,
7390               .resetvalue = cpu->isar.id_pfr0 },
7391             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7392              * the value of the GIC field until after we define these regs.
7393              */
7394             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7395               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7396               .access = PL1_R, .type = ARM_CP_NO_RAW,
7397               .accessfn = access_aa32_tid3,
7398               .readfn = id_pfr1_read,
7399               .writefn = arm_cp_write_ignore },
7400             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7401               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7402               .access = PL1_R, .type = ARM_CP_CONST,
7403               .accessfn = access_aa32_tid3,
7404               .resetvalue = cpu->isar.id_dfr0 },
7405             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7406               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7407               .access = PL1_R, .type = ARM_CP_CONST,
7408               .accessfn = access_aa32_tid3,
7409               .resetvalue = cpu->id_afr0 },
7410             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7411               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7412               .access = PL1_R, .type = ARM_CP_CONST,
7413               .accessfn = access_aa32_tid3,
7414               .resetvalue = cpu->isar.id_mmfr0 },
7415             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7416               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7417               .access = PL1_R, .type = ARM_CP_CONST,
7418               .accessfn = access_aa32_tid3,
7419               .resetvalue = cpu->isar.id_mmfr1 },
7420             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7421               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7422               .access = PL1_R, .type = ARM_CP_CONST,
7423               .accessfn = access_aa32_tid3,
7424               .resetvalue = cpu->isar.id_mmfr2 },
7425             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7426               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7427               .access = PL1_R, .type = ARM_CP_CONST,
7428               .accessfn = access_aa32_tid3,
7429               .resetvalue = cpu->isar.id_mmfr3 },
7430             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7431               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7432               .access = PL1_R, .type = ARM_CP_CONST,
7433               .accessfn = access_aa32_tid3,
7434               .resetvalue = cpu->isar.id_isar0 },
7435             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7436               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7437               .access = PL1_R, .type = ARM_CP_CONST,
7438               .accessfn = access_aa32_tid3,
7439               .resetvalue = cpu->isar.id_isar1 },
7440             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7441               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7442               .access = PL1_R, .type = ARM_CP_CONST,
7443               .accessfn = access_aa32_tid3,
7444               .resetvalue = cpu->isar.id_isar2 },
7445             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7446               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7447               .access = PL1_R, .type = ARM_CP_CONST,
7448               .accessfn = access_aa32_tid3,
7449               .resetvalue = cpu->isar.id_isar3 },
7450             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7451               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7452               .access = PL1_R, .type = ARM_CP_CONST,
7453               .accessfn = access_aa32_tid3,
7454               .resetvalue = cpu->isar.id_isar4 },
7455             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7456               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7457               .access = PL1_R, .type = ARM_CP_CONST,
7458               .accessfn = access_aa32_tid3,
7459               .resetvalue = cpu->isar.id_isar5 },
7460             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7461               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7462               .access = PL1_R, .type = ARM_CP_CONST,
7463               .accessfn = access_aa32_tid3,
7464               .resetvalue = cpu->isar.id_mmfr4 },
7465             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7466               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7467               .access = PL1_R, .type = ARM_CP_CONST,
7468               .accessfn = access_aa32_tid3,
7469               .resetvalue = cpu->isar.id_isar6 },
7470             REGINFO_SENTINEL
7471         };
7472         define_arm_cp_regs(cpu, v6_idregs);
7473         define_arm_cp_regs(cpu, v6_cp_reginfo);
7474     } else {
7475         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7476     }
7477     if (arm_feature(env, ARM_FEATURE_V6K)) {
7478         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7479     }
7480     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7481         !arm_feature(env, ARM_FEATURE_PMSA)) {
7482         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7483     }
7484     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7485         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7486     }
7487     if (arm_feature(env, ARM_FEATURE_V7)) {
7488         ARMCPRegInfo clidr = {
7489             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7490             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7491             .access = PL1_R, .type = ARM_CP_CONST,
7492             .accessfn = access_aa64_tid2,
7493             .resetvalue = cpu->clidr
7494         };
7495         define_one_arm_cp_reg(cpu, &clidr);
7496         define_arm_cp_regs(cpu, v7_cp_reginfo);
7497         define_debug_regs(cpu);
7498         define_pmu_regs(cpu);
7499     } else {
7500         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7501     }
7502     if (arm_feature(env, ARM_FEATURE_V8)) {
7503         /* AArch64 ID registers, which all have impdef reset values.
7504          * Note that within the ID register ranges the unused slots
7505          * must all RAZ, not UNDEF; future architecture versions may
7506          * define new registers here.
7507          */
7508         ARMCPRegInfo v8_idregs[] = {
7509             /*
7510              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7511              * emulation because we don't know the right value for the
7512              * GIC field until after we define these regs.
7513              */
7514             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7515               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7516               .access = PL1_R,
7517 #ifdef CONFIG_USER_ONLY
7518               .type = ARM_CP_CONST,
7519               .resetvalue = cpu->isar.id_aa64pfr0
7520 #else
7521               .type = ARM_CP_NO_RAW,
7522               .accessfn = access_aa64_tid3,
7523               .readfn = id_aa64pfr0_read,
7524               .writefn = arm_cp_write_ignore
7525 #endif
7526             },
7527             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7528               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7529               .access = PL1_R, .type = ARM_CP_CONST,
7530               .accessfn = access_aa64_tid3,
7531               .resetvalue = cpu->isar.id_aa64pfr1},
7532             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7533               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7534               .access = PL1_R, .type = ARM_CP_CONST,
7535               .accessfn = access_aa64_tid3,
7536               .resetvalue = 0 },
7537             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7538               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7539               .access = PL1_R, .type = ARM_CP_CONST,
7540               .accessfn = access_aa64_tid3,
7541               .resetvalue = 0 },
7542             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7543               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7544               .access = PL1_R, .type = ARM_CP_CONST,
7545               .accessfn = access_aa64_tid3,
7546               /* At present, only SVEver == 0 is defined anyway.  */
7547               .resetvalue = 0 },
7548             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7549               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7550               .access = PL1_R, .type = ARM_CP_CONST,
7551               .accessfn = access_aa64_tid3,
7552               .resetvalue = 0 },
7553             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7554               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7555               .access = PL1_R, .type = ARM_CP_CONST,
7556               .accessfn = access_aa64_tid3,
7557               .resetvalue = 0 },
7558             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7559               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7560               .access = PL1_R, .type = ARM_CP_CONST,
7561               .accessfn = access_aa64_tid3,
7562               .resetvalue = 0 },
7563             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7564               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7565               .access = PL1_R, .type = ARM_CP_CONST,
7566               .accessfn = access_aa64_tid3,
7567               .resetvalue = cpu->isar.id_aa64dfr0 },
7568             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7569               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7570               .access = PL1_R, .type = ARM_CP_CONST,
7571               .accessfn = access_aa64_tid3,
7572               .resetvalue = cpu->isar.id_aa64dfr1 },
7573             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7574               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7575               .access = PL1_R, .type = ARM_CP_CONST,
7576               .accessfn = access_aa64_tid3,
7577               .resetvalue = 0 },
7578             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7579               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7580               .access = PL1_R, .type = ARM_CP_CONST,
7581               .accessfn = access_aa64_tid3,
7582               .resetvalue = 0 },
7583             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7584               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7585               .access = PL1_R, .type = ARM_CP_CONST,
7586               .accessfn = access_aa64_tid3,
7587               .resetvalue = cpu->id_aa64afr0 },
7588             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7589               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7590               .access = PL1_R, .type = ARM_CP_CONST,
7591               .accessfn = access_aa64_tid3,
7592               .resetvalue = cpu->id_aa64afr1 },
7593             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7594               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7595               .access = PL1_R, .type = ARM_CP_CONST,
7596               .accessfn = access_aa64_tid3,
7597               .resetvalue = 0 },
7598             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7599               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7600               .access = PL1_R, .type = ARM_CP_CONST,
7601               .accessfn = access_aa64_tid3,
7602               .resetvalue = 0 },
7603             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7604               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7605               .access = PL1_R, .type = ARM_CP_CONST,
7606               .accessfn = access_aa64_tid3,
7607               .resetvalue = cpu->isar.id_aa64isar0 },
7608             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7609               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7610               .access = PL1_R, .type = ARM_CP_CONST,
7611               .accessfn = access_aa64_tid3,
7612               .resetvalue = cpu->isar.id_aa64isar1 },
7613             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7614               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7615               .access = PL1_R, .type = ARM_CP_CONST,
7616               .accessfn = access_aa64_tid3,
7617               .resetvalue = 0 },
7618             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7619               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7620               .access = PL1_R, .type = ARM_CP_CONST,
7621               .accessfn = access_aa64_tid3,
7622               .resetvalue = 0 },
7623             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7624               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7625               .access = PL1_R, .type = ARM_CP_CONST,
7626               .accessfn = access_aa64_tid3,
7627               .resetvalue = 0 },
7628             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7629               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7630               .access = PL1_R, .type = ARM_CP_CONST,
7631               .accessfn = access_aa64_tid3,
7632               .resetvalue = 0 },
7633             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7634               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7635               .access = PL1_R, .type = ARM_CP_CONST,
7636               .accessfn = access_aa64_tid3,
7637               .resetvalue = 0 },
7638             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7639               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7640               .access = PL1_R, .type = ARM_CP_CONST,
7641               .accessfn = access_aa64_tid3,
7642               .resetvalue = 0 },
7643             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7644               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7645               .access = PL1_R, .type = ARM_CP_CONST,
7646               .accessfn = access_aa64_tid3,
7647               .resetvalue = cpu->isar.id_aa64mmfr0 },
7648             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7649               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7650               .access = PL1_R, .type = ARM_CP_CONST,
7651               .accessfn = access_aa64_tid3,
7652               .resetvalue = cpu->isar.id_aa64mmfr1 },
7653             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7654               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7655               .access = PL1_R, .type = ARM_CP_CONST,
7656               .accessfn = access_aa64_tid3,
7657               .resetvalue = cpu->isar.id_aa64mmfr2 },
7658             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7659               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7660               .access = PL1_R, .type = ARM_CP_CONST,
7661               .accessfn = access_aa64_tid3,
7662               .resetvalue = 0 },
7663             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7664               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7665               .access = PL1_R, .type = ARM_CP_CONST,
7666               .accessfn = access_aa64_tid3,
7667               .resetvalue = 0 },
7668             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7669               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7670               .access = PL1_R, .type = ARM_CP_CONST,
7671               .accessfn = access_aa64_tid3,
7672               .resetvalue = 0 },
7673             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7674               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7675               .access = PL1_R, .type = ARM_CP_CONST,
7676               .accessfn = access_aa64_tid3,
7677               .resetvalue = 0 },
7678             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7679               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7680               .access = PL1_R, .type = ARM_CP_CONST,
7681               .accessfn = access_aa64_tid3,
7682               .resetvalue = 0 },
7683             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7684               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7685               .access = PL1_R, .type = ARM_CP_CONST,
7686               .accessfn = access_aa64_tid3,
7687               .resetvalue = cpu->isar.mvfr0 },
7688             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7689               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7690               .access = PL1_R, .type = ARM_CP_CONST,
7691               .accessfn = access_aa64_tid3,
7692               .resetvalue = cpu->isar.mvfr1 },
7693             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7694               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7695               .access = PL1_R, .type = ARM_CP_CONST,
7696               .accessfn = access_aa64_tid3,
7697               .resetvalue = cpu->isar.mvfr2 },
7698             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7699               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7700               .access = PL1_R, .type = ARM_CP_CONST,
7701               .accessfn = access_aa64_tid3,
7702               .resetvalue = 0 },
7703             { .name = "ID_PFR2", .state = ARM_CP_STATE_BOTH,
7704               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7705               .access = PL1_R, .type = ARM_CP_CONST,
7706               .accessfn = access_aa64_tid3,
7707               .resetvalue = cpu->isar.id_pfr2 },
7708             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7709               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7710               .access = PL1_R, .type = ARM_CP_CONST,
7711               .accessfn = access_aa64_tid3,
7712               .resetvalue = 0 },
7713             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7714               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7715               .access = PL1_R, .type = ARM_CP_CONST,
7716               .accessfn = access_aa64_tid3,
7717               .resetvalue = 0 },
7718             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7719               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7720               .access = PL1_R, .type = ARM_CP_CONST,
7721               .accessfn = access_aa64_tid3,
7722               .resetvalue = 0 },
7723             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7724               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7725               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7726               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7727             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7728               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7729               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7730               .resetvalue = cpu->pmceid0 },
7731             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7732               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7733               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7734               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7735             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7736               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7737               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7738               .resetvalue = cpu->pmceid1 },
7739             REGINFO_SENTINEL
7740         };
7741 #ifdef CONFIG_USER_ONLY
7742         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7743             { .name = "ID_AA64PFR0_EL1",
7744               .exported_bits = 0x000f000f00ff0000,
7745               .fixed_bits    = 0x0000000000000011 },
7746             { .name = "ID_AA64PFR1_EL1",
7747               .exported_bits = 0x00000000000000f0 },
7748             { .name = "ID_AA64PFR*_EL1_RESERVED",
7749               .is_glob = true                     },
7750             { .name = "ID_AA64ZFR0_EL1"           },
7751             { .name = "ID_AA64MMFR0_EL1",
7752               .fixed_bits    = 0x00000000ff000000 },
7753             { .name = "ID_AA64MMFR1_EL1"          },
7754             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7755               .is_glob = true                     },
7756             { .name = "ID_AA64DFR0_EL1",
7757               .fixed_bits    = 0x0000000000000006 },
7758             { .name = "ID_AA64DFR1_EL1"           },
7759             { .name = "ID_AA64DFR*_EL1_RESERVED",
7760               .is_glob = true                     },
7761             { .name = "ID_AA64AFR*",
7762               .is_glob = true                     },
7763             { .name = "ID_AA64ISAR0_EL1",
7764               .exported_bits = 0x00fffffff0fffff0 },
7765             { .name = "ID_AA64ISAR1_EL1",
7766               .exported_bits = 0x000000f0ffffffff },
7767             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7768               .is_glob = true                     },
7769             REGUSERINFO_SENTINEL
7770         };
7771         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7772 #endif
7773         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7774         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7775             !arm_feature(env, ARM_FEATURE_EL2)) {
7776             ARMCPRegInfo rvbar = {
7777                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7778                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7779                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
7780             };
7781             define_one_arm_cp_reg(cpu, &rvbar);
7782         }
7783         define_arm_cp_regs(cpu, v8_idregs);
7784         define_arm_cp_regs(cpu, v8_cp_reginfo);
7785     }
7786     if (arm_feature(env, ARM_FEATURE_EL2)) {
7787         uint64_t vmpidr_def = mpidr_read_val(env);
7788         ARMCPRegInfo vpidr_regs[] = {
7789             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7790               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7791               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7792               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
7793               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7794             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7795               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7796               .access = PL2_RW, .resetvalue = cpu->midr,
7797               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7798             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7799               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7800               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7801               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
7802               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7803             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7804               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7805               .access = PL2_RW,
7806               .resetvalue = vmpidr_def,
7807               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7808             REGINFO_SENTINEL
7809         };
7810         define_arm_cp_regs(cpu, vpidr_regs);
7811         define_arm_cp_regs(cpu, el2_cp_reginfo);
7812         if (arm_feature(env, ARM_FEATURE_V8)) {
7813             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
7814         }
7815         if (cpu_isar_feature(aa64_sel2, cpu)) {
7816             define_arm_cp_regs(cpu, el2_sec_cp_reginfo);
7817         }
7818         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
7819         if (!arm_feature(env, ARM_FEATURE_EL3)) {
7820             ARMCPRegInfo rvbar = {
7821                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
7822                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
7823                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
7824             };
7825             define_one_arm_cp_reg(cpu, &rvbar);
7826         }
7827     } else {
7828         /* If EL2 is missing but higher ELs are enabled, we need to
7829          * register the no_el2 reginfos.
7830          */
7831         if (arm_feature(env, ARM_FEATURE_EL3)) {
7832             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
7833              * of MIDR_EL1 and MPIDR_EL1.
7834              */
7835             ARMCPRegInfo vpidr_regs[] = {
7836                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7837                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7838                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
7839                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
7840                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7841                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7842                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7843                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
7844                   .type = ARM_CP_NO_RAW,
7845                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
7846                 REGINFO_SENTINEL
7847             };
7848             define_arm_cp_regs(cpu, vpidr_regs);
7849             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
7850             if (arm_feature(env, ARM_FEATURE_V8)) {
7851                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
7852             }
7853         }
7854     }
7855     if (arm_feature(env, ARM_FEATURE_EL3)) {
7856         define_arm_cp_regs(cpu, el3_cp_reginfo);
7857         ARMCPRegInfo el3_regs[] = {
7858             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
7859               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
7860               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
7861             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
7862               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
7863               .access = PL3_RW,
7864               .raw_writefn = raw_write, .writefn = sctlr_write,
7865               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
7866               .resetvalue = cpu->reset_sctlr },
7867             REGINFO_SENTINEL
7868         };
7869 
7870         define_arm_cp_regs(cpu, el3_regs);
7871     }
7872     /* The behaviour of NSACR is sufficiently various that we don't
7873      * try to describe it in a single reginfo:
7874      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
7875      *     reads as constant 0xc00 from NS EL1 and NS EL2
7876      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
7877      *  if v7 without EL3, register doesn't exist
7878      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
7879      */
7880     if (arm_feature(env, ARM_FEATURE_EL3)) {
7881         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7882             ARMCPRegInfo nsacr = {
7883                 .name = "NSACR", .type = ARM_CP_CONST,
7884                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7885                 .access = PL1_RW, .accessfn = nsacr_access,
7886                 .resetvalue = 0xc00
7887             };
7888             define_one_arm_cp_reg(cpu, &nsacr);
7889         } else {
7890             ARMCPRegInfo nsacr = {
7891                 .name = "NSACR",
7892                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7893                 .access = PL3_RW | PL1_R,
7894                 .resetvalue = 0,
7895                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
7896             };
7897             define_one_arm_cp_reg(cpu, &nsacr);
7898         }
7899     } else {
7900         if (arm_feature(env, ARM_FEATURE_V8)) {
7901             ARMCPRegInfo nsacr = {
7902                 .name = "NSACR", .type = ARM_CP_CONST,
7903                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7904                 .access = PL1_R,
7905                 .resetvalue = 0xc00
7906             };
7907             define_one_arm_cp_reg(cpu, &nsacr);
7908         }
7909     }
7910 
7911     if (arm_feature(env, ARM_FEATURE_PMSA)) {
7912         if (arm_feature(env, ARM_FEATURE_V6)) {
7913             /* PMSAv6 not implemented */
7914             assert(arm_feature(env, ARM_FEATURE_V7));
7915             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7916             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
7917         } else {
7918             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
7919         }
7920     } else {
7921         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7922         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
7923         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
7924         if (cpu_isar_feature(aa32_hpd, cpu)) {
7925             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
7926         }
7927     }
7928     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
7929         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
7930     }
7931     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
7932         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
7933     }
7934     if (arm_feature(env, ARM_FEATURE_VAPA)) {
7935         define_arm_cp_regs(cpu, vapa_cp_reginfo);
7936     }
7937     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
7938         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
7939     }
7940     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
7941         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
7942     }
7943     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
7944         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
7945     }
7946     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
7947         define_arm_cp_regs(cpu, omap_cp_reginfo);
7948     }
7949     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
7950         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
7951     }
7952     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
7953         define_arm_cp_regs(cpu, xscale_cp_reginfo);
7954     }
7955     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
7956         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
7957     }
7958     if (arm_feature(env, ARM_FEATURE_LPAE)) {
7959         define_arm_cp_regs(cpu, lpae_cp_reginfo);
7960     }
7961     if (cpu_isar_feature(aa32_jazelle, cpu)) {
7962         define_arm_cp_regs(cpu, jazelle_regs);
7963     }
7964     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
7965      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
7966      * be read-only (ie write causes UNDEF exception).
7967      */
7968     {
7969         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
7970             /* Pre-v8 MIDR space.
7971              * Note that the MIDR isn't a simple constant register because
7972              * of the TI925 behaviour where writes to another register can
7973              * cause the MIDR value to change.
7974              *
7975              * Unimplemented registers in the c15 0 0 0 space default to
7976              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
7977              * and friends override accordingly.
7978              */
7979             { .name = "MIDR",
7980               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
7981               .access = PL1_R, .resetvalue = cpu->midr,
7982               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
7983               .readfn = midr_read,
7984               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7985               .type = ARM_CP_OVERRIDE },
7986             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
7987             { .name = "DUMMY",
7988               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
7989               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7990             { .name = "DUMMY",
7991               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
7992               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7993             { .name = "DUMMY",
7994               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
7995               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7996             { .name = "DUMMY",
7997               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
7998               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7999             { .name = "DUMMY",
8000               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
8001               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8002             REGINFO_SENTINEL
8003         };
8004         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
8005             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
8006               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
8007               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
8008               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8009               .readfn = midr_read },
8010             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
8011             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8012               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8013               .access = PL1_R, .resetvalue = cpu->midr },
8014             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8015               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
8016               .access = PL1_R, .resetvalue = cpu->midr },
8017             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
8018               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
8019               .access = PL1_R,
8020               .accessfn = access_aa64_tid1,
8021               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
8022             REGINFO_SENTINEL
8023         };
8024         ARMCPRegInfo id_cp_reginfo[] = {
8025             /* These are common to v8 and pre-v8 */
8026             { .name = "CTR",
8027               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
8028               .access = PL1_R, .accessfn = ctr_el0_access,
8029               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8030             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
8031               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
8032               .access = PL0_R, .accessfn = ctr_el0_access,
8033               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8034             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
8035             { .name = "TCMTR",
8036               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
8037               .access = PL1_R,
8038               .accessfn = access_aa32_tid1,
8039               .type = ARM_CP_CONST, .resetvalue = 0 },
8040             REGINFO_SENTINEL
8041         };
8042         /* TLBTR is specific to VMSA */
8043         ARMCPRegInfo id_tlbtr_reginfo = {
8044               .name = "TLBTR",
8045               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
8046               .access = PL1_R,
8047               .accessfn = access_aa32_tid1,
8048               .type = ARM_CP_CONST, .resetvalue = 0,
8049         };
8050         /* MPUIR is specific to PMSA V6+ */
8051         ARMCPRegInfo id_mpuir_reginfo = {
8052               .name = "MPUIR",
8053               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8054               .access = PL1_R, .type = ARM_CP_CONST,
8055               .resetvalue = cpu->pmsav7_dregion << 8
8056         };
8057         ARMCPRegInfo crn0_wi_reginfo = {
8058             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
8059             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
8060             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
8061         };
8062 #ifdef CONFIG_USER_ONLY
8063         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
8064             { .name = "MIDR_EL1",
8065               .exported_bits = 0x00000000ffffffff },
8066             { .name = "REVIDR_EL1"                },
8067             REGUSERINFO_SENTINEL
8068         };
8069         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
8070 #endif
8071         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
8072             arm_feature(env, ARM_FEATURE_STRONGARM)) {
8073             ARMCPRegInfo *r;
8074             /* Register the blanket "writes ignored" value first to cover the
8075              * whole space. Then update the specific ID registers to allow write
8076              * access, so that they ignore writes rather than causing them to
8077              * UNDEF.
8078              */
8079             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
8080             for (r = id_pre_v8_midr_cp_reginfo;
8081                  r->type != ARM_CP_SENTINEL; r++) {
8082                 r->access = PL1_RW;
8083             }
8084             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
8085                 r->access = PL1_RW;
8086             }
8087             id_mpuir_reginfo.access = PL1_RW;
8088             id_tlbtr_reginfo.access = PL1_RW;
8089         }
8090         if (arm_feature(env, ARM_FEATURE_V8)) {
8091             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
8092         } else {
8093             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
8094         }
8095         define_arm_cp_regs(cpu, id_cp_reginfo);
8096         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
8097             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
8098         } else if (arm_feature(env, ARM_FEATURE_V7)) {
8099             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
8100         }
8101     }
8102 
8103     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
8104         ARMCPRegInfo mpidr_cp_reginfo[] = {
8105             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
8106               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
8107               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
8108             REGINFO_SENTINEL
8109         };
8110 #ifdef CONFIG_USER_ONLY
8111         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
8112             { .name = "MPIDR_EL1",
8113               .fixed_bits = 0x0000000080000000 },
8114             REGUSERINFO_SENTINEL
8115         };
8116         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
8117 #endif
8118         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
8119     }
8120 
8121     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
8122         ARMCPRegInfo auxcr_reginfo[] = {
8123             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
8124               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
8125               .access = PL1_RW, .accessfn = access_tacr,
8126               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
8127             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
8128               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
8129               .access = PL2_RW, .type = ARM_CP_CONST,
8130               .resetvalue = 0 },
8131             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
8132               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
8133               .access = PL3_RW, .type = ARM_CP_CONST,
8134               .resetvalue = 0 },
8135             REGINFO_SENTINEL
8136         };
8137         define_arm_cp_regs(cpu, auxcr_reginfo);
8138         if (cpu_isar_feature(aa32_ac2, cpu)) {
8139             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
8140         }
8141     }
8142 
8143     if (arm_feature(env, ARM_FEATURE_CBAR)) {
8144         /*
8145          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
8146          * There are two flavours:
8147          *  (1) older 32-bit only cores have a simple 32-bit CBAR
8148          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
8149          *      32-bit register visible to AArch32 at a different encoding
8150          *      to the "flavour 1" register and with the bits rearranged to
8151          *      be able to squash a 64-bit address into the 32-bit view.
8152          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
8153          * in future if we support AArch32-only configs of some of the
8154          * AArch64 cores we might need to add a specific feature flag
8155          * to indicate cores with "flavour 2" CBAR.
8156          */
8157         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8158             /* 32 bit view is [31:18] 0...0 [43:32]. */
8159             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
8160                 | extract64(cpu->reset_cbar, 32, 12);
8161             ARMCPRegInfo cbar_reginfo[] = {
8162                 { .name = "CBAR",
8163                   .type = ARM_CP_CONST,
8164                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
8165                   .access = PL1_R, .resetvalue = cbar32 },
8166                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
8167                   .type = ARM_CP_CONST,
8168                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
8169                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
8170                 REGINFO_SENTINEL
8171             };
8172             /* We don't implement a r/w 64 bit CBAR currently */
8173             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
8174             define_arm_cp_regs(cpu, cbar_reginfo);
8175         } else {
8176             ARMCPRegInfo cbar = {
8177                 .name = "CBAR",
8178                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
8179                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
8180                 .fieldoffset = offsetof(CPUARMState,
8181                                         cp15.c15_config_base_address)
8182             };
8183             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
8184                 cbar.access = PL1_R;
8185                 cbar.fieldoffset = 0;
8186                 cbar.type = ARM_CP_CONST;
8187             }
8188             define_one_arm_cp_reg(cpu, &cbar);
8189         }
8190     }
8191 
8192     if (arm_feature(env, ARM_FEATURE_VBAR)) {
8193         ARMCPRegInfo vbar_cp_reginfo[] = {
8194             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
8195               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
8196               .access = PL1_RW, .writefn = vbar_write,
8197               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
8198                                      offsetof(CPUARMState, cp15.vbar_ns) },
8199               .resetvalue = 0 },
8200             REGINFO_SENTINEL
8201         };
8202         define_arm_cp_regs(cpu, vbar_cp_reginfo);
8203     }
8204 
8205     /* Generic registers whose values depend on the implementation */
8206     {
8207         ARMCPRegInfo sctlr = {
8208             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8209             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8210             .access = PL1_RW, .accessfn = access_tvm_trvm,
8211             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8212                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8213             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8214             .raw_writefn = raw_write,
8215         };
8216         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8217             /* Normally we would always end the TB on an SCTLR write, but Linux
8218              * arch/arm/mach-pxa/sleep.S expects two instructions following
8219              * an MMU enable to execute from cache.  Imitate this behaviour.
8220              */
8221             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8222         }
8223         define_one_arm_cp_reg(cpu, &sctlr);
8224     }
8225 
8226     if (cpu_isar_feature(aa64_lor, cpu)) {
8227         define_arm_cp_regs(cpu, lor_reginfo);
8228     }
8229     if (cpu_isar_feature(aa64_pan, cpu)) {
8230         define_one_arm_cp_reg(cpu, &pan_reginfo);
8231     }
8232 #ifndef CONFIG_USER_ONLY
8233     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8234         define_arm_cp_regs(cpu, ats1e1_reginfo);
8235     }
8236     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8237         define_arm_cp_regs(cpu, ats1cp_reginfo);
8238     }
8239 #endif
8240     if (cpu_isar_feature(aa64_uao, cpu)) {
8241         define_one_arm_cp_reg(cpu, &uao_reginfo);
8242     }
8243 
8244     if (cpu_isar_feature(aa64_dit, cpu)) {
8245         define_one_arm_cp_reg(cpu, &dit_reginfo);
8246     }
8247 
8248     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8249         define_arm_cp_regs(cpu, vhe_reginfo);
8250     }
8251 
8252     if (cpu_isar_feature(aa64_sve, cpu)) {
8253         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
8254         if (arm_feature(env, ARM_FEATURE_EL2)) {
8255             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
8256         } else {
8257             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
8258         }
8259         if (arm_feature(env, ARM_FEATURE_EL3)) {
8260             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
8261         }
8262     }
8263 
8264 #ifdef TARGET_AARCH64
8265     if (cpu_isar_feature(aa64_pauth, cpu)) {
8266         define_arm_cp_regs(cpu, pauth_reginfo);
8267     }
8268     if (cpu_isar_feature(aa64_rndr, cpu)) {
8269         define_arm_cp_regs(cpu, rndr_reginfo);
8270     }
8271 #ifndef CONFIG_USER_ONLY
8272     /* Data Cache clean instructions up to PoP */
8273     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8274         define_one_arm_cp_reg(cpu, dcpop_reg);
8275 
8276         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8277             define_one_arm_cp_reg(cpu, dcpodp_reg);
8278         }
8279     }
8280 #endif /*CONFIG_USER_ONLY*/
8281 
8282     /*
8283      * If full MTE is enabled, add all of the system registers.
8284      * If only "instructions available at EL0" are enabled,
8285      * then define only a RAZ/WI version of PSTATE.TCO.
8286      */
8287     if (cpu_isar_feature(aa64_mte, cpu)) {
8288         define_arm_cp_regs(cpu, mte_reginfo);
8289         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8290     } else if (cpu_isar_feature(aa64_mte_insn_reg, cpu)) {
8291         define_arm_cp_regs(cpu, mte_tco_ro_reginfo);
8292         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8293     }
8294 #endif
8295 
8296     if (cpu_isar_feature(any_predinv, cpu)) {
8297         define_arm_cp_regs(cpu, predinv_reginfo);
8298     }
8299 
8300     if (cpu_isar_feature(any_ccidx, cpu)) {
8301         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8302     }
8303 
8304 #ifndef CONFIG_USER_ONLY
8305     /*
8306      * Register redirections and aliases must be done last,
8307      * after the registers from the other extensions have been defined.
8308      */
8309     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8310         define_arm_vh_e2h_redirects_aliases(cpu);
8311     }
8312 #endif
8313 }
8314 
8315 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
8316 {
8317     CPUState *cs = CPU(cpu);
8318     CPUARMState *env = &cpu->env;
8319 
8320     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8321         /*
8322          * The lower part of each SVE register aliases to the FPU
8323          * registers so we don't need to include both.
8324          */
8325 #ifdef TARGET_AARCH64
8326         if (isar_feature_aa64_sve(&cpu->isar)) {
8327             gdb_register_coprocessor(cs, arm_gdb_get_svereg, arm_gdb_set_svereg,
8328                                      arm_gen_dynamic_svereg_xml(cs, cs->gdb_num_regs),
8329                                      "sve-registers.xml", 0);
8330         } else
8331 #endif
8332         {
8333             gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
8334                                      aarch64_fpu_gdb_set_reg,
8335                                      34, "aarch64-fpu.xml", 0);
8336         }
8337     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
8338         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8339                                  51, "arm-neon.xml", 0);
8340     } else if (cpu_isar_feature(aa32_simd_r32, cpu)) {
8341         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8342                                  35, "arm-vfp3.xml", 0);
8343     } else if (cpu_isar_feature(aa32_vfp_simd, cpu)) {
8344         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8345                                  19, "arm-vfp.xml", 0);
8346     }
8347     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
8348                              arm_gen_dynamic_sysreg_xml(cs, cs->gdb_num_regs),
8349                              "system-registers.xml", 0);
8350 
8351 }
8352 
8353 /* Sort alphabetically by type name, except for "any". */
8354 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8355 {
8356     ObjectClass *class_a = (ObjectClass *)a;
8357     ObjectClass *class_b = (ObjectClass *)b;
8358     const char *name_a, *name_b;
8359 
8360     name_a = object_class_get_name(class_a);
8361     name_b = object_class_get_name(class_b);
8362     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8363         return 1;
8364     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8365         return -1;
8366     } else {
8367         return strcmp(name_a, name_b);
8368     }
8369 }
8370 
8371 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8372 {
8373     ObjectClass *oc = data;
8374     const char *typename;
8375     char *name;
8376 
8377     typename = object_class_get_name(oc);
8378     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8379     qemu_printf("  %s\n", name);
8380     g_free(name);
8381 }
8382 
8383 void arm_cpu_list(void)
8384 {
8385     GSList *list;
8386 
8387     list = object_class_get_list(TYPE_ARM_CPU, false);
8388     list = g_slist_sort(list, arm_cpu_list_compare);
8389     qemu_printf("Available CPUs:\n");
8390     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8391     g_slist_free(list);
8392 }
8393 
8394 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8395 {
8396     ObjectClass *oc = data;
8397     CpuDefinitionInfoList **cpu_list = user_data;
8398     CpuDefinitionInfo *info;
8399     const char *typename;
8400 
8401     typename = object_class_get_name(oc);
8402     info = g_malloc0(sizeof(*info));
8403     info->name = g_strndup(typename,
8404                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8405     info->q_typename = g_strdup(typename);
8406 
8407     QAPI_LIST_PREPEND(*cpu_list, info);
8408 }
8409 
8410 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8411 {
8412     CpuDefinitionInfoList *cpu_list = NULL;
8413     GSList *list;
8414 
8415     list = object_class_get_list(TYPE_ARM_CPU, false);
8416     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8417     g_slist_free(list);
8418 
8419     return cpu_list;
8420 }
8421 
8422 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8423                                    void *opaque, int state, int secstate,
8424                                    int crm, int opc1, int opc2,
8425                                    const char *name)
8426 {
8427     /* Private utility function for define_one_arm_cp_reg_with_opaque():
8428      * add a single reginfo struct to the hash table.
8429      */
8430     uint32_t *key = g_new(uint32_t, 1);
8431     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
8432     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
8433     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
8434 
8435     r2->name = g_strdup(name);
8436     /* Reset the secure state to the specific incoming state.  This is
8437      * necessary as the register may have been defined with both states.
8438      */
8439     r2->secure = secstate;
8440 
8441     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8442         /* Register is banked (using both entries in array).
8443          * Overwriting fieldoffset as the array is only used to define
8444          * banked registers but later only fieldoffset is used.
8445          */
8446         r2->fieldoffset = r->bank_fieldoffsets[ns];
8447     }
8448 
8449     if (state == ARM_CP_STATE_AA32) {
8450         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8451             /* If the register is banked then we don't need to migrate or
8452              * reset the 32-bit instance in certain cases:
8453              *
8454              * 1) If the register has both 32-bit and 64-bit instances then we
8455              *    can count on the 64-bit instance taking care of the
8456              *    non-secure bank.
8457              * 2) If ARMv8 is enabled then we can count on a 64-bit version
8458              *    taking care of the secure bank.  This requires that separate
8459              *    32 and 64-bit definitions are provided.
8460              */
8461             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8462                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
8463                 r2->type |= ARM_CP_ALIAS;
8464             }
8465         } else if ((secstate != r->secure) && !ns) {
8466             /* The register is not banked so we only want to allow migration of
8467              * the non-secure instance.
8468              */
8469             r2->type |= ARM_CP_ALIAS;
8470         }
8471 
8472         if (r->state == ARM_CP_STATE_BOTH) {
8473             /* We assume it is a cp15 register if the .cp field is left unset.
8474              */
8475             if (r2->cp == 0) {
8476                 r2->cp = 15;
8477             }
8478 
8479 #ifdef HOST_WORDS_BIGENDIAN
8480             if (r2->fieldoffset) {
8481                 r2->fieldoffset += sizeof(uint32_t);
8482             }
8483 #endif
8484         }
8485     }
8486     if (state == ARM_CP_STATE_AA64) {
8487         /* To allow abbreviation of ARMCPRegInfo
8488          * definitions, we treat cp == 0 as equivalent to
8489          * the value for "standard guest-visible sysreg".
8490          * STATE_BOTH definitions are also always "standard
8491          * sysreg" in their AArch64 view (the .cp value may
8492          * be non-zero for the benefit of the AArch32 view).
8493          */
8494         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8495             r2->cp = CP_REG_ARM64_SYSREG_CP;
8496         }
8497         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
8498                                   r2->opc0, opc1, opc2);
8499     } else {
8500         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
8501     }
8502     if (opaque) {
8503         r2->opaque = opaque;
8504     }
8505     /* reginfo passed to helpers is correct for the actual access,
8506      * and is never ARM_CP_STATE_BOTH:
8507      */
8508     r2->state = state;
8509     /* Make sure reginfo passed to helpers for wildcarded regs
8510      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
8511      */
8512     r2->crm = crm;
8513     r2->opc1 = opc1;
8514     r2->opc2 = opc2;
8515     /* By convention, for wildcarded registers only the first
8516      * entry is used for migration; the others are marked as
8517      * ALIAS so we don't try to transfer the register
8518      * multiple times. Special registers (ie NOP/WFI) are
8519      * never migratable and not even raw-accessible.
8520      */
8521     if ((r->type & ARM_CP_SPECIAL)) {
8522         r2->type |= ARM_CP_NO_RAW;
8523     }
8524     if (((r->crm == CP_ANY) && crm != 0) ||
8525         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8526         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8527         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8528     }
8529 
8530     /* Check that raw accesses are either forbidden or handled. Note that
8531      * we can't assert this earlier because the setup of fieldoffset for
8532      * banked registers has to be done first.
8533      */
8534     if (!(r2->type & ARM_CP_NO_RAW)) {
8535         assert(!raw_accessors_invalid(r2));
8536     }
8537 
8538     /* Overriding of an existing definition must be explicitly
8539      * requested.
8540      */
8541     if (!(r->type & ARM_CP_OVERRIDE)) {
8542         ARMCPRegInfo *oldreg;
8543         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
8544         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
8545             fprintf(stderr, "Register redefined: cp=%d %d bit "
8546                     "crn=%d crm=%d opc1=%d opc2=%d, "
8547                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
8548                     r2->crn, r2->crm, r2->opc1, r2->opc2,
8549                     oldreg->name, r2->name);
8550             g_assert_not_reached();
8551         }
8552     }
8553     g_hash_table_insert(cpu->cp_regs, key, r2);
8554 }
8555 
8556 
8557 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8558                                        const ARMCPRegInfo *r, void *opaque)
8559 {
8560     /* Define implementations of coprocessor registers.
8561      * We store these in a hashtable because typically
8562      * there are less than 150 registers in a space which
8563      * is 16*16*16*8*8 = 262144 in size.
8564      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8565      * If a register is defined twice then the second definition is
8566      * used, so this can be used to define some generic registers and
8567      * then override them with implementation specific variations.
8568      * At least one of the original and the second definition should
8569      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8570      * against accidental use.
8571      *
8572      * The state field defines whether the register is to be
8573      * visible in the AArch32 or AArch64 execution state. If the
8574      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8575      * reginfo structure for the AArch32 view, which sees the lower
8576      * 32 bits of the 64 bit register.
8577      *
8578      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8579      * be wildcarded. AArch64 registers are always considered to be 64
8580      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8581      * the register, if any.
8582      */
8583     int crm, opc1, opc2, state;
8584     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8585     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8586     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8587     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8588     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8589     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8590     /* 64 bit registers have only CRm and Opc1 fields */
8591     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8592     /* op0 only exists in the AArch64 encodings */
8593     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8594     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8595     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8596     /*
8597      * This API is only for Arm's system coprocessors (14 and 15) or
8598      * (M-profile or v7A-and-earlier only) for implementation defined
8599      * coprocessors in the range 0..7.  Our decode assumes this, since
8600      * 8..13 can be used for other insns including VFP and Neon. See
8601      * valid_cp() in translate.c.  Assert here that we haven't tried
8602      * to use an invalid coprocessor number.
8603      */
8604     switch (r->state) {
8605     case ARM_CP_STATE_BOTH:
8606         /* 0 has a special meaning, but otherwise the same rules as AA32. */
8607         if (r->cp == 0) {
8608             break;
8609         }
8610         /* fall through */
8611     case ARM_CP_STATE_AA32:
8612         if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
8613             !arm_feature(&cpu->env, ARM_FEATURE_M)) {
8614             assert(r->cp >= 14 && r->cp <= 15);
8615         } else {
8616             assert(r->cp < 8 || (r->cp >= 14 && r->cp <= 15));
8617         }
8618         break;
8619     case ARM_CP_STATE_AA64:
8620         assert(r->cp == 0 || r->cp == CP_REG_ARM64_SYSREG_CP);
8621         break;
8622     default:
8623         g_assert_not_reached();
8624     }
8625     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8626      * encodes a minimum access level for the register. We roll this
8627      * runtime check into our general permission check code, so check
8628      * here that the reginfo's specified permissions are strict enough
8629      * to encompass the generic architectural permission check.
8630      */
8631     if (r->state != ARM_CP_STATE_AA32) {
8632         int mask = 0;
8633         switch (r->opc1) {
8634         case 0:
8635             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8636             mask = PL0U_R | PL1_RW;
8637             break;
8638         case 1: case 2:
8639             /* min_EL EL1 */
8640             mask = PL1_RW;
8641             break;
8642         case 3:
8643             /* min_EL EL0 */
8644             mask = PL0_RW;
8645             break;
8646         case 4:
8647         case 5:
8648             /* min_EL EL2 */
8649             mask = PL2_RW;
8650             break;
8651         case 6:
8652             /* min_EL EL3 */
8653             mask = PL3_RW;
8654             break;
8655         case 7:
8656             /* min_EL EL1, secure mode only (we don't check the latter) */
8657             mask = PL1_RW;
8658             break;
8659         default:
8660             /* broken reginfo with out-of-range opc1 */
8661             assert(false);
8662             break;
8663         }
8664         /* assert our permissions are not too lax (stricter is fine) */
8665         assert((r->access & ~mask) == 0);
8666     }
8667 
8668     /* Check that the register definition has enough info to handle
8669      * reads and writes if they are permitted.
8670      */
8671     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
8672         if (r->access & PL3_R) {
8673             assert((r->fieldoffset ||
8674                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8675                    r->readfn);
8676         }
8677         if (r->access & PL3_W) {
8678             assert((r->fieldoffset ||
8679                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8680                    r->writefn);
8681         }
8682     }
8683     /* Bad type field probably means missing sentinel at end of reg list */
8684     assert(cptype_valid(r->type));
8685     for (crm = crmmin; crm <= crmmax; crm++) {
8686         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8687             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8688                 for (state = ARM_CP_STATE_AA32;
8689                      state <= ARM_CP_STATE_AA64; state++) {
8690                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8691                         continue;
8692                     }
8693                     if (state == ARM_CP_STATE_AA32) {
8694                         /* Under AArch32 CP registers can be common
8695                          * (same for secure and non-secure world) or banked.
8696                          */
8697                         char *name;
8698 
8699                         switch (r->secure) {
8700                         case ARM_CP_SECSTATE_S:
8701                         case ARM_CP_SECSTATE_NS:
8702                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8703                                                    r->secure, crm, opc1, opc2,
8704                                                    r->name);
8705                             break;
8706                         default:
8707                             name = g_strdup_printf("%s_S", r->name);
8708                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8709                                                    ARM_CP_SECSTATE_S,
8710                                                    crm, opc1, opc2, name);
8711                             g_free(name);
8712                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8713                                                    ARM_CP_SECSTATE_NS,
8714                                                    crm, opc1, opc2, r->name);
8715                             break;
8716                         }
8717                     } else {
8718                         /* AArch64 registers get mapped to non-secure instance
8719                          * of AArch32 */
8720                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8721                                                ARM_CP_SECSTATE_NS,
8722                                                crm, opc1, opc2, r->name);
8723                     }
8724                 }
8725             }
8726         }
8727     }
8728 }
8729 
8730 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
8731                                     const ARMCPRegInfo *regs, void *opaque)
8732 {
8733     /* Define a whole list of registers */
8734     const ARMCPRegInfo *r;
8735     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8736         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
8737     }
8738 }
8739 
8740 /*
8741  * Modify ARMCPRegInfo for access from userspace.
8742  *
8743  * This is a data driven modification directed by
8744  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8745  * user-space cannot alter any values and dynamic values pertaining to
8746  * execution state are hidden from user space view anyway.
8747  */
8748 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
8749 {
8750     const ARMCPRegUserSpaceInfo *m;
8751     ARMCPRegInfo *r;
8752 
8753     for (m = mods; m->name; m++) {
8754         GPatternSpec *pat = NULL;
8755         if (m->is_glob) {
8756             pat = g_pattern_spec_new(m->name);
8757         }
8758         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8759             if (pat && g_pattern_match_string(pat, r->name)) {
8760                 r->type = ARM_CP_CONST;
8761                 r->access = PL0U_R;
8762                 r->resetvalue = 0;
8763                 /* continue */
8764             } else if (strcmp(r->name, m->name) == 0) {
8765                 r->type = ARM_CP_CONST;
8766                 r->access = PL0U_R;
8767                 r->resetvalue &= m->exported_bits;
8768                 r->resetvalue |= m->fixed_bits;
8769                 break;
8770             }
8771         }
8772         if (pat) {
8773             g_pattern_spec_free(pat);
8774         }
8775     }
8776 }
8777 
8778 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8779 {
8780     return g_hash_table_lookup(cpregs, &encoded_cp);
8781 }
8782 
8783 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8784                          uint64_t value)
8785 {
8786     /* Helper coprocessor write function for write-ignore registers */
8787 }
8788 
8789 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8790 {
8791     /* Helper coprocessor write function for read-as-zero registers */
8792     return 0;
8793 }
8794 
8795 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8796 {
8797     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8798 }
8799 
8800 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8801 {
8802     /* Return true if it is not valid for us to switch to
8803      * this CPU mode (ie all the UNPREDICTABLE cases in
8804      * the ARM ARM CPSRWriteByInstr pseudocode).
8805      */
8806 
8807     /* Changes to or from Hyp via MSR and CPS are illegal. */
8808     if (write_type == CPSRWriteByInstr &&
8809         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8810          mode == ARM_CPU_MODE_HYP)) {
8811         return 1;
8812     }
8813 
8814     switch (mode) {
8815     case ARM_CPU_MODE_USR:
8816         return 0;
8817     case ARM_CPU_MODE_SYS:
8818     case ARM_CPU_MODE_SVC:
8819     case ARM_CPU_MODE_ABT:
8820     case ARM_CPU_MODE_UND:
8821     case ARM_CPU_MODE_IRQ:
8822     case ARM_CPU_MODE_FIQ:
8823         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
8824          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
8825          */
8826         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
8827          * and CPS are treated as illegal mode changes.
8828          */
8829         if (write_type == CPSRWriteByInstr &&
8830             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
8831             (arm_hcr_el2_eff(env) & HCR_TGE)) {
8832             return 1;
8833         }
8834         return 0;
8835     case ARM_CPU_MODE_HYP:
8836         return !arm_is_el2_enabled(env) || arm_current_el(env) < 2;
8837     case ARM_CPU_MODE_MON:
8838         return arm_current_el(env) < 3;
8839     default:
8840         return 1;
8841     }
8842 }
8843 
8844 uint32_t cpsr_read(CPUARMState *env)
8845 {
8846     int ZF;
8847     ZF = (env->ZF == 0);
8848     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
8849         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
8850         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
8851         | ((env->condexec_bits & 0xfc) << 8)
8852         | (env->GE << 16) | (env->daif & CPSR_AIF);
8853 }
8854 
8855 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
8856                 CPSRWriteType write_type)
8857 {
8858     uint32_t changed_daif;
8859 
8860     if (mask & CPSR_NZCV) {
8861         env->ZF = (~val) & CPSR_Z;
8862         env->NF = val;
8863         env->CF = (val >> 29) & 1;
8864         env->VF = (val << 3) & 0x80000000;
8865     }
8866     if (mask & CPSR_Q)
8867         env->QF = ((val & CPSR_Q) != 0);
8868     if (mask & CPSR_T)
8869         env->thumb = ((val & CPSR_T) != 0);
8870     if (mask & CPSR_IT_0_1) {
8871         env->condexec_bits &= ~3;
8872         env->condexec_bits |= (val >> 25) & 3;
8873     }
8874     if (mask & CPSR_IT_2_7) {
8875         env->condexec_bits &= 3;
8876         env->condexec_bits |= (val >> 8) & 0xfc;
8877     }
8878     if (mask & CPSR_GE) {
8879         env->GE = (val >> 16) & 0xf;
8880     }
8881 
8882     /* In a V7 implementation that includes the security extensions but does
8883      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
8884      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
8885      * bits respectively.
8886      *
8887      * In a V8 implementation, it is permitted for privileged software to
8888      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
8889      */
8890     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
8891         arm_feature(env, ARM_FEATURE_EL3) &&
8892         !arm_feature(env, ARM_FEATURE_EL2) &&
8893         !arm_is_secure(env)) {
8894 
8895         changed_daif = (env->daif ^ val) & mask;
8896 
8897         if (changed_daif & CPSR_A) {
8898             /* Check to see if we are allowed to change the masking of async
8899              * abort exceptions from a non-secure state.
8900              */
8901             if (!(env->cp15.scr_el3 & SCR_AW)) {
8902                 qemu_log_mask(LOG_GUEST_ERROR,
8903                               "Ignoring attempt to switch CPSR_A flag from "
8904                               "non-secure world with SCR.AW bit clear\n");
8905                 mask &= ~CPSR_A;
8906             }
8907         }
8908 
8909         if (changed_daif & CPSR_F) {
8910             /* Check to see if we are allowed to change the masking of FIQ
8911              * exceptions from a non-secure state.
8912              */
8913             if (!(env->cp15.scr_el3 & SCR_FW)) {
8914                 qemu_log_mask(LOG_GUEST_ERROR,
8915                               "Ignoring attempt to switch CPSR_F flag from "
8916                               "non-secure world with SCR.FW bit clear\n");
8917                 mask &= ~CPSR_F;
8918             }
8919 
8920             /* Check whether non-maskable FIQ (NMFI) support is enabled.
8921              * If this bit is set software is not allowed to mask
8922              * FIQs, but is allowed to set CPSR_F to 0.
8923              */
8924             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
8925                 (val & CPSR_F)) {
8926                 qemu_log_mask(LOG_GUEST_ERROR,
8927                               "Ignoring attempt to enable CPSR_F flag "
8928                               "(non-maskable FIQ [NMFI] support enabled)\n");
8929                 mask &= ~CPSR_F;
8930             }
8931         }
8932     }
8933 
8934     env->daif &= ~(CPSR_AIF & mask);
8935     env->daif |= val & CPSR_AIF & mask;
8936 
8937     if (write_type != CPSRWriteRaw &&
8938         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
8939         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
8940             /* Note that we can only get here in USR mode if this is a
8941              * gdb stub write; for this case we follow the architectural
8942              * behaviour for guest writes in USR mode of ignoring an attempt
8943              * to switch mode. (Those are caught by translate.c for writes
8944              * triggered by guest instructions.)
8945              */
8946             mask &= ~CPSR_M;
8947         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
8948             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
8949              * v7, and has defined behaviour in v8:
8950              *  + leave CPSR.M untouched
8951              *  + allow changes to the other CPSR fields
8952              *  + set PSTATE.IL
8953              * For user changes via the GDB stub, we don't set PSTATE.IL,
8954              * as this would be unnecessarily harsh for a user error.
8955              */
8956             mask &= ~CPSR_M;
8957             if (write_type != CPSRWriteByGDBStub &&
8958                 arm_feature(env, ARM_FEATURE_V8)) {
8959                 mask |= CPSR_IL;
8960                 val |= CPSR_IL;
8961             }
8962             qemu_log_mask(LOG_GUEST_ERROR,
8963                           "Illegal AArch32 mode switch attempt from %s to %s\n",
8964                           aarch32_mode_name(env->uncached_cpsr),
8965                           aarch32_mode_name(val));
8966         } else {
8967             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
8968                           write_type == CPSRWriteExceptionReturn ?
8969                           "Exception return from AArch32" :
8970                           "AArch32 mode switch from",
8971                           aarch32_mode_name(env->uncached_cpsr),
8972                           aarch32_mode_name(val), env->regs[15]);
8973             switch_mode(env, val & CPSR_M);
8974         }
8975     }
8976     mask &= ~CACHED_CPSR_BITS;
8977     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
8978 }
8979 
8980 /* Sign/zero extend */
8981 uint32_t HELPER(sxtb16)(uint32_t x)
8982 {
8983     uint32_t res;
8984     res = (uint16_t)(int8_t)x;
8985     res |= (uint32_t)(int8_t)(x >> 16) << 16;
8986     return res;
8987 }
8988 
8989 uint32_t HELPER(uxtb16)(uint32_t x)
8990 {
8991     uint32_t res;
8992     res = (uint16_t)(uint8_t)x;
8993     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
8994     return res;
8995 }
8996 
8997 int32_t HELPER(sdiv)(int32_t num, int32_t den)
8998 {
8999     if (den == 0)
9000       return 0;
9001     if (num == INT_MIN && den == -1)
9002       return INT_MIN;
9003     return num / den;
9004 }
9005 
9006 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
9007 {
9008     if (den == 0)
9009       return 0;
9010     return num / den;
9011 }
9012 
9013 uint32_t HELPER(rbit)(uint32_t x)
9014 {
9015     return revbit32(x);
9016 }
9017 
9018 #ifdef CONFIG_USER_ONLY
9019 
9020 static void switch_mode(CPUARMState *env, int mode)
9021 {
9022     ARMCPU *cpu = env_archcpu(env);
9023 
9024     if (mode != ARM_CPU_MODE_USR) {
9025         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
9026     }
9027 }
9028 
9029 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9030                                  uint32_t cur_el, bool secure)
9031 {
9032     return 1;
9033 }
9034 
9035 void aarch64_sync_64_to_32(CPUARMState *env)
9036 {
9037     g_assert_not_reached();
9038 }
9039 
9040 #else
9041 
9042 static void switch_mode(CPUARMState *env, int mode)
9043 {
9044     int old_mode;
9045     int i;
9046 
9047     old_mode = env->uncached_cpsr & CPSR_M;
9048     if (mode == old_mode)
9049         return;
9050 
9051     if (old_mode == ARM_CPU_MODE_FIQ) {
9052         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
9053         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
9054     } else if (mode == ARM_CPU_MODE_FIQ) {
9055         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
9056         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
9057     }
9058 
9059     i = bank_number(old_mode);
9060     env->banked_r13[i] = env->regs[13];
9061     env->banked_spsr[i] = env->spsr;
9062 
9063     i = bank_number(mode);
9064     env->regs[13] = env->banked_r13[i];
9065     env->spsr = env->banked_spsr[i];
9066 
9067     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
9068     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
9069 }
9070 
9071 /* Physical Interrupt Target EL Lookup Table
9072  *
9073  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
9074  *
9075  * The below multi-dimensional table is used for looking up the target
9076  * exception level given numerous condition criteria.  Specifically, the
9077  * target EL is based on SCR and HCR routing controls as well as the
9078  * currently executing EL and secure state.
9079  *
9080  *    Dimensions:
9081  *    target_el_table[2][2][2][2][2][4]
9082  *                    |  |  |  |  |  +--- Current EL
9083  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
9084  *                    |  |  |  +--------- HCR mask override
9085  *                    |  |  +------------ SCR exec state control
9086  *                    |  +--------------- SCR mask override
9087  *                    +------------------ 32-bit(0)/64-bit(1) EL3
9088  *
9089  *    The table values are as such:
9090  *    0-3 = EL0-EL3
9091  *     -1 = Cannot occur
9092  *
9093  * The ARM ARM target EL table includes entries indicating that an "exception
9094  * is not taken".  The two cases where this is applicable are:
9095  *    1) An exception is taken from EL3 but the SCR does not have the exception
9096  *    routed to EL3.
9097  *    2) An exception is taken from EL2 but the HCR does not have the exception
9098  *    routed to EL2.
9099  * In these two cases, the below table contain a target of EL1.  This value is
9100  * returned as it is expected that the consumer of the table data will check
9101  * for "target EL >= current EL" to ensure the exception is not taken.
9102  *
9103  *            SCR     HCR
9104  *         64  EA     AMO                 From
9105  *        BIT IRQ     IMO      Non-secure         Secure
9106  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
9107  */
9108 static const int8_t target_el_table[2][2][2][2][2][4] = {
9109     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9110        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
9111       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9112        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
9113      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9114        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
9115       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9116        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
9117     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
9118        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 2,  2, -1,  1 },},},
9119       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1,  1,  1 },},
9120        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 2,  2,  2,  1 },},},},
9121      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
9122        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
9123       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},
9124        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},},},},
9125 };
9126 
9127 /*
9128  * Determine the target EL for physical exceptions
9129  */
9130 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9131                                  uint32_t cur_el, bool secure)
9132 {
9133     CPUARMState *env = cs->env_ptr;
9134     bool rw;
9135     bool scr;
9136     bool hcr;
9137     int target_el;
9138     /* Is the highest EL AArch64? */
9139     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
9140     uint64_t hcr_el2;
9141 
9142     if (arm_feature(env, ARM_FEATURE_EL3)) {
9143         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
9144     } else {
9145         /* Either EL2 is the highest EL (and so the EL2 register width
9146          * is given by is64); or there is no EL2 or EL3, in which case
9147          * the value of 'rw' does not affect the table lookup anyway.
9148          */
9149         rw = is64;
9150     }
9151 
9152     hcr_el2 = arm_hcr_el2_eff(env);
9153     switch (excp_idx) {
9154     case EXCP_IRQ:
9155         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
9156         hcr = hcr_el2 & HCR_IMO;
9157         break;
9158     case EXCP_FIQ:
9159         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
9160         hcr = hcr_el2 & HCR_FMO;
9161         break;
9162     default:
9163         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
9164         hcr = hcr_el2 & HCR_AMO;
9165         break;
9166     };
9167 
9168     /*
9169      * For these purposes, TGE and AMO/IMO/FMO both force the
9170      * interrupt to EL2.  Fold TGE into the bit extracted above.
9171      */
9172     hcr |= (hcr_el2 & HCR_TGE) != 0;
9173 
9174     /* Perform a table-lookup for the target EL given the current state */
9175     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
9176 
9177     assert(target_el > 0);
9178 
9179     return target_el;
9180 }
9181 
9182 void arm_log_exception(int idx)
9183 {
9184     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9185         const char *exc = NULL;
9186         static const char * const excnames[] = {
9187             [EXCP_UDEF] = "Undefined Instruction",
9188             [EXCP_SWI] = "SVC",
9189             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9190             [EXCP_DATA_ABORT] = "Data Abort",
9191             [EXCP_IRQ] = "IRQ",
9192             [EXCP_FIQ] = "FIQ",
9193             [EXCP_BKPT] = "Breakpoint",
9194             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9195             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9196             [EXCP_HVC] = "Hypervisor Call",
9197             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9198             [EXCP_SMC] = "Secure Monitor Call",
9199             [EXCP_VIRQ] = "Virtual IRQ",
9200             [EXCP_VFIQ] = "Virtual FIQ",
9201             [EXCP_SEMIHOST] = "Semihosting call",
9202             [EXCP_NOCP] = "v7M NOCP UsageFault",
9203             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9204             [EXCP_STKOF] = "v8M STKOF UsageFault",
9205             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9206             [EXCP_LSERR] = "v8M LSERR UsageFault",
9207             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9208         };
9209 
9210         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9211             exc = excnames[idx];
9212         }
9213         if (!exc) {
9214             exc = "unknown";
9215         }
9216         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
9217     }
9218 }
9219 
9220 /*
9221  * Function used to synchronize QEMU's AArch64 register set with AArch32
9222  * register set.  This is necessary when switching between AArch32 and AArch64
9223  * execution state.
9224  */
9225 void aarch64_sync_32_to_64(CPUARMState *env)
9226 {
9227     int i;
9228     uint32_t mode = env->uncached_cpsr & CPSR_M;
9229 
9230     /* We can blanket copy R[0:7] to X[0:7] */
9231     for (i = 0; i < 8; i++) {
9232         env->xregs[i] = env->regs[i];
9233     }
9234 
9235     /*
9236      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9237      * Otherwise, they come from the banked user regs.
9238      */
9239     if (mode == ARM_CPU_MODE_FIQ) {
9240         for (i = 8; i < 13; i++) {
9241             env->xregs[i] = env->usr_regs[i - 8];
9242         }
9243     } else {
9244         for (i = 8; i < 13; i++) {
9245             env->xregs[i] = env->regs[i];
9246         }
9247     }
9248 
9249     /*
9250      * Registers x13-x23 are the various mode SP and FP registers. Registers
9251      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9252      * from the mode banked register.
9253      */
9254     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9255         env->xregs[13] = env->regs[13];
9256         env->xregs[14] = env->regs[14];
9257     } else {
9258         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9259         /* HYP is an exception in that it is copied from r14 */
9260         if (mode == ARM_CPU_MODE_HYP) {
9261             env->xregs[14] = env->regs[14];
9262         } else {
9263             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9264         }
9265     }
9266 
9267     if (mode == ARM_CPU_MODE_HYP) {
9268         env->xregs[15] = env->regs[13];
9269     } else {
9270         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9271     }
9272 
9273     if (mode == ARM_CPU_MODE_IRQ) {
9274         env->xregs[16] = env->regs[14];
9275         env->xregs[17] = env->regs[13];
9276     } else {
9277         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9278         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9279     }
9280 
9281     if (mode == ARM_CPU_MODE_SVC) {
9282         env->xregs[18] = env->regs[14];
9283         env->xregs[19] = env->regs[13];
9284     } else {
9285         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9286         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9287     }
9288 
9289     if (mode == ARM_CPU_MODE_ABT) {
9290         env->xregs[20] = env->regs[14];
9291         env->xregs[21] = env->regs[13];
9292     } else {
9293         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9294         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9295     }
9296 
9297     if (mode == ARM_CPU_MODE_UND) {
9298         env->xregs[22] = env->regs[14];
9299         env->xregs[23] = env->regs[13];
9300     } else {
9301         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9302         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9303     }
9304 
9305     /*
9306      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9307      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9308      * FIQ bank for r8-r14.
9309      */
9310     if (mode == ARM_CPU_MODE_FIQ) {
9311         for (i = 24; i < 31; i++) {
9312             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9313         }
9314     } else {
9315         for (i = 24; i < 29; i++) {
9316             env->xregs[i] = env->fiq_regs[i - 24];
9317         }
9318         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9319         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9320     }
9321 
9322     env->pc = env->regs[15];
9323 }
9324 
9325 /*
9326  * Function used to synchronize QEMU's AArch32 register set with AArch64
9327  * register set.  This is necessary when switching between AArch32 and AArch64
9328  * execution state.
9329  */
9330 void aarch64_sync_64_to_32(CPUARMState *env)
9331 {
9332     int i;
9333     uint32_t mode = env->uncached_cpsr & CPSR_M;
9334 
9335     /* We can blanket copy X[0:7] to R[0:7] */
9336     for (i = 0; i < 8; i++) {
9337         env->regs[i] = env->xregs[i];
9338     }
9339 
9340     /*
9341      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9342      * Otherwise, we copy x8-x12 into the banked user regs.
9343      */
9344     if (mode == ARM_CPU_MODE_FIQ) {
9345         for (i = 8; i < 13; i++) {
9346             env->usr_regs[i - 8] = env->xregs[i];
9347         }
9348     } else {
9349         for (i = 8; i < 13; i++) {
9350             env->regs[i] = env->xregs[i];
9351         }
9352     }
9353 
9354     /*
9355      * Registers r13 & r14 depend on the current mode.
9356      * If we are in a given mode, we copy the corresponding x registers to r13
9357      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9358      * for the mode.
9359      */
9360     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9361         env->regs[13] = env->xregs[13];
9362         env->regs[14] = env->xregs[14];
9363     } else {
9364         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9365 
9366         /*
9367          * HYP is an exception in that it does not have its own banked r14 but
9368          * shares the USR r14
9369          */
9370         if (mode == ARM_CPU_MODE_HYP) {
9371             env->regs[14] = env->xregs[14];
9372         } else {
9373             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9374         }
9375     }
9376 
9377     if (mode == ARM_CPU_MODE_HYP) {
9378         env->regs[13] = env->xregs[15];
9379     } else {
9380         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9381     }
9382 
9383     if (mode == ARM_CPU_MODE_IRQ) {
9384         env->regs[14] = env->xregs[16];
9385         env->regs[13] = env->xregs[17];
9386     } else {
9387         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9388         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9389     }
9390 
9391     if (mode == ARM_CPU_MODE_SVC) {
9392         env->regs[14] = env->xregs[18];
9393         env->regs[13] = env->xregs[19];
9394     } else {
9395         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9396         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9397     }
9398 
9399     if (mode == ARM_CPU_MODE_ABT) {
9400         env->regs[14] = env->xregs[20];
9401         env->regs[13] = env->xregs[21];
9402     } else {
9403         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9404         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9405     }
9406 
9407     if (mode == ARM_CPU_MODE_UND) {
9408         env->regs[14] = env->xregs[22];
9409         env->regs[13] = env->xregs[23];
9410     } else {
9411         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9412         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9413     }
9414 
9415     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9416      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9417      * FIQ bank for r8-r14.
9418      */
9419     if (mode == ARM_CPU_MODE_FIQ) {
9420         for (i = 24; i < 31; i++) {
9421             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9422         }
9423     } else {
9424         for (i = 24; i < 29; i++) {
9425             env->fiq_regs[i - 24] = env->xregs[i];
9426         }
9427         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9428         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9429     }
9430 
9431     env->regs[15] = env->pc;
9432 }
9433 
9434 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9435                                    uint32_t mask, uint32_t offset,
9436                                    uint32_t newpc)
9437 {
9438     int new_el;
9439 
9440     /* Change the CPU state so as to actually take the exception. */
9441     switch_mode(env, new_mode);
9442 
9443     /*
9444      * For exceptions taken to AArch32 we must clear the SS bit in both
9445      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9446      */
9447     env->pstate &= ~PSTATE_SS;
9448     env->spsr = cpsr_read(env);
9449     /* Clear IT bits.  */
9450     env->condexec_bits = 0;
9451     /* Switch to the new mode, and to the correct instruction set.  */
9452     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9453 
9454     /* This must be after mode switching. */
9455     new_el = arm_current_el(env);
9456 
9457     /* Set new mode endianness */
9458     env->uncached_cpsr &= ~CPSR_E;
9459     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9460         env->uncached_cpsr |= CPSR_E;
9461     }
9462     /* J and IL must always be cleared for exception entry */
9463     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9464     env->daif |= mask;
9465 
9466     if (new_mode == ARM_CPU_MODE_HYP) {
9467         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9468         env->elr_el[2] = env->regs[15];
9469     } else {
9470         /* CPSR.PAN is normally preserved preserved unless...  */
9471         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9472             switch (new_el) {
9473             case 3:
9474                 if (!arm_is_secure_below_el3(env)) {
9475                     /* ... the target is EL3, from non-secure state.  */
9476                     env->uncached_cpsr &= ~CPSR_PAN;
9477                     break;
9478                 }
9479                 /* ... the target is EL3, from secure state ... */
9480                 /* fall through */
9481             case 1:
9482                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9483                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9484                     env->uncached_cpsr |= CPSR_PAN;
9485                 }
9486                 break;
9487             }
9488         }
9489         /*
9490          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9491          * and we should just guard the thumb mode on V4
9492          */
9493         if (arm_feature(env, ARM_FEATURE_V4T)) {
9494             env->thumb =
9495                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9496         }
9497         env->regs[14] = env->regs[15] + offset;
9498     }
9499     env->regs[15] = newpc;
9500     arm_rebuild_hflags(env);
9501 }
9502 
9503 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9504 {
9505     /*
9506      * Handle exception entry to Hyp mode; this is sufficiently
9507      * different to entry to other AArch32 modes that we handle it
9508      * separately here.
9509      *
9510      * The vector table entry used is always the 0x14 Hyp mode entry point,
9511      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
9512      * The offset applied to the preferred return address is always zero
9513      * (see DDI0487C.a section G1.12.3).
9514      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9515      */
9516     uint32_t addr, mask;
9517     ARMCPU *cpu = ARM_CPU(cs);
9518     CPUARMState *env = &cpu->env;
9519 
9520     switch (cs->exception_index) {
9521     case EXCP_UDEF:
9522         addr = 0x04;
9523         break;
9524     case EXCP_SWI:
9525         addr = 0x14;
9526         break;
9527     case EXCP_BKPT:
9528         /* Fall through to prefetch abort.  */
9529     case EXCP_PREFETCH_ABORT:
9530         env->cp15.ifar_s = env->exception.vaddress;
9531         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9532                       (uint32_t)env->exception.vaddress);
9533         addr = 0x0c;
9534         break;
9535     case EXCP_DATA_ABORT:
9536         env->cp15.dfar_s = env->exception.vaddress;
9537         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9538                       (uint32_t)env->exception.vaddress);
9539         addr = 0x10;
9540         break;
9541     case EXCP_IRQ:
9542         addr = 0x18;
9543         break;
9544     case EXCP_FIQ:
9545         addr = 0x1c;
9546         break;
9547     case EXCP_HVC:
9548         addr = 0x08;
9549         break;
9550     case EXCP_HYP_TRAP:
9551         addr = 0x14;
9552         break;
9553     default:
9554         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9555     }
9556 
9557     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9558         if (!arm_feature(env, ARM_FEATURE_V8)) {
9559             /*
9560              * QEMU syndrome values are v8-style. v7 has the IL bit
9561              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9562              * If this is a v7 CPU, squash the IL bit in those cases.
9563              */
9564             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9565                 (cs->exception_index == EXCP_DATA_ABORT &&
9566                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9567                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9568                 env->exception.syndrome &= ~ARM_EL_IL;
9569             }
9570         }
9571         env->cp15.esr_el[2] = env->exception.syndrome;
9572     }
9573 
9574     if (arm_current_el(env) != 2 && addr < 0x14) {
9575         addr = 0x14;
9576     }
9577 
9578     mask = 0;
9579     if (!(env->cp15.scr_el3 & SCR_EA)) {
9580         mask |= CPSR_A;
9581     }
9582     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9583         mask |= CPSR_I;
9584     }
9585     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9586         mask |= CPSR_F;
9587     }
9588 
9589     addr += env->cp15.hvbar;
9590 
9591     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9592 }
9593 
9594 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9595 {
9596     ARMCPU *cpu = ARM_CPU(cs);
9597     CPUARMState *env = &cpu->env;
9598     uint32_t addr;
9599     uint32_t mask;
9600     int new_mode;
9601     uint32_t offset;
9602     uint32_t moe;
9603 
9604     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9605     switch (syn_get_ec(env->exception.syndrome)) {
9606     case EC_BREAKPOINT:
9607     case EC_BREAKPOINT_SAME_EL:
9608         moe = 1;
9609         break;
9610     case EC_WATCHPOINT:
9611     case EC_WATCHPOINT_SAME_EL:
9612         moe = 10;
9613         break;
9614     case EC_AA32_BKPT:
9615         moe = 3;
9616         break;
9617     case EC_VECTORCATCH:
9618         moe = 5;
9619         break;
9620     default:
9621         moe = 0;
9622         break;
9623     }
9624 
9625     if (moe) {
9626         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9627     }
9628 
9629     if (env->exception.target_el == 2) {
9630         arm_cpu_do_interrupt_aarch32_hyp(cs);
9631         return;
9632     }
9633 
9634     switch (cs->exception_index) {
9635     case EXCP_UDEF:
9636         new_mode = ARM_CPU_MODE_UND;
9637         addr = 0x04;
9638         mask = CPSR_I;
9639         if (env->thumb)
9640             offset = 2;
9641         else
9642             offset = 4;
9643         break;
9644     case EXCP_SWI:
9645         new_mode = ARM_CPU_MODE_SVC;
9646         addr = 0x08;
9647         mask = CPSR_I;
9648         /* The PC already points to the next instruction.  */
9649         offset = 0;
9650         break;
9651     case EXCP_BKPT:
9652         /* Fall through to prefetch abort.  */
9653     case EXCP_PREFETCH_ABORT:
9654         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9655         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9656         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9657                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9658         new_mode = ARM_CPU_MODE_ABT;
9659         addr = 0x0c;
9660         mask = CPSR_A | CPSR_I;
9661         offset = 4;
9662         break;
9663     case EXCP_DATA_ABORT:
9664         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9665         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9666         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9667                       env->exception.fsr,
9668                       (uint32_t)env->exception.vaddress);
9669         new_mode = ARM_CPU_MODE_ABT;
9670         addr = 0x10;
9671         mask = CPSR_A | CPSR_I;
9672         offset = 8;
9673         break;
9674     case EXCP_IRQ:
9675         new_mode = ARM_CPU_MODE_IRQ;
9676         addr = 0x18;
9677         /* Disable IRQ and imprecise data aborts.  */
9678         mask = CPSR_A | CPSR_I;
9679         offset = 4;
9680         if (env->cp15.scr_el3 & SCR_IRQ) {
9681             /* IRQ routed to monitor mode */
9682             new_mode = ARM_CPU_MODE_MON;
9683             mask |= CPSR_F;
9684         }
9685         break;
9686     case EXCP_FIQ:
9687         new_mode = ARM_CPU_MODE_FIQ;
9688         addr = 0x1c;
9689         /* Disable FIQ, IRQ and imprecise data aborts.  */
9690         mask = CPSR_A | CPSR_I | CPSR_F;
9691         if (env->cp15.scr_el3 & SCR_FIQ) {
9692             /* FIQ routed to monitor mode */
9693             new_mode = ARM_CPU_MODE_MON;
9694         }
9695         offset = 4;
9696         break;
9697     case EXCP_VIRQ:
9698         new_mode = ARM_CPU_MODE_IRQ;
9699         addr = 0x18;
9700         /* Disable IRQ and imprecise data aborts.  */
9701         mask = CPSR_A | CPSR_I;
9702         offset = 4;
9703         break;
9704     case EXCP_VFIQ:
9705         new_mode = ARM_CPU_MODE_FIQ;
9706         addr = 0x1c;
9707         /* Disable FIQ, IRQ and imprecise data aborts.  */
9708         mask = CPSR_A | CPSR_I | CPSR_F;
9709         offset = 4;
9710         break;
9711     case EXCP_SMC:
9712         new_mode = ARM_CPU_MODE_MON;
9713         addr = 0x08;
9714         mask = CPSR_A | CPSR_I | CPSR_F;
9715         offset = 0;
9716         break;
9717     default:
9718         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9719         return; /* Never happens.  Keep compiler happy.  */
9720     }
9721 
9722     if (new_mode == ARM_CPU_MODE_MON) {
9723         addr += env->cp15.mvbar;
9724     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9725         /* High vectors. When enabled, base address cannot be remapped. */
9726         addr += 0xffff0000;
9727     } else {
9728         /* ARM v7 architectures provide a vector base address register to remap
9729          * the interrupt vector table.
9730          * This register is only followed in non-monitor mode, and is banked.
9731          * Note: only bits 31:5 are valid.
9732          */
9733         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9734     }
9735 
9736     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9737         env->cp15.scr_el3 &= ~SCR_NS;
9738     }
9739 
9740     take_aarch32_exception(env, new_mode, mask, offset, addr);
9741 }
9742 
9743 static int aarch64_regnum(CPUARMState *env, int aarch32_reg)
9744 {
9745     /*
9746      * Return the register number of the AArch64 view of the AArch32
9747      * register @aarch32_reg. The CPUARMState CPSR is assumed to still
9748      * be that of the AArch32 mode the exception came from.
9749      */
9750     int mode = env->uncached_cpsr & CPSR_M;
9751 
9752     switch (aarch32_reg) {
9753     case 0 ... 7:
9754         return aarch32_reg;
9755     case 8 ... 12:
9756         return mode == ARM_CPU_MODE_FIQ ? aarch32_reg + 16 : aarch32_reg;
9757     case 13:
9758         switch (mode) {
9759         case ARM_CPU_MODE_USR:
9760         case ARM_CPU_MODE_SYS:
9761             return 13;
9762         case ARM_CPU_MODE_HYP:
9763             return 15;
9764         case ARM_CPU_MODE_IRQ:
9765             return 17;
9766         case ARM_CPU_MODE_SVC:
9767             return 19;
9768         case ARM_CPU_MODE_ABT:
9769             return 21;
9770         case ARM_CPU_MODE_UND:
9771             return 23;
9772         case ARM_CPU_MODE_FIQ:
9773             return 29;
9774         default:
9775             g_assert_not_reached();
9776         }
9777     case 14:
9778         switch (mode) {
9779         case ARM_CPU_MODE_USR:
9780         case ARM_CPU_MODE_SYS:
9781         case ARM_CPU_MODE_HYP:
9782             return 14;
9783         case ARM_CPU_MODE_IRQ:
9784             return 16;
9785         case ARM_CPU_MODE_SVC:
9786             return 18;
9787         case ARM_CPU_MODE_ABT:
9788             return 20;
9789         case ARM_CPU_MODE_UND:
9790             return 22;
9791         case ARM_CPU_MODE_FIQ:
9792             return 30;
9793         default:
9794             g_assert_not_reached();
9795         }
9796     case 15:
9797         return 31;
9798     default:
9799         g_assert_not_reached();
9800     }
9801 }
9802 
9803 static uint32_t cpsr_read_for_spsr_elx(CPUARMState *env)
9804 {
9805     uint32_t ret = cpsr_read(env);
9806 
9807     /* Move DIT to the correct location for SPSR_ELx */
9808     if (ret & CPSR_DIT) {
9809         ret &= ~CPSR_DIT;
9810         ret |= PSTATE_DIT;
9811     }
9812     /* Merge PSTATE.SS into SPSR_ELx */
9813     ret |= env->pstate & PSTATE_SS;
9814 
9815     return ret;
9816 }
9817 
9818 /* Handle exception entry to a target EL which is using AArch64 */
9819 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
9820 {
9821     ARMCPU *cpu = ARM_CPU(cs);
9822     CPUARMState *env = &cpu->env;
9823     unsigned int new_el = env->exception.target_el;
9824     target_ulong addr = env->cp15.vbar_el[new_el];
9825     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
9826     unsigned int old_mode;
9827     unsigned int cur_el = arm_current_el(env);
9828     int rt;
9829 
9830     /*
9831      * Note that new_el can never be 0.  If cur_el is 0, then
9832      * el0_a64 is is_a64(), else el0_a64 is ignored.
9833      */
9834     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
9835 
9836     if (cur_el < new_el) {
9837         /* Entry vector offset depends on whether the implemented EL
9838          * immediately lower than the target level is using AArch32 or AArch64
9839          */
9840         bool is_aa64;
9841         uint64_t hcr;
9842 
9843         switch (new_el) {
9844         case 3:
9845             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
9846             break;
9847         case 2:
9848             hcr = arm_hcr_el2_eff(env);
9849             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
9850                 is_aa64 = (hcr & HCR_RW) != 0;
9851                 break;
9852             }
9853             /* fall through */
9854         case 1:
9855             is_aa64 = is_a64(env);
9856             break;
9857         default:
9858             g_assert_not_reached();
9859         }
9860 
9861         if (is_aa64) {
9862             addr += 0x400;
9863         } else {
9864             addr += 0x600;
9865         }
9866     } else if (pstate_read(env) & PSTATE_SP) {
9867         addr += 0x200;
9868     }
9869 
9870     switch (cs->exception_index) {
9871     case EXCP_PREFETCH_ABORT:
9872     case EXCP_DATA_ABORT:
9873         env->cp15.far_el[new_el] = env->exception.vaddress;
9874         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
9875                       env->cp15.far_el[new_el]);
9876         /* fall through */
9877     case EXCP_BKPT:
9878     case EXCP_UDEF:
9879     case EXCP_SWI:
9880     case EXCP_HVC:
9881     case EXCP_HYP_TRAP:
9882     case EXCP_SMC:
9883         switch (syn_get_ec(env->exception.syndrome)) {
9884         case EC_ADVSIMDFPACCESSTRAP:
9885             /*
9886              * QEMU internal FP/SIMD syndromes from AArch32 include the
9887              * TA and coproc fields which are only exposed if the exception
9888              * is taken to AArch32 Hyp mode. Mask them out to get a valid
9889              * AArch64 format syndrome.
9890              */
9891             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
9892             break;
9893         case EC_CP14RTTRAP:
9894         case EC_CP15RTTRAP:
9895         case EC_CP14DTTRAP:
9896             /*
9897              * For a trap on AArch32 MRC/MCR/LDC/STC the Rt field is currently
9898              * the raw register field from the insn; when taking this to
9899              * AArch64 we must convert it to the AArch64 view of the register
9900              * number. Notice that we read a 4-bit AArch32 register number and
9901              * write back a 5-bit AArch64 one.
9902              */
9903             rt = extract32(env->exception.syndrome, 5, 4);
9904             rt = aarch64_regnum(env, rt);
9905             env->exception.syndrome = deposit32(env->exception.syndrome,
9906                                                 5, 5, rt);
9907             break;
9908         case EC_CP15RRTTRAP:
9909         case EC_CP14RRTTRAP:
9910             /* Similarly for MRRC/MCRR traps for Rt and Rt2 fields */
9911             rt = extract32(env->exception.syndrome, 5, 4);
9912             rt = aarch64_regnum(env, rt);
9913             env->exception.syndrome = deposit32(env->exception.syndrome,
9914                                                 5, 5, rt);
9915             rt = extract32(env->exception.syndrome, 10, 4);
9916             rt = aarch64_regnum(env, rt);
9917             env->exception.syndrome = deposit32(env->exception.syndrome,
9918                                                 10, 5, rt);
9919             break;
9920         }
9921         env->cp15.esr_el[new_el] = env->exception.syndrome;
9922         break;
9923     case EXCP_IRQ:
9924     case EXCP_VIRQ:
9925         addr += 0x80;
9926         break;
9927     case EXCP_FIQ:
9928     case EXCP_VFIQ:
9929         addr += 0x100;
9930         break;
9931     default:
9932         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9933     }
9934 
9935     if (is_a64(env)) {
9936         old_mode = pstate_read(env);
9937         aarch64_save_sp(env, arm_current_el(env));
9938         env->elr_el[new_el] = env->pc;
9939     } else {
9940         old_mode = cpsr_read_for_spsr_elx(env);
9941         env->elr_el[new_el] = env->regs[15];
9942 
9943         aarch64_sync_32_to_64(env);
9944 
9945         env->condexec_bits = 0;
9946     }
9947     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
9948 
9949     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
9950                   env->elr_el[new_el]);
9951 
9952     if (cpu_isar_feature(aa64_pan, cpu)) {
9953         /* The value of PSTATE.PAN is normally preserved, except when ... */
9954         new_mode |= old_mode & PSTATE_PAN;
9955         switch (new_el) {
9956         case 2:
9957             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
9958             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
9959                 != (HCR_E2H | HCR_TGE)) {
9960                 break;
9961             }
9962             /* fall through */
9963         case 1:
9964             /* ... the target is EL1 ... */
9965             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
9966             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
9967                 new_mode |= PSTATE_PAN;
9968             }
9969             break;
9970         }
9971     }
9972     if (cpu_isar_feature(aa64_mte, cpu)) {
9973         new_mode |= PSTATE_TCO;
9974     }
9975 
9976     pstate_write(env, PSTATE_DAIF | new_mode);
9977     env->aarch64 = 1;
9978     aarch64_restore_sp(env, new_el);
9979     helper_rebuild_hflags_a64(env, new_el);
9980 
9981     env->pc = addr;
9982 
9983     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
9984                   new_el, env->pc, pstate_read(env));
9985 }
9986 
9987 /*
9988  * Do semihosting call and set the appropriate return value. All the
9989  * permission and validity checks have been done at translate time.
9990  *
9991  * We only see semihosting exceptions in TCG only as they are not
9992  * trapped to the hypervisor in KVM.
9993  */
9994 #ifdef CONFIG_TCG
9995 static void handle_semihosting(CPUState *cs)
9996 {
9997     ARMCPU *cpu = ARM_CPU(cs);
9998     CPUARMState *env = &cpu->env;
9999 
10000     if (is_a64(env)) {
10001         qemu_log_mask(CPU_LOG_INT,
10002                       "...handling as semihosting call 0x%" PRIx64 "\n",
10003                       env->xregs[0]);
10004         env->xregs[0] = do_common_semihosting(cs);
10005         env->pc += 4;
10006     } else {
10007         qemu_log_mask(CPU_LOG_INT,
10008                       "...handling as semihosting call 0x%x\n",
10009                       env->regs[0]);
10010         env->regs[0] = do_common_semihosting(cs);
10011         env->regs[15] += env->thumb ? 2 : 4;
10012     }
10013 }
10014 #endif
10015 
10016 /* Handle a CPU exception for A and R profile CPUs.
10017  * Do any appropriate logging, handle PSCI calls, and then hand off
10018  * to the AArch64-entry or AArch32-entry function depending on the
10019  * target exception level's register width.
10020  *
10021  * Note: this is used for both TCG (as the do_interrupt tcg op),
10022  *       and KVM to re-inject guest debug exceptions, and to
10023  *       inject a Synchronous-External-Abort.
10024  */
10025 void arm_cpu_do_interrupt(CPUState *cs)
10026 {
10027     ARMCPU *cpu = ARM_CPU(cs);
10028     CPUARMState *env = &cpu->env;
10029     unsigned int new_el = env->exception.target_el;
10030 
10031     assert(!arm_feature(env, ARM_FEATURE_M));
10032 
10033     arm_log_exception(cs->exception_index);
10034     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10035                   new_el);
10036     if (qemu_loglevel_mask(CPU_LOG_INT)
10037         && !excp_is_internal(cs->exception_index)) {
10038         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10039                       syn_get_ec(env->exception.syndrome),
10040                       env->exception.syndrome);
10041     }
10042 
10043     if (arm_is_psci_call(cpu, cs->exception_index)) {
10044         arm_handle_psci_call(cpu);
10045         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10046         return;
10047     }
10048 
10049     /*
10050      * Semihosting semantics depend on the register width of the code
10051      * that caused the exception, not the target exception level, so
10052      * must be handled here.
10053      */
10054 #ifdef CONFIG_TCG
10055     if (cs->exception_index == EXCP_SEMIHOST) {
10056         handle_semihosting(cs);
10057         return;
10058     }
10059 #endif
10060 
10061     /* Hooks may change global state so BQL should be held, also the
10062      * BQL needs to be held for any modification of
10063      * cs->interrupt_request.
10064      */
10065     g_assert(qemu_mutex_iothread_locked());
10066 
10067     arm_call_pre_el_change_hook(cpu);
10068 
10069     assert(!excp_is_internal(cs->exception_index));
10070     if (arm_el_is_aa64(env, new_el)) {
10071         arm_cpu_do_interrupt_aarch64(cs);
10072     } else {
10073         arm_cpu_do_interrupt_aarch32(cs);
10074     }
10075 
10076     arm_call_el_change_hook(cpu);
10077 
10078     if (!kvm_enabled()) {
10079         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10080     }
10081 }
10082 #endif /* !CONFIG_USER_ONLY */
10083 
10084 uint64_t arm_sctlr(CPUARMState *env, int el)
10085 {
10086     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
10087     if (el == 0) {
10088         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
10089         el = (mmu_idx == ARMMMUIdx_E20_0 || mmu_idx == ARMMMUIdx_SE20_0)
10090              ? 2 : 1;
10091     }
10092     return env->cp15.sctlr_el[el];
10093 }
10094 
10095 /* Return the SCTLR value which controls this address translation regime */
10096 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10097 {
10098     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10099 }
10100 
10101 #ifndef CONFIG_USER_ONLY
10102 
10103 /* Return true if the specified stage of address translation is disabled */
10104 static inline bool regime_translation_disabled(CPUARMState *env,
10105                                                ARMMMUIdx mmu_idx)
10106 {
10107     uint64_t hcr_el2;
10108 
10109     if (arm_feature(env, ARM_FEATURE_M)) {
10110         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10111                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10112         case R_V7M_MPU_CTRL_ENABLE_MASK:
10113             /* Enabled, but not for HardFault and NMI */
10114             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10115         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10116             /* Enabled for all cases */
10117             return false;
10118         case 0:
10119         default:
10120             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10121              * we warned about that in armv7m_nvic.c when the guest set it.
10122              */
10123             return true;
10124         }
10125     }
10126 
10127     hcr_el2 = arm_hcr_el2_eff(env);
10128 
10129     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10130         /* HCR.DC means HCR.VM behaves as 1 */
10131         return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10132     }
10133 
10134     if (hcr_el2 & HCR_TGE) {
10135         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10136         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10137             return true;
10138         }
10139     }
10140 
10141     if ((hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
10142         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10143         return true;
10144     }
10145 
10146     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10147 }
10148 
10149 static inline bool regime_translation_big_endian(CPUARMState *env,
10150                                                  ARMMMUIdx mmu_idx)
10151 {
10152     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10153 }
10154 
10155 /* Return the TTBR associated with this translation regime */
10156 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10157                                    int ttbrn)
10158 {
10159     if (mmu_idx == ARMMMUIdx_Stage2) {
10160         return env->cp15.vttbr_el2;
10161     }
10162     if (mmu_idx == ARMMMUIdx_Stage2_S) {
10163         return env->cp15.vsttbr_el2;
10164     }
10165     if (ttbrn == 0) {
10166         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10167     } else {
10168         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10169     }
10170 }
10171 
10172 #endif /* !CONFIG_USER_ONLY */
10173 
10174 /* Convert a possible stage1+2 MMU index into the appropriate
10175  * stage 1 MMU index
10176  */
10177 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10178 {
10179     switch (mmu_idx) {
10180     case ARMMMUIdx_SE10_0:
10181         return ARMMMUIdx_Stage1_SE0;
10182     case ARMMMUIdx_SE10_1:
10183         return ARMMMUIdx_Stage1_SE1;
10184     case ARMMMUIdx_SE10_1_PAN:
10185         return ARMMMUIdx_Stage1_SE1_PAN;
10186     case ARMMMUIdx_E10_0:
10187         return ARMMMUIdx_Stage1_E0;
10188     case ARMMMUIdx_E10_1:
10189         return ARMMMUIdx_Stage1_E1;
10190     case ARMMMUIdx_E10_1_PAN:
10191         return ARMMMUIdx_Stage1_E1_PAN;
10192     default:
10193         return mmu_idx;
10194     }
10195 }
10196 
10197 /* Return true if the translation regime is using LPAE format page tables */
10198 static inline bool regime_using_lpae_format(CPUARMState *env,
10199                                             ARMMMUIdx mmu_idx)
10200 {
10201     int el = regime_el(env, mmu_idx);
10202     if (el == 2 || arm_el_is_aa64(env, el)) {
10203         return true;
10204     }
10205     if (arm_feature(env, ARM_FEATURE_LPAE)
10206         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10207         return true;
10208     }
10209     return false;
10210 }
10211 
10212 /* Returns true if the stage 1 translation regime is using LPAE format page
10213  * tables. Used when raising alignment exceptions, whose FSR changes depending
10214  * on whether the long or short descriptor format is in use. */
10215 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10216 {
10217     mmu_idx = stage_1_mmu_idx(mmu_idx);
10218 
10219     return regime_using_lpae_format(env, mmu_idx);
10220 }
10221 
10222 #ifndef CONFIG_USER_ONLY
10223 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10224 {
10225     switch (mmu_idx) {
10226     case ARMMMUIdx_SE10_0:
10227     case ARMMMUIdx_E20_0:
10228     case ARMMMUIdx_SE20_0:
10229     case ARMMMUIdx_Stage1_E0:
10230     case ARMMMUIdx_Stage1_SE0:
10231     case ARMMMUIdx_MUser:
10232     case ARMMMUIdx_MSUser:
10233     case ARMMMUIdx_MUserNegPri:
10234     case ARMMMUIdx_MSUserNegPri:
10235         return true;
10236     default:
10237         return false;
10238     case ARMMMUIdx_E10_0:
10239     case ARMMMUIdx_E10_1:
10240     case ARMMMUIdx_E10_1_PAN:
10241         g_assert_not_reached();
10242     }
10243 }
10244 
10245 /* Translate section/page access permissions to page
10246  * R/W protection flags
10247  *
10248  * @env:         CPUARMState
10249  * @mmu_idx:     MMU index indicating required translation regime
10250  * @ap:          The 3-bit access permissions (AP[2:0])
10251  * @domain_prot: The 2-bit domain access permissions
10252  */
10253 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10254                                 int ap, int domain_prot)
10255 {
10256     bool is_user = regime_is_user(env, mmu_idx);
10257 
10258     if (domain_prot == 3) {
10259         return PAGE_READ | PAGE_WRITE;
10260     }
10261 
10262     switch (ap) {
10263     case 0:
10264         if (arm_feature(env, ARM_FEATURE_V7)) {
10265             return 0;
10266         }
10267         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10268         case SCTLR_S:
10269             return is_user ? 0 : PAGE_READ;
10270         case SCTLR_R:
10271             return PAGE_READ;
10272         default:
10273             return 0;
10274         }
10275     case 1:
10276         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10277     case 2:
10278         if (is_user) {
10279             return PAGE_READ;
10280         } else {
10281             return PAGE_READ | PAGE_WRITE;
10282         }
10283     case 3:
10284         return PAGE_READ | PAGE_WRITE;
10285     case 4: /* Reserved.  */
10286         return 0;
10287     case 5:
10288         return is_user ? 0 : PAGE_READ;
10289     case 6:
10290         return PAGE_READ;
10291     case 7:
10292         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10293             return 0;
10294         }
10295         return PAGE_READ;
10296     default:
10297         g_assert_not_reached();
10298     }
10299 }
10300 
10301 /* Translate section/page access permissions to page
10302  * R/W protection flags.
10303  *
10304  * @ap:      The 2-bit simple AP (AP[2:1])
10305  * @is_user: TRUE if accessing from PL0
10306  */
10307 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10308 {
10309     switch (ap) {
10310     case 0:
10311         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10312     case 1:
10313         return PAGE_READ | PAGE_WRITE;
10314     case 2:
10315         return is_user ? 0 : PAGE_READ;
10316     case 3:
10317         return PAGE_READ;
10318     default:
10319         g_assert_not_reached();
10320     }
10321 }
10322 
10323 static inline int
10324 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10325 {
10326     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10327 }
10328 
10329 /* Translate S2 section/page access permissions to protection flags
10330  *
10331  * @env:     CPUARMState
10332  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10333  * @xn:      XN (execute-never) bits
10334  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
10335  */
10336 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
10337 {
10338     int prot = 0;
10339 
10340     if (s2ap & 1) {
10341         prot |= PAGE_READ;
10342     }
10343     if (s2ap & 2) {
10344         prot |= PAGE_WRITE;
10345     }
10346 
10347     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
10348         switch (xn) {
10349         case 0:
10350             prot |= PAGE_EXEC;
10351             break;
10352         case 1:
10353             if (s1_is_el0) {
10354                 prot |= PAGE_EXEC;
10355             }
10356             break;
10357         case 2:
10358             break;
10359         case 3:
10360             if (!s1_is_el0) {
10361                 prot |= PAGE_EXEC;
10362             }
10363             break;
10364         default:
10365             g_assert_not_reached();
10366         }
10367     } else {
10368         if (!extract32(xn, 1, 1)) {
10369             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10370                 prot |= PAGE_EXEC;
10371             }
10372         }
10373     }
10374     return prot;
10375 }
10376 
10377 /* Translate section/page access permissions to protection flags
10378  *
10379  * @env:     CPUARMState
10380  * @mmu_idx: MMU index indicating required translation regime
10381  * @is_aa64: TRUE if AArch64
10382  * @ap:      The 2-bit simple AP (AP[2:1])
10383  * @ns:      NS (non-secure) bit
10384  * @xn:      XN (execute-never) bit
10385  * @pxn:     PXN (privileged execute-never) bit
10386  */
10387 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10388                       int ap, int ns, int xn, int pxn)
10389 {
10390     bool is_user = regime_is_user(env, mmu_idx);
10391     int prot_rw, user_rw;
10392     bool have_wxn;
10393     int wxn = 0;
10394 
10395     assert(mmu_idx != ARMMMUIdx_Stage2);
10396     assert(mmu_idx != ARMMMUIdx_Stage2_S);
10397 
10398     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10399     if (is_user) {
10400         prot_rw = user_rw;
10401     } else {
10402         if (user_rw && regime_is_pan(env, mmu_idx)) {
10403             /* PAN forbids data accesses but doesn't affect insn fetch */
10404             prot_rw = 0;
10405         } else {
10406             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10407         }
10408     }
10409 
10410     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10411         return prot_rw;
10412     }
10413 
10414     /* TODO have_wxn should be replaced with
10415      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10416      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10417      * compatible processors have EL2, which is required for [U]WXN.
10418      */
10419     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10420 
10421     if (have_wxn) {
10422         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10423     }
10424 
10425     if (is_aa64) {
10426         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10427             xn = pxn || (user_rw & PAGE_WRITE);
10428         }
10429     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10430         switch (regime_el(env, mmu_idx)) {
10431         case 1:
10432         case 3:
10433             if (is_user) {
10434                 xn = xn || !(user_rw & PAGE_READ);
10435             } else {
10436                 int uwxn = 0;
10437                 if (have_wxn) {
10438                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10439                 }
10440                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10441                      (uwxn && (user_rw & PAGE_WRITE));
10442             }
10443             break;
10444         case 2:
10445             break;
10446         }
10447     } else {
10448         xn = wxn = 0;
10449     }
10450 
10451     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10452         return prot_rw;
10453     }
10454     return prot_rw | PAGE_EXEC;
10455 }
10456 
10457 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10458                                      uint32_t *table, uint32_t address)
10459 {
10460     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10461     TCR *tcr = regime_tcr(env, mmu_idx);
10462 
10463     if (address & tcr->mask) {
10464         if (tcr->raw_tcr & TTBCR_PD1) {
10465             /* Translation table walk disabled for TTBR1 */
10466             return false;
10467         }
10468         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10469     } else {
10470         if (tcr->raw_tcr & TTBCR_PD0) {
10471             /* Translation table walk disabled for TTBR0 */
10472             return false;
10473         }
10474         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10475     }
10476     *table |= (address >> 18) & 0x3ffc;
10477     return true;
10478 }
10479 
10480 /* Translate a S1 pagetable walk through S2 if needed.  */
10481 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10482                                hwaddr addr, bool *is_secure,
10483                                ARMMMUFaultInfo *fi)
10484 {
10485     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10486         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10487         target_ulong s2size;
10488         hwaddr s2pa;
10489         int s2prot;
10490         int ret;
10491         ARMMMUIdx s2_mmu_idx = *is_secure ? ARMMMUIdx_Stage2_S
10492                                           : ARMMMUIdx_Stage2;
10493         ARMCacheAttrs cacheattrs = {};
10494         MemTxAttrs txattrs = {};
10495 
10496         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, s2_mmu_idx, false,
10497                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10498                                  &cacheattrs);
10499         if (ret) {
10500             assert(fi->type != ARMFault_None);
10501             fi->s2addr = addr;
10502             fi->stage2 = true;
10503             fi->s1ptw = true;
10504             fi->s1ns = !*is_secure;
10505             return ~0;
10506         }
10507         if ((arm_hcr_el2_eff(env) & HCR_PTW) &&
10508             (cacheattrs.attrs & 0xf0) == 0) {
10509             /*
10510              * PTW set and S1 walk touched S2 Device memory:
10511              * generate Permission fault.
10512              */
10513             fi->type = ARMFault_Permission;
10514             fi->s2addr = addr;
10515             fi->stage2 = true;
10516             fi->s1ptw = true;
10517             fi->s1ns = !*is_secure;
10518             return ~0;
10519         }
10520 
10521         if (arm_is_secure_below_el3(env)) {
10522             /* Check if page table walk is to secure or non-secure PA space. */
10523             if (*is_secure) {
10524                 *is_secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
10525             } else {
10526                 *is_secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
10527             }
10528         } else {
10529             assert(!*is_secure);
10530         }
10531 
10532         addr = s2pa;
10533     }
10534     return addr;
10535 }
10536 
10537 /* All loads done in the course of a page table walk go through here. */
10538 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10539                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10540 {
10541     ARMCPU *cpu = ARM_CPU(cs);
10542     CPUARMState *env = &cpu->env;
10543     MemTxAttrs attrs = {};
10544     MemTxResult result = MEMTX_OK;
10545     AddressSpace *as;
10546     uint32_t data;
10547 
10548     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10549     attrs.secure = is_secure;
10550     as = arm_addressspace(cs, attrs);
10551     if (fi->s1ptw) {
10552         return 0;
10553     }
10554     if (regime_translation_big_endian(env, mmu_idx)) {
10555         data = address_space_ldl_be(as, addr, attrs, &result);
10556     } else {
10557         data = address_space_ldl_le(as, addr, attrs, &result);
10558     }
10559     if (result == MEMTX_OK) {
10560         return data;
10561     }
10562     fi->type = ARMFault_SyncExternalOnWalk;
10563     fi->ea = arm_extabort_type(result);
10564     return 0;
10565 }
10566 
10567 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10568                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10569 {
10570     ARMCPU *cpu = ARM_CPU(cs);
10571     CPUARMState *env = &cpu->env;
10572     MemTxAttrs attrs = {};
10573     MemTxResult result = MEMTX_OK;
10574     AddressSpace *as;
10575     uint64_t data;
10576 
10577     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10578     attrs.secure = is_secure;
10579     as = arm_addressspace(cs, attrs);
10580     if (fi->s1ptw) {
10581         return 0;
10582     }
10583     if (regime_translation_big_endian(env, mmu_idx)) {
10584         data = address_space_ldq_be(as, addr, attrs, &result);
10585     } else {
10586         data = address_space_ldq_le(as, addr, attrs, &result);
10587     }
10588     if (result == MEMTX_OK) {
10589         return data;
10590     }
10591     fi->type = ARMFault_SyncExternalOnWalk;
10592     fi->ea = arm_extabort_type(result);
10593     return 0;
10594 }
10595 
10596 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10597                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10598                              hwaddr *phys_ptr, int *prot,
10599                              target_ulong *page_size,
10600                              ARMMMUFaultInfo *fi)
10601 {
10602     CPUState *cs = env_cpu(env);
10603     int level = 1;
10604     uint32_t table;
10605     uint32_t desc;
10606     int type;
10607     int ap;
10608     int domain = 0;
10609     int domain_prot;
10610     hwaddr phys_addr;
10611     uint32_t dacr;
10612 
10613     /* Pagetable walk.  */
10614     /* Lookup l1 descriptor.  */
10615     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10616         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10617         fi->type = ARMFault_Translation;
10618         goto do_fault;
10619     }
10620     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10621                        mmu_idx, fi);
10622     if (fi->type != ARMFault_None) {
10623         goto do_fault;
10624     }
10625     type = (desc & 3);
10626     domain = (desc >> 5) & 0x0f;
10627     if (regime_el(env, mmu_idx) == 1) {
10628         dacr = env->cp15.dacr_ns;
10629     } else {
10630         dacr = env->cp15.dacr_s;
10631     }
10632     domain_prot = (dacr >> (domain * 2)) & 3;
10633     if (type == 0) {
10634         /* Section translation fault.  */
10635         fi->type = ARMFault_Translation;
10636         goto do_fault;
10637     }
10638     if (type != 2) {
10639         level = 2;
10640     }
10641     if (domain_prot == 0 || domain_prot == 2) {
10642         fi->type = ARMFault_Domain;
10643         goto do_fault;
10644     }
10645     if (type == 2) {
10646         /* 1Mb section.  */
10647         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10648         ap = (desc >> 10) & 3;
10649         *page_size = 1024 * 1024;
10650     } else {
10651         /* Lookup l2 entry.  */
10652         if (type == 1) {
10653             /* Coarse pagetable.  */
10654             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10655         } else {
10656             /* Fine pagetable.  */
10657             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10658         }
10659         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10660                            mmu_idx, fi);
10661         if (fi->type != ARMFault_None) {
10662             goto do_fault;
10663         }
10664         switch (desc & 3) {
10665         case 0: /* Page translation fault.  */
10666             fi->type = ARMFault_Translation;
10667             goto do_fault;
10668         case 1: /* 64k page.  */
10669             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10670             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10671             *page_size = 0x10000;
10672             break;
10673         case 2: /* 4k page.  */
10674             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10675             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10676             *page_size = 0x1000;
10677             break;
10678         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10679             if (type == 1) {
10680                 /* ARMv6/XScale extended small page format */
10681                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10682                     || arm_feature(env, ARM_FEATURE_V6)) {
10683                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10684                     *page_size = 0x1000;
10685                 } else {
10686                     /* UNPREDICTABLE in ARMv5; we choose to take a
10687                      * page translation fault.
10688                      */
10689                     fi->type = ARMFault_Translation;
10690                     goto do_fault;
10691                 }
10692             } else {
10693                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10694                 *page_size = 0x400;
10695             }
10696             ap = (desc >> 4) & 3;
10697             break;
10698         default:
10699             /* Never happens, but compiler isn't smart enough to tell.  */
10700             abort();
10701         }
10702     }
10703     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10704     *prot |= *prot ? PAGE_EXEC : 0;
10705     if (!(*prot & (1 << access_type))) {
10706         /* Access permission fault.  */
10707         fi->type = ARMFault_Permission;
10708         goto do_fault;
10709     }
10710     *phys_ptr = phys_addr;
10711     return false;
10712 do_fault:
10713     fi->domain = domain;
10714     fi->level = level;
10715     return true;
10716 }
10717 
10718 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10719                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10720                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10721                              target_ulong *page_size, ARMMMUFaultInfo *fi)
10722 {
10723     CPUState *cs = env_cpu(env);
10724     ARMCPU *cpu = env_archcpu(env);
10725     int level = 1;
10726     uint32_t table;
10727     uint32_t desc;
10728     uint32_t xn;
10729     uint32_t pxn = 0;
10730     int type;
10731     int ap;
10732     int domain = 0;
10733     int domain_prot;
10734     hwaddr phys_addr;
10735     uint32_t dacr;
10736     bool ns;
10737 
10738     /* Pagetable walk.  */
10739     /* Lookup l1 descriptor.  */
10740     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10741         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10742         fi->type = ARMFault_Translation;
10743         goto do_fault;
10744     }
10745     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10746                        mmu_idx, fi);
10747     if (fi->type != ARMFault_None) {
10748         goto do_fault;
10749     }
10750     type = (desc & 3);
10751     if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
10752         /* Section translation fault, or attempt to use the encoding
10753          * which is Reserved on implementations without PXN.
10754          */
10755         fi->type = ARMFault_Translation;
10756         goto do_fault;
10757     }
10758     if ((type == 1) || !(desc & (1 << 18))) {
10759         /* Page or Section.  */
10760         domain = (desc >> 5) & 0x0f;
10761     }
10762     if (regime_el(env, mmu_idx) == 1) {
10763         dacr = env->cp15.dacr_ns;
10764     } else {
10765         dacr = env->cp15.dacr_s;
10766     }
10767     if (type == 1) {
10768         level = 2;
10769     }
10770     domain_prot = (dacr >> (domain * 2)) & 3;
10771     if (domain_prot == 0 || domain_prot == 2) {
10772         /* Section or Page domain fault */
10773         fi->type = ARMFault_Domain;
10774         goto do_fault;
10775     }
10776     if (type != 1) {
10777         if (desc & (1 << 18)) {
10778             /* Supersection.  */
10779             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
10780             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
10781             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
10782             *page_size = 0x1000000;
10783         } else {
10784             /* Section.  */
10785             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10786             *page_size = 0x100000;
10787         }
10788         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
10789         xn = desc & (1 << 4);
10790         pxn = desc & 1;
10791         ns = extract32(desc, 19, 1);
10792     } else {
10793         if (cpu_isar_feature(aa32_pxn, cpu)) {
10794             pxn = (desc >> 2) & 1;
10795         }
10796         ns = extract32(desc, 3, 1);
10797         /* Lookup l2 entry.  */
10798         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10799         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10800                            mmu_idx, fi);
10801         if (fi->type != ARMFault_None) {
10802             goto do_fault;
10803         }
10804         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
10805         switch (desc & 3) {
10806         case 0: /* Page translation fault.  */
10807             fi->type = ARMFault_Translation;
10808             goto do_fault;
10809         case 1: /* 64k page.  */
10810             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10811             xn = desc & (1 << 15);
10812             *page_size = 0x10000;
10813             break;
10814         case 2: case 3: /* 4k page.  */
10815             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10816             xn = desc & 1;
10817             *page_size = 0x1000;
10818             break;
10819         default:
10820             /* Never happens, but compiler isn't smart enough to tell.  */
10821             abort();
10822         }
10823     }
10824     if (domain_prot == 3) {
10825         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10826     } else {
10827         if (pxn && !regime_is_user(env, mmu_idx)) {
10828             xn = 1;
10829         }
10830         if (xn && access_type == MMU_INST_FETCH) {
10831             fi->type = ARMFault_Permission;
10832             goto do_fault;
10833         }
10834 
10835         if (arm_feature(env, ARM_FEATURE_V6K) &&
10836                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
10837             /* The simplified model uses AP[0] as an access control bit.  */
10838             if ((ap & 1) == 0) {
10839                 /* Access flag fault.  */
10840                 fi->type = ARMFault_AccessFlag;
10841                 goto do_fault;
10842             }
10843             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
10844         } else {
10845             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10846         }
10847         if (*prot && !xn) {
10848             *prot |= PAGE_EXEC;
10849         }
10850         if (!(*prot & (1 << access_type))) {
10851             /* Access permission fault.  */
10852             fi->type = ARMFault_Permission;
10853             goto do_fault;
10854         }
10855     }
10856     if (ns) {
10857         /* The NS bit will (as required by the architecture) have no effect if
10858          * the CPU doesn't support TZ or this is a non-secure translation
10859          * regime, because the attribute will already be non-secure.
10860          */
10861         attrs->secure = false;
10862     }
10863     *phys_ptr = phys_addr;
10864     return false;
10865 do_fault:
10866     fi->domain = domain;
10867     fi->level = level;
10868     return true;
10869 }
10870 
10871 /*
10872  * check_s2_mmu_setup
10873  * @cpu:        ARMCPU
10874  * @is_aa64:    True if the translation regime is in AArch64 state
10875  * @startlevel: Suggested starting level
10876  * @inputsize:  Bitsize of IPAs
10877  * @stride:     Page-table stride (See the ARM ARM)
10878  *
10879  * Returns true if the suggested S2 translation parameters are OK and
10880  * false otherwise.
10881  */
10882 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
10883                                int inputsize, int stride)
10884 {
10885     const int grainsize = stride + 3;
10886     int startsizecheck;
10887 
10888     /* Negative levels are never allowed.  */
10889     if (level < 0) {
10890         return false;
10891     }
10892 
10893     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
10894     if (startsizecheck < 1 || startsizecheck > stride + 4) {
10895         return false;
10896     }
10897 
10898     if (is_aa64) {
10899         CPUARMState *env = &cpu->env;
10900         unsigned int pamax = arm_pamax(cpu);
10901 
10902         switch (stride) {
10903         case 13: /* 64KB Pages.  */
10904             if (level == 0 || (level == 1 && pamax <= 42)) {
10905                 return false;
10906             }
10907             break;
10908         case 11: /* 16KB Pages.  */
10909             if (level == 0 || (level == 1 && pamax <= 40)) {
10910                 return false;
10911             }
10912             break;
10913         case 9: /* 4KB Pages.  */
10914             if (level == 0 && pamax <= 42) {
10915                 return false;
10916             }
10917             break;
10918         default:
10919             g_assert_not_reached();
10920         }
10921 
10922         /* Inputsize checks.  */
10923         if (inputsize > pamax &&
10924             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
10925             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
10926             return false;
10927         }
10928     } else {
10929         /* AArch32 only supports 4KB pages. Assert on that.  */
10930         assert(stride == 9);
10931 
10932         if (level == 0) {
10933             return false;
10934         }
10935     }
10936     return true;
10937 }
10938 
10939 /* Translate from the 4-bit stage 2 representation of
10940  * memory attributes (without cache-allocation hints) to
10941  * the 8-bit representation of the stage 1 MAIR registers
10942  * (which includes allocation hints).
10943  *
10944  * ref: shared/translation/attrs/S2AttrDecode()
10945  *      .../S2ConvertAttrsHints()
10946  */
10947 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
10948 {
10949     uint8_t hiattr = extract32(s2attrs, 2, 2);
10950     uint8_t loattr = extract32(s2attrs, 0, 2);
10951     uint8_t hihint = 0, lohint = 0;
10952 
10953     if (hiattr != 0) { /* normal memory */
10954         if (arm_hcr_el2_eff(env) & HCR_CD) { /* cache disabled */
10955             hiattr = loattr = 1; /* non-cacheable */
10956         } else {
10957             if (hiattr != 1) { /* Write-through or write-back */
10958                 hihint = 3; /* RW allocate */
10959             }
10960             if (loattr != 1) { /* Write-through or write-back */
10961                 lohint = 3; /* RW allocate */
10962             }
10963         }
10964     }
10965 
10966     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
10967 }
10968 #endif /* !CONFIG_USER_ONLY */
10969 
10970 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
10971 {
10972     if (regime_has_2_ranges(mmu_idx)) {
10973         return extract64(tcr, 37, 2);
10974     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10975         return 0; /* VTCR_EL2 */
10976     } else {
10977         /* Replicate the single TBI bit so we always have 2 bits.  */
10978         return extract32(tcr, 20, 1) * 3;
10979     }
10980 }
10981 
10982 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
10983 {
10984     if (regime_has_2_ranges(mmu_idx)) {
10985         return extract64(tcr, 51, 2);
10986     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10987         return 0; /* VTCR_EL2 */
10988     } else {
10989         /* Replicate the single TBID bit so we always have 2 bits.  */
10990         return extract32(tcr, 29, 1) * 3;
10991     }
10992 }
10993 
10994 static int aa64_va_parameter_tcma(uint64_t tcr, ARMMMUIdx mmu_idx)
10995 {
10996     if (regime_has_2_ranges(mmu_idx)) {
10997         return extract64(tcr, 57, 2);
10998     } else {
10999         /* Replicate the single TCMA bit so we always have 2 bits.  */
11000         return extract32(tcr, 30, 1) * 3;
11001     }
11002 }
11003 
11004 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11005                                    ARMMMUIdx mmu_idx, bool data)
11006 {
11007     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11008     bool epd, hpd, using16k, using64k;
11009     int select, tsz, tbi, max_tsz;
11010 
11011     if (!regime_has_2_ranges(mmu_idx)) {
11012         select = 0;
11013         tsz = extract32(tcr, 0, 6);
11014         using64k = extract32(tcr, 14, 1);
11015         using16k = extract32(tcr, 15, 1);
11016         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11017             /* VTCR_EL2 */
11018             hpd = false;
11019         } else {
11020             hpd = extract32(tcr, 24, 1);
11021         }
11022         epd = false;
11023     } else {
11024         /*
11025          * Bit 55 is always between the two regions, and is canonical for
11026          * determining if address tagging is enabled.
11027          */
11028         select = extract64(va, 55, 1);
11029         if (!select) {
11030             tsz = extract32(tcr, 0, 6);
11031             epd = extract32(tcr, 7, 1);
11032             using64k = extract32(tcr, 14, 1);
11033             using16k = extract32(tcr, 15, 1);
11034             hpd = extract64(tcr, 41, 1);
11035         } else {
11036             int tg = extract32(tcr, 30, 2);
11037             using16k = tg == 1;
11038             using64k = tg == 3;
11039             tsz = extract32(tcr, 16, 6);
11040             epd = extract32(tcr, 23, 1);
11041             hpd = extract64(tcr, 42, 1);
11042         }
11043     }
11044 
11045     if (cpu_isar_feature(aa64_st, env_archcpu(env))) {
11046         max_tsz = 48 - using64k;
11047     } else {
11048         max_tsz = 39;
11049     }
11050 
11051     tsz = MIN(tsz, max_tsz);
11052     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
11053 
11054     /* Present TBI as a composite with TBID.  */
11055     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11056     if (!data) {
11057         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11058     }
11059     tbi = (tbi >> select) & 1;
11060 
11061     return (ARMVAParameters) {
11062         .tsz = tsz,
11063         .select = select,
11064         .tbi = tbi,
11065         .epd = epd,
11066         .hpd = hpd,
11067         .using16k = using16k,
11068         .using64k = using64k,
11069     };
11070 }
11071 
11072 #ifndef CONFIG_USER_ONLY
11073 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11074                                           ARMMMUIdx mmu_idx)
11075 {
11076     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11077     uint32_t el = regime_el(env, mmu_idx);
11078     int select, tsz;
11079     bool epd, hpd;
11080 
11081     assert(mmu_idx != ARMMMUIdx_Stage2_S);
11082 
11083     if (mmu_idx == ARMMMUIdx_Stage2) {
11084         /* VTCR */
11085         bool sext = extract32(tcr, 4, 1);
11086         bool sign = extract32(tcr, 3, 1);
11087 
11088         /*
11089          * If the sign-extend bit is not the same as t0sz[3], the result
11090          * is unpredictable. Flag this as a guest error.
11091          */
11092         if (sign != sext) {
11093             qemu_log_mask(LOG_GUEST_ERROR,
11094                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11095         }
11096         tsz = sextract32(tcr, 0, 4) + 8;
11097         select = 0;
11098         hpd = false;
11099         epd = false;
11100     } else if (el == 2) {
11101         /* HTCR */
11102         tsz = extract32(tcr, 0, 3);
11103         select = 0;
11104         hpd = extract64(tcr, 24, 1);
11105         epd = false;
11106     } else {
11107         int t0sz = extract32(tcr, 0, 3);
11108         int t1sz = extract32(tcr, 16, 3);
11109 
11110         if (t1sz == 0) {
11111             select = va > (0xffffffffu >> t0sz);
11112         } else {
11113             /* Note that we will detect errors later.  */
11114             select = va >= ~(0xffffffffu >> t1sz);
11115         }
11116         if (!select) {
11117             tsz = t0sz;
11118             epd = extract32(tcr, 7, 1);
11119             hpd = extract64(tcr, 41, 1);
11120         } else {
11121             tsz = t1sz;
11122             epd = extract32(tcr, 23, 1);
11123             hpd = extract64(tcr, 42, 1);
11124         }
11125         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11126         hpd &= extract32(tcr, 6, 1);
11127     }
11128 
11129     return (ARMVAParameters) {
11130         .tsz = tsz,
11131         .select = select,
11132         .epd = epd,
11133         .hpd = hpd,
11134     };
11135 }
11136 
11137 /**
11138  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
11139  *
11140  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11141  * prot and page_size may not be filled in, and the populated fsr value provides
11142  * information on why the translation aborted, in the format of a long-format
11143  * DFSR/IFSR fault register, with the following caveats:
11144  *  * the WnR bit is never set (the caller must do this).
11145  *
11146  * @env: CPUARMState
11147  * @address: virtual address to get physical address for
11148  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
11149  * @mmu_idx: MMU index indicating required translation regime
11150  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
11151  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
11152  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
11153  * @phys_ptr: set to the physical address corresponding to the virtual address
11154  * @attrs: set to the memory transaction attributes to use
11155  * @prot: set to the permissions for the page containing phys_ptr
11156  * @page_size_ptr: set to the size of the page containing phys_ptr
11157  * @fi: set to fault info if the translation fails
11158  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11159  */
11160 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
11161                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11162                                bool s1_is_el0,
11163                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11164                                target_ulong *page_size_ptr,
11165                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11166 {
11167     ARMCPU *cpu = env_archcpu(env);
11168     CPUState *cs = CPU(cpu);
11169     /* Read an LPAE long-descriptor translation table. */
11170     ARMFaultType fault_type = ARMFault_Translation;
11171     uint32_t level;
11172     ARMVAParameters param;
11173     uint64_t ttbr;
11174     hwaddr descaddr, indexmask, indexmask_grainsize;
11175     uint32_t tableattrs;
11176     target_ulong page_size;
11177     uint32_t attrs;
11178     int32_t stride;
11179     int addrsize, inputsize;
11180     TCR *tcr = regime_tcr(env, mmu_idx);
11181     int ap, ns, xn, pxn;
11182     uint32_t el = regime_el(env, mmu_idx);
11183     uint64_t descaddrmask;
11184     bool aarch64 = arm_el_is_aa64(env, el);
11185     bool guarded = false;
11186 
11187     /* TODO: This code does not support shareability levels. */
11188     if (aarch64) {
11189         param = aa64_va_parameters(env, address, mmu_idx,
11190                                    access_type != MMU_INST_FETCH);
11191         level = 0;
11192         addrsize = 64 - 8 * param.tbi;
11193         inputsize = 64 - param.tsz;
11194     } else {
11195         param = aa32_va_parameters(env, address, mmu_idx);
11196         level = 1;
11197         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
11198         inputsize = addrsize - param.tsz;
11199     }
11200 
11201     /*
11202      * We determined the region when collecting the parameters, but we
11203      * have not yet validated that the address is valid for the region.
11204      * Extract the top bits and verify that they all match select.
11205      *
11206      * For aa32, if inputsize == addrsize, then we have selected the
11207      * region by exclusion in aa32_va_parameters and there is no more
11208      * validation to do here.
11209      */
11210     if (inputsize < addrsize) {
11211         target_ulong top_bits = sextract64(address, inputsize,
11212                                            addrsize - inputsize);
11213         if (-top_bits != param.select) {
11214             /* The gap between the two regions is a Translation fault */
11215             fault_type = ARMFault_Translation;
11216             goto do_fault;
11217         }
11218     }
11219 
11220     if (param.using64k) {
11221         stride = 13;
11222     } else if (param.using16k) {
11223         stride = 11;
11224     } else {
11225         stride = 9;
11226     }
11227 
11228     /* Note that QEMU ignores shareability and cacheability attributes,
11229      * so we don't need to do anything with the SH, ORGN, IRGN fields
11230      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11231      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11232      * implement any ASID-like capability so we can ignore it (instead
11233      * we will always flush the TLB any time the ASID is changed).
11234      */
11235     ttbr = regime_ttbr(env, mmu_idx, param.select);
11236 
11237     /* Here we should have set up all the parameters for the translation:
11238      * inputsize, ttbr, epd, stride, tbi
11239      */
11240 
11241     if (param.epd) {
11242         /* Translation table walk disabled => Translation fault on TLB miss
11243          * Note: This is always 0 on 64-bit EL2 and EL3.
11244          */
11245         goto do_fault;
11246     }
11247 
11248     if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
11249         /* The starting level depends on the virtual address size (which can
11250          * be up to 48 bits) and the translation granule size. It indicates
11251          * the number of strides (stride bits at a time) needed to
11252          * consume the bits of the input address. In the pseudocode this is:
11253          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11254          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11255          * our 'stride + 3' and 'stride' is our 'stride'.
11256          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11257          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11258          * = 4 - (inputsize - 4) / stride;
11259          */
11260         level = 4 - (inputsize - 4) / stride;
11261     } else {
11262         /* For stage 2 translations the starting level is specified by the
11263          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11264          */
11265         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11266         uint32_t startlevel;
11267         bool ok;
11268 
11269         if (!aarch64 || stride == 9) {
11270             /* AArch32 or 4KB pages */
11271             startlevel = 2 - sl0;
11272 
11273             if (cpu_isar_feature(aa64_st, cpu)) {
11274                 startlevel &= 3;
11275             }
11276         } else {
11277             /* 16KB or 64KB pages */
11278             startlevel = 3 - sl0;
11279         }
11280 
11281         /* Check that the starting level is valid. */
11282         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11283                                 inputsize, stride);
11284         if (!ok) {
11285             fault_type = ARMFault_Translation;
11286             goto do_fault;
11287         }
11288         level = startlevel;
11289     }
11290 
11291     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
11292     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
11293 
11294     /* Now we can extract the actual base address from the TTBR */
11295     descaddr = extract64(ttbr, 0, 48);
11296     /*
11297      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
11298      * and also to mask out CnP (bit 0) which could validly be non-zero.
11299      */
11300     descaddr &= ~indexmask;
11301 
11302     /* The address field in the descriptor goes up to bit 39 for ARMv7
11303      * but up to bit 47 for ARMv8, but we use the descaddrmask
11304      * up to bit 39 for AArch32, because we don't need other bits in that case
11305      * to construct next descriptor address (anyway they should be all zeroes).
11306      */
11307     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
11308                    ~indexmask_grainsize;
11309 
11310     /* Secure accesses start with the page table in secure memory and
11311      * can be downgraded to non-secure at any step. Non-secure accesses
11312      * remain non-secure. We implement this by just ORing in the NSTable/NS
11313      * bits at each step.
11314      */
11315     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11316     for (;;) {
11317         uint64_t descriptor;
11318         bool nstable;
11319 
11320         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11321         descaddr &= ~7ULL;
11322         nstable = extract32(tableattrs, 4, 1);
11323         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11324         if (fi->type != ARMFault_None) {
11325             goto do_fault;
11326         }
11327 
11328         if (!(descriptor & 1) ||
11329             (!(descriptor & 2) && (level == 3))) {
11330             /* Invalid, or the Reserved level 3 encoding */
11331             goto do_fault;
11332         }
11333         descaddr = descriptor & descaddrmask;
11334 
11335         if ((descriptor & 2) && (level < 3)) {
11336             /* Table entry. The top five bits are attributes which may
11337              * propagate down through lower levels of the table (and
11338              * which are all arranged so that 0 means "no effect", so
11339              * we can gather them up by ORing in the bits at each level).
11340              */
11341             tableattrs |= extract64(descriptor, 59, 5);
11342             level++;
11343             indexmask = indexmask_grainsize;
11344             continue;
11345         }
11346         /* Block entry at level 1 or 2, or page entry at level 3.
11347          * These are basically the same thing, although the number
11348          * of bits we pull in from the vaddr varies.
11349          */
11350         page_size = (1ULL << ((stride * (4 - level)) + 3));
11351         descaddr |= (address & (page_size - 1));
11352         /* Extract attributes from the descriptor */
11353         attrs = extract64(descriptor, 2, 10)
11354             | (extract64(descriptor, 52, 12) << 10);
11355 
11356         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11357             /* Stage 2 table descriptors do not include any attribute fields */
11358             break;
11359         }
11360         /* Merge in attributes from table descriptors */
11361         attrs |= nstable << 3; /* NS */
11362         guarded = extract64(descriptor, 50, 1);  /* GP */
11363         if (param.hpd) {
11364             /* HPD disables all the table attributes except NSTable.  */
11365             break;
11366         }
11367         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11368         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11369          * means "force PL1 access only", which means forcing AP[1] to 0.
11370          */
11371         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11372         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11373         break;
11374     }
11375     /* Here descaddr is the final physical address, and attributes
11376      * are all in attrs.
11377      */
11378     fault_type = ARMFault_AccessFlag;
11379     if ((attrs & (1 << 8)) == 0) {
11380         /* Access flag */
11381         goto do_fault;
11382     }
11383 
11384     ap = extract32(attrs, 4, 2);
11385 
11386     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11387         ns = mmu_idx == ARMMMUIdx_Stage2;
11388         xn = extract32(attrs, 11, 2);
11389         *prot = get_S2prot(env, ap, xn, s1_is_el0);
11390     } else {
11391         ns = extract32(attrs, 3, 1);
11392         xn = extract32(attrs, 12, 1);
11393         pxn = extract32(attrs, 11, 1);
11394         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11395     }
11396 
11397     fault_type = ARMFault_Permission;
11398     if (!(*prot & (1 << access_type))) {
11399         goto do_fault;
11400     }
11401 
11402     if (ns) {
11403         /* The NS bit will (as required by the architecture) have no effect if
11404          * the CPU doesn't support TZ or this is a non-secure translation
11405          * regime, because the attribute will already be non-secure.
11406          */
11407         txattrs->secure = false;
11408     }
11409     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11410     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11411         arm_tlb_bti_gp(txattrs) = true;
11412     }
11413 
11414     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11415         cacheattrs->attrs = convert_stage2_attrs(env, extract32(attrs, 0, 4));
11416     } else {
11417         /* Index into MAIR registers for cache attributes */
11418         uint8_t attrindx = extract32(attrs, 0, 3);
11419         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11420         assert(attrindx <= 7);
11421         cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11422     }
11423     cacheattrs->shareability = extract32(attrs, 6, 2);
11424 
11425     *phys_ptr = descaddr;
11426     *page_size_ptr = page_size;
11427     return false;
11428 
11429 do_fault:
11430     fi->type = fault_type;
11431     fi->level = level;
11432     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11433     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2 ||
11434                                mmu_idx == ARMMMUIdx_Stage2_S);
11435     fi->s1ns = mmu_idx == ARMMMUIdx_Stage2;
11436     return true;
11437 }
11438 
11439 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11440                                                 ARMMMUIdx mmu_idx,
11441                                                 int32_t address, int *prot)
11442 {
11443     if (!arm_feature(env, ARM_FEATURE_M)) {
11444         *prot = PAGE_READ | PAGE_WRITE;
11445         switch (address) {
11446         case 0xF0000000 ... 0xFFFFFFFF:
11447             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11448                 /* hivecs execing is ok */
11449                 *prot |= PAGE_EXEC;
11450             }
11451             break;
11452         case 0x00000000 ... 0x7FFFFFFF:
11453             *prot |= PAGE_EXEC;
11454             break;
11455         }
11456     } else {
11457         /* Default system address map for M profile cores.
11458          * The architecture specifies which regions are execute-never;
11459          * at the MPU level no other checks are defined.
11460          */
11461         switch (address) {
11462         case 0x00000000 ... 0x1fffffff: /* ROM */
11463         case 0x20000000 ... 0x3fffffff: /* SRAM */
11464         case 0x60000000 ... 0x7fffffff: /* RAM */
11465         case 0x80000000 ... 0x9fffffff: /* RAM */
11466             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11467             break;
11468         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11469         case 0xa0000000 ... 0xbfffffff: /* Device */
11470         case 0xc0000000 ... 0xdfffffff: /* Device */
11471         case 0xe0000000 ... 0xffffffff: /* System */
11472             *prot = PAGE_READ | PAGE_WRITE;
11473             break;
11474         default:
11475             g_assert_not_reached();
11476         }
11477     }
11478 }
11479 
11480 static bool pmsav7_use_background_region(ARMCPU *cpu,
11481                                          ARMMMUIdx mmu_idx, bool is_user)
11482 {
11483     /* Return true if we should use the default memory map as a
11484      * "background" region if there are no hits against any MPU regions.
11485      */
11486     CPUARMState *env = &cpu->env;
11487 
11488     if (is_user) {
11489         return false;
11490     }
11491 
11492     if (arm_feature(env, ARM_FEATURE_M)) {
11493         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11494             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11495     } else {
11496         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11497     }
11498 }
11499 
11500 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11501 {
11502     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11503     return arm_feature(env, ARM_FEATURE_M) &&
11504         extract32(address, 20, 12) == 0xe00;
11505 }
11506 
11507 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11508 {
11509     /* True if address is in the M profile system region
11510      * 0xe0000000 - 0xffffffff
11511      */
11512     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11513 }
11514 
11515 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11516                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11517                                  hwaddr *phys_ptr, int *prot,
11518                                  target_ulong *page_size,
11519                                  ARMMMUFaultInfo *fi)
11520 {
11521     ARMCPU *cpu = env_archcpu(env);
11522     int n;
11523     bool is_user = regime_is_user(env, mmu_idx);
11524 
11525     *phys_ptr = address;
11526     *page_size = TARGET_PAGE_SIZE;
11527     *prot = 0;
11528 
11529     if (regime_translation_disabled(env, mmu_idx) ||
11530         m_is_ppb_region(env, address)) {
11531         /* MPU disabled or M profile PPB access: use default memory map.
11532          * The other case which uses the default memory map in the
11533          * v7M ARM ARM pseudocode is exception vector reads from the vector
11534          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11535          * which always does a direct read using address_space_ldl(), rather
11536          * than going via this function, so we don't need to check that here.
11537          */
11538         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11539     } else { /* MPU enabled */
11540         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11541             /* region search */
11542             uint32_t base = env->pmsav7.drbar[n];
11543             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11544             uint32_t rmask;
11545             bool srdis = false;
11546 
11547             if (!(env->pmsav7.drsr[n] & 0x1)) {
11548                 continue;
11549             }
11550 
11551             if (!rsize) {
11552                 qemu_log_mask(LOG_GUEST_ERROR,
11553                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11554                 continue;
11555             }
11556             rsize++;
11557             rmask = (1ull << rsize) - 1;
11558 
11559             if (base & rmask) {
11560                 qemu_log_mask(LOG_GUEST_ERROR,
11561                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11562                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11563                               n, base, rmask);
11564                 continue;
11565             }
11566 
11567             if (address < base || address > base + rmask) {
11568                 /*
11569                  * Address not in this region. We must check whether the
11570                  * region covers addresses in the same page as our address.
11571                  * In that case we must not report a size that covers the
11572                  * whole page for a subsequent hit against a different MPU
11573                  * region or the background region, because it would result in
11574                  * incorrect TLB hits for subsequent accesses to addresses that
11575                  * are in this MPU region.
11576                  */
11577                 if (ranges_overlap(base, rmask,
11578                                    address & TARGET_PAGE_MASK,
11579                                    TARGET_PAGE_SIZE)) {
11580                     *page_size = 1;
11581                 }
11582                 continue;
11583             }
11584 
11585             /* Region matched */
11586 
11587             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11588                 int i, snd;
11589                 uint32_t srdis_mask;
11590 
11591                 rsize -= 3; /* sub region size (power of 2) */
11592                 snd = ((address - base) >> rsize) & 0x7;
11593                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11594 
11595                 srdis_mask = srdis ? 0x3 : 0x0;
11596                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11597                     /* This will check in groups of 2, 4 and then 8, whether
11598                      * the subregion bits are consistent. rsize is incremented
11599                      * back up to give the region size, considering consistent
11600                      * adjacent subregions as one region. Stop testing if rsize
11601                      * is already big enough for an entire QEMU page.
11602                      */
11603                     int snd_rounded = snd & ~(i - 1);
11604                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11605                                                      snd_rounded + 8, i);
11606                     if (srdis_mask ^ srdis_multi) {
11607                         break;
11608                     }
11609                     srdis_mask = (srdis_mask << i) | srdis_mask;
11610                     rsize++;
11611                 }
11612             }
11613             if (srdis) {
11614                 continue;
11615             }
11616             if (rsize < TARGET_PAGE_BITS) {
11617                 *page_size = 1 << rsize;
11618             }
11619             break;
11620         }
11621 
11622         if (n == -1) { /* no hits */
11623             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11624                 /* background fault */
11625                 fi->type = ARMFault_Background;
11626                 return true;
11627             }
11628             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11629         } else { /* a MPU hit! */
11630             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
11631             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
11632 
11633             if (m_is_system_region(env, address)) {
11634                 /* System space is always execute never */
11635                 xn = 1;
11636             }
11637 
11638             if (is_user) { /* User mode AP bit decoding */
11639                 switch (ap) {
11640                 case 0:
11641                 case 1:
11642                 case 5:
11643                     break; /* no access */
11644                 case 3:
11645                     *prot |= PAGE_WRITE;
11646                     /* fall through */
11647                 case 2:
11648                 case 6:
11649                     *prot |= PAGE_READ | PAGE_EXEC;
11650                     break;
11651                 case 7:
11652                     /* for v7M, same as 6; for R profile a reserved value */
11653                     if (arm_feature(env, ARM_FEATURE_M)) {
11654                         *prot |= PAGE_READ | PAGE_EXEC;
11655                         break;
11656                     }
11657                     /* fall through */
11658                 default:
11659                     qemu_log_mask(LOG_GUEST_ERROR,
11660                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11661                                   PRIx32 "\n", n, ap);
11662                 }
11663             } else { /* Priv. mode AP bits decoding */
11664                 switch (ap) {
11665                 case 0:
11666                     break; /* no access */
11667                 case 1:
11668                 case 2:
11669                 case 3:
11670                     *prot |= PAGE_WRITE;
11671                     /* fall through */
11672                 case 5:
11673                 case 6:
11674                     *prot |= PAGE_READ | PAGE_EXEC;
11675                     break;
11676                 case 7:
11677                     /* for v7M, same as 6; for R profile a reserved value */
11678                     if (arm_feature(env, ARM_FEATURE_M)) {
11679                         *prot |= PAGE_READ | PAGE_EXEC;
11680                         break;
11681                     }
11682                     /* fall through */
11683                 default:
11684                     qemu_log_mask(LOG_GUEST_ERROR,
11685                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11686                                   PRIx32 "\n", n, ap);
11687                 }
11688             }
11689 
11690             /* execute never */
11691             if (xn) {
11692                 *prot &= ~PAGE_EXEC;
11693             }
11694         }
11695     }
11696 
11697     fi->type = ARMFault_Permission;
11698     fi->level = 1;
11699     return !(*prot & (1 << access_type));
11700 }
11701 
11702 static bool v8m_is_sau_exempt(CPUARMState *env,
11703                               uint32_t address, MMUAccessType access_type)
11704 {
11705     /* The architecture specifies that certain address ranges are
11706      * exempt from v8M SAU/IDAU checks.
11707      */
11708     return
11709         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
11710         (address >= 0xe0000000 && address <= 0xe0002fff) ||
11711         (address >= 0xe000e000 && address <= 0xe000efff) ||
11712         (address >= 0xe002e000 && address <= 0xe002efff) ||
11713         (address >= 0xe0040000 && address <= 0xe0041fff) ||
11714         (address >= 0xe00ff000 && address <= 0xe00fffff);
11715 }
11716 
11717 void v8m_security_lookup(CPUARMState *env, uint32_t address,
11718                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
11719                                 V8M_SAttributes *sattrs)
11720 {
11721     /* Look up the security attributes for this address. Compare the
11722      * pseudocode SecurityCheck() function.
11723      * We assume the caller has zero-initialized *sattrs.
11724      */
11725     ARMCPU *cpu = env_archcpu(env);
11726     int r;
11727     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
11728     int idau_region = IREGION_NOTVALID;
11729     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11730     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11731 
11732     if (cpu->idau) {
11733         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
11734         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
11735 
11736         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
11737                    &idau_nsc);
11738     }
11739 
11740     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
11741         /* 0xf0000000..0xffffffff is always S for insn fetches */
11742         return;
11743     }
11744 
11745     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
11746         sattrs->ns = !regime_is_secure(env, mmu_idx);
11747         return;
11748     }
11749 
11750     if (idau_region != IREGION_NOTVALID) {
11751         sattrs->irvalid = true;
11752         sattrs->iregion = idau_region;
11753     }
11754 
11755     switch (env->sau.ctrl & 3) {
11756     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
11757         break;
11758     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
11759         sattrs->ns = true;
11760         break;
11761     default: /* SAU.ENABLE == 1 */
11762         for (r = 0; r < cpu->sau_sregion; r++) {
11763             if (env->sau.rlar[r] & 1) {
11764                 uint32_t base = env->sau.rbar[r] & ~0x1f;
11765                 uint32_t limit = env->sau.rlar[r] | 0x1f;
11766 
11767                 if (base <= address && limit >= address) {
11768                     if (base > addr_page_base || limit < addr_page_limit) {
11769                         sattrs->subpage = true;
11770                     }
11771                     if (sattrs->srvalid) {
11772                         /* If we hit in more than one region then we must report
11773                          * as Secure, not NS-Callable, with no valid region
11774                          * number info.
11775                          */
11776                         sattrs->ns = false;
11777                         sattrs->nsc = false;
11778                         sattrs->sregion = 0;
11779                         sattrs->srvalid = false;
11780                         break;
11781                     } else {
11782                         if (env->sau.rlar[r] & 2) {
11783                             sattrs->nsc = true;
11784                         } else {
11785                             sattrs->ns = true;
11786                         }
11787                         sattrs->srvalid = true;
11788                         sattrs->sregion = r;
11789                     }
11790                 } else {
11791                     /*
11792                      * Address not in this region. We must check whether the
11793                      * region covers addresses in the same page as our address.
11794                      * In that case we must not report a size that covers the
11795                      * whole page for a subsequent hit against a different MPU
11796                      * region or the background region, because it would result
11797                      * in incorrect TLB hits for subsequent accesses to
11798                      * addresses that are in this MPU region.
11799                      */
11800                     if (limit >= base &&
11801                         ranges_overlap(base, limit - base + 1,
11802                                        addr_page_base,
11803                                        TARGET_PAGE_SIZE)) {
11804                         sattrs->subpage = true;
11805                     }
11806                 }
11807             }
11808         }
11809         break;
11810     }
11811 
11812     /*
11813      * The IDAU will override the SAU lookup results if it specifies
11814      * higher security than the SAU does.
11815      */
11816     if (!idau_ns) {
11817         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
11818             sattrs->ns = false;
11819             sattrs->nsc = idau_nsc;
11820         }
11821     }
11822 }
11823 
11824 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
11825                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
11826                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
11827                               int *prot, bool *is_subpage,
11828                               ARMMMUFaultInfo *fi, uint32_t *mregion)
11829 {
11830     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
11831      * that a full phys-to-virt translation does).
11832      * mregion is (if not NULL) set to the region number which matched,
11833      * or -1 if no region number is returned (MPU off, address did not
11834      * hit a region, address hit in multiple regions).
11835      * We set is_subpage to true if the region hit doesn't cover the
11836      * entire TARGET_PAGE the address is within.
11837      */
11838     ARMCPU *cpu = env_archcpu(env);
11839     bool is_user = regime_is_user(env, mmu_idx);
11840     uint32_t secure = regime_is_secure(env, mmu_idx);
11841     int n;
11842     int matchregion = -1;
11843     bool hit = false;
11844     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11845     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11846 
11847     *is_subpage = false;
11848     *phys_ptr = address;
11849     *prot = 0;
11850     if (mregion) {
11851         *mregion = -1;
11852     }
11853 
11854     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
11855      * was an exception vector read from the vector table (which is always
11856      * done using the default system address map), because those accesses
11857      * are done in arm_v7m_load_vector(), which always does a direct
11858      * read using address_space_ldl(), rather than going via this function.
11859      */
11860     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
11861         hit = true;
11862     } else if (m_is_ppb_region(env, address)) {
11863         hit = true;
11864     } else {
11865         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11866             hit = true;
11867         }
11868 
11869         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11870             /* region search */
11871             /* Note that the base address is bits [31:5] from the register
11872              * with bits [4:0] all zeroes, but the limit address is bits
11873              * [31:5] from the register with bits [4:0] all ones.
11874              */
11875             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
11876             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
11877 
11878             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
11879                 /* Region disabled */
11880                 continue;
11881             }
11882 
11883             if (address < base || address > limit) {
11884                 /*
11885                  * Address not in this region. We must check whether the
11886                  * region covers addresses in the same page as our address.
11887                  * In that case we must not report a size that covers the
11888                  * whole page for a subsequent hit against a different MPU
11889                  * region or the background region, because it would result in
11890                  * incorrect TLB hits for subsequent accesses to addresses that
11891                  * are in this MPU region.
11892                  */
11893                 if (limit >= base &&
11894                     ranges_overlap(base, limit - base + 1,
11895                                    addr_page_base,
11896                                    TARGET_PAGE_SIZE)) {
11897                     *is_subpage = true;
11898                 }
11899                 continue;
11900             }
11901 
11902             if (base > addr_page_base || limit < addr_page_limit) {
11903                 *is_subpage = true;
11904             }
11905 
11906             if (matchregion != -1) {
11907                 /* Multiple regions match -- always a failure (unlike
11908                  * PMSAv7 where highest-numbered-region wins)
11909                  */
11910                 fi->type = ARMFault_Permission;
11911                 fi->level = 1;
11912                 return true;
11913             }
11914 
11915             matchregion = n;
11916             hit = true;
11917         }
11918     }
11919 
11920     if (!hit) {
11921         /* background fault */
11922         fi->type = ARMFault_Background;
11923         return true;
11924     }
11925 
11926     if (matchregion == -1) {
11927         /* hit using the background region */
11928         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11929     } else {
11930         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
11931         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
11932         bool pxn = false;
11933 
11934         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
11935             pxn = extract32(env->pmsav8.rlar[secure][matchregion], 4, 1);
11936         }
11937 
11938         if (m_is_system_region(env, address)) {
11939             /* System space is always execute never */
11940             xn = 1;
11941         }
11942 
11943         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
11944         if (*prot && !xn && !(pxn && !is_user)) {
11945             *prot |= PAGE_EXEC;
11946         }
11947         /* We don't need to look the attribute up in the MAIR0/MAIR1
11948          * registers because that only tells us about cacheability.
11949          */
11950         if (mregion) {
11951             *mregion = matchregion;
11952         }
11953     }
11954 
11955     fi->type = ARMFault_Permission;
11956     fi->level = 1;
11957     return !(*prot & (1 << access_type));
11958 }
11959 
11960 
11961 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
11962                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11963                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
11964                                  int *prot, target_ulong *page_size,
11965                                  ARMMMUFaultInfo *fi)
11966 {
11967     uint32_t secure = regime_is_secure(env, mmu_idx);
11968     V8M_SAttributes sattrs = {};
11969     bool ret;
11970     bool mpu_is_subpage;
11971 
11972     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
11973         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
11974         if (access_type == MMU_INST_FETCH) {
11975             /* Instruction fetches always use the MMU bank and the
11976              * transaction attribute determined by the fetch address,
11977              * regardless of CPU state. This is painful for QEMU
11978              * to handle, because it would mean we need to encode
11979              * into the mmu_idx not just the (user, negpri) information
11980              * for the current security state but also that for the
11981              * other security state, which would balloon the number
11982              * of mmu_idx values needed alarmingly.
11983              * Fortunately we can avoid this because it's not actually
11984              * possible to arbitrarily execute code from memory with
11985              * the wrong security attribute: it will always generate
11986              * an exception of some kind or another, apart from the
11987              * special case of an NS CPU executing an SG instruction
11988              * in S&NSC memory. So we always just fail the translation
11989              * here and sort things out in the exception handler
11990              * (including possibly emulating an SG instruction).
11991              */
11992             if (sattrs.ns != !secure) {
11993                 if (sattrs.nsc) {
11994                     fi->type = ARMFault_QEMU_NSCExec;
11995                 } else {
11996                     fi->type = ARMFault_QEMU_SFault;
11997                 }
11998                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
11999                 *phys_ptr = address;
12000                 *prot = 0;
12001                 return true;
12002             }
12003         } else {
12004             /* For data accesses we always use the MMU bank indicated
12005              * by the current CPU state, but the security attributes
12006              * might downgrade a secure access to nonsecure.
12007              */
12008             if (sattrs.ns) {
12009                 txattrs->secure = false;
12010             } else if (!secure) {
12011                 /* NS access to S memory must fault.
12012                  * Architecturally we should first check whether the
12013                  * MPU information for this address indicates that we
12014                  * are doing an unaligned access to Device memory, which
12015                  * should generate a UsageFault instead. QEMU does not
12016                  * currently check for that kind of unaligned access though.
12017                  * If we added it we would need to do so as a special case
12018                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12019                  */
12020                 fi->type = ARMFault_QEMU_SFault;
12021                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12022                 *phys_ptr = address;
12023                 *prot = 0;
12024                 return true;
12025             }
12026         }
12027     }
12028 
12029     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12030                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12031     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12032     return ret;
12033 }
12034 
12035 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12036                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12037                                  hwaddr *phys_ptr, int *prot,
12038                                  ARMMMUFaultInfo *fi)
12039 {
12040     int n;
12041     uint32_t mask;
12042     uint32_t base;
12043     bool is_user = regime_is_user(env, mmu_idx);
12044 
12045     if (regime_translation_disabled(env, mmu_idx)) {
12046         /* MPU disabled.  */
12047         *phys_ptr = address;
12048         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12049         return false;
12050     }
12051 
12052     *phys_ptr = address;
12053     for (n = 7; n >= 0; n--) {
12054         base = env->cp15.c6_region[n];
12055         if ((base & 1) == 0) {
12056             continue;
12057         }
12058         mask = 1 << ((base >> 1) & 0x1f);
12059         /* Keep this shift separate from the above to avoid an
12060            (undefined) << 32.  */
12061         mask = (mask << 1) - 1;
12062         if (((base ^ address) & ~mask) == 0) {
12063             break;
12064         }
12065     }
12066     if (n < 0) {
12067         fi->type = ARMFault_Background;
12068         return true;
12069     }
12070 
12071     if (access_type == MMU_INST_FETCH) {
12072         mask = env->cp15.pmsav5_insn_ap;
12073     } else {
12074         mask = env->cp15.pmsav5_data_ap;
12075     }
12076     mask = (mask >> (n * 4)) & 0xf;
12077     switch (mask) {
12078     case 0:
12079         fi->type = ARMFault_Permission;
12080         fi->level = 1;
12081         return true;
12082     case 1:
12083         if (is_user) {
12084             fi->type = ARMFault_Permission;
12085             fi->level = 1;
12086             return true;
12087         }
12088         *prot = PAGE_READ | PAGE_WRITE;
12089         break;
12090     case 2:
12091         *prot = PAGE_READ;
12092         if (!is_user) {
12093             *prot |= PAGE_WRITE;
12094         }
12095         break;
12096     case 3:
12097         *prot = PAGE_READ | PAGE_WRITE;
12098         break;
12099     case 5:
12100         if (is_user) {
12101             fi->type = ARMFault_Permission;
12102             fi->level = 1;
12103             return true;
12104         }
12105         *prot = PAGE_READ;
12106         break;
12107     case 6:
12108         *prot = PAGE_READ;
12109         break;
12110     default:
12111         /* Bad permission.  */
12112         fi->type = ARMFault_Permission;
12113         fi->level = 1;
12114         return true;
12115     }
12116     *prot |= PAGE_EXEC;
12117     return false;
12118 }
12119 
12120 /* Combine either inner or outer cacheability attributes for normal
12121  * memory, according to table D4-42 and pseudocode procedure
12122  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12123  *
12124  * NB: only stage 1 includes allocation hints (RW bits), leading to
12125  * some asymmetry.
12126  */
12127 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12128 {
12129     if (s1 == 4 || s2 == 4) {
12130         /* non-cacheable has precedence */
12131         return 4;
12132     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12133         /* stage 1 write-through takes precedence */
12134         return s1;
12135     } else if (extract32(s2, 2, 2) == 2) {
12136         /* stage 2 write-through takes precedence, but the allocation hint
12137          * is still taken from stage 1
12138          */
12139         return (2 << 2) | extract32(s1, 0, 2);
12140     } else { /* write-back */
12141         return s1;
12142     }
12143 }
12144 
12145 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12146  * and CombineS1S2Desc()
12147  *
12148  * @s1:      Attributes from stage 1 walk
12149  * @s2:      Attributes from stage 2 walk
12150  */
12151 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
12152 {
12153     uint8_t s1lo, s2lo, s1hi, s2hi;
12154     ARMCacheAttrs ret;
12155     bool tagged = false;
12156 
12157     if (s1.attrs == 0xf0) {
12158         tagged = true;
12159         s1.attrs = 0xff;
12160     }
12161 
12162     s1lo = extract32(s1.attrs, 0, 4);
12163     s2lo = extract32(s2.attrs, 0, 4);
12164     s1hi = extract32(s1.attrs, 4, 4);
12165     s2hi = extract32(s2.attrs, 4, 4);
12166 
12167     /* Combine shareability attributes (table D4-43) */
12168     if (s1.shareability == 2 || s2.shareability == 2) {
12169         /* if either are outer-shareable, the result is outer-shareable */
12170         ret.shareability = 2;
12171     } else if (s1.shareability == 3 || s2.shareability == 3) {
12172         /* if either are inner-shareable, the result is inner-shareable */
12173         ret.shareability = 3;
12174     } else {
12175         /* both non-shareable */
12176         ret.shareability = 0;
12177     }
12178 
12179     /* Combine memory type and cacheability attributes */
12180     if (s1hi == 0 || s2hi == 0) {
12181         /* Device has precedence over normal */
12182         if (s1lo == 0 || s2lo == 0) {
12183             /* nGnRnE has precedence over anything */
12184             ret.attrs = 0;
12185         } else if (s1lo == 4 || s2lo == 4) {
12186             /* non-Reordering has precedence over Reordering */
12187             ret.attrs = 4;  /* nGnRE */
12188         } else if (s1lo == 8 || s2lo == 8) {
12189             /* non-Gathering has precedence over Gathering */
12190             ret.attrs = 8;  /* nGRE */
12191         } else {
12192             ret.attrs = 0xc; /* GRE */
12193         }
12194 
12195         /* Any location for which the resultant memory type is any
12196          * type of Device memory is always treated as Outer Shareable.
12197          */
12198         ret.shareability = 2;
12199     } else { /* Normal memory */
12200         /* Outer/inner cacheability combine independently */
12201         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12202                   | combine_cacheattr_nibble(s1lo, s2lo);
12203 
12204         if (ret.attrs == 0x44) {
12205             /* Any location for which the resultant memory type is Normal
12206              * Inner Non-cacheable, Outer Non-cacheable is always treated
12207              * as Outer Shareable.
12208              */
12209             ret.shareability = 2;
12210         }
12211     }
12212 
12213     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
12214     if (tagged && ret.attrs == 0xff) {
12215         ret.attrs = 0xf0;
12216     }
12217 
12218     return ret;
12219 }
12220 
12221 
12222 /* get_phys_addr - get the physical address for this virtual address
12223  *
12224  * Find the physical address corresponding to the given virtual address,
12225  * by doing a translation table walk on MMU based systems or using the
12226  * MPU state on MPU based systems.
12227  *
12228  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12229  * prot and page_size may not be filled in, and the populated fsr value provides
12230  * information on why the translation aborted, in the format of a
12231  * DFSR/IFSR fault register, with the following caveats:
12232  *  * we honour the short vs long DFSR format differences.
12233  *  * the WnR bit is never set (the caller must do this).
12234  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12235  *    value.
12236  *
12237  * @env: CPUARMState
12238  * @address: virtual address to get physical address for
12239  * @access_type: 0 for read, 1 for write, 2 for execute
12240  * @mmu_idx: MMU index indicating required translation regime
12241  * @phys_ptr: set to the physical address corresponding to the virtual address
12242  * @attrs: set to the memory transaction attributes to use
12243  * @prot: set to the permissions for the page containing phys_ptr
12244  * @page_size: set to the size of the page containing phys_ptr
12245  * @fi: set to fault info if the translation fails
12246  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12247  */
12248 bool get_phys_addr(CPUARMState *env, target_ulong address,
12249                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12250                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12251                    target_ulong *page_size,
12252                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12253 {
12254     ARMMMUIdx s1_mmu_idx = stage_1_mmu_idx(mmu_idx);
12255 
12256     if (mmu_idx != s1_mmu_idx) {
12257         /* Call ourselves recursively to do the stage 1 and then stage 2
12258          * translations if mmu_idx is a two-stage regime.
12259          */
12260         if (arm_feature(env, ARM_FEATURE_EL2)) {
12261             hwaddr ipa;
12262             int s2_prot;
12263             int ret;
12264             ARMCacheAttrs cacheattrs2 = {};
12265             ARMMMUIdx s2_mmu_idx;
12266             bool is_el0;
12267 
12268             ret = get_phys_addr(env, address, access_type, s1_mmu_idx, &ipa,
12269                                 attrs, prot, page_size, fi, cacheattrs);
12270 
12271             /* If S1 fails or S2 is disabled, return early.  */
12272             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
12273                 *phys_ptr = ipa;
12274                 return ret;
12275             }
12276 
12277             s2_mmu_idx = attrs->secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
12278             is_el0 = mmu_idx == ARMMMUIdx_E10_0 || mmu_idx == ARMMMUIdx_SE10_0;
12279 
12280             /* S1 is done. Now do S2 translation.  */
12281             ret = get_phys_addr_lpae(env, ipa, access_type, s2_mmu_idx, is_el0,
12282                                      phys_ptr, attrs, &s2_prot,
12283                                      page_size, fi, &cacheattrs2);
12284             fi->s2addr = ipa;
12285             /* Combine the S1 and S2 perms.  */
12286             *prot &= s2_prot;
12287 
12288             /* If S2 fails, return early.  */
12289             if (ret) {
12290                 return ret;
12291             }
12292 
12293             /* Combine the S1 and S2 cache attributes. */
12294             if (arm_hcr_el2_eff(env) & HCR_DC) {
12295                 /*
12296                  * HCR.DC forces the first stage attributes to
12297                  *  Normal Non-Shareable,
12298                  *  Inner Write-Back Read-Allocate Write-Allocate,
12299                  *  Outer Write-Back Read-Allocate Write-Allocate.
12300                  * Do not overwrite Tagged within attrs.
12301                  */
12302                 if (cacheattrs->attrs != 0xf0) {
12303                     cacheattrs->attrs = 0xff;
12304                 }
12305                 cacheattrs->shareability = 0;
12306             }
12307             *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12308 
12309             /* Check if IPA translates to secure or non-secure PA space. */
12310             if (arm_is_secure_below_el3(env)) {
12311                 if (attrs->secure) {
12312                     attrs->secure =
12313                         !(env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW));
12314                 } else {
12315                     attrs->secure =
12316                         !((env->cp15.vtcr_el2.raw_tcr & (VTCR_NSA | VTCR_NSW))
12317                         || (env->cp15.vstcr_el2.raw_tcr & VSTCR_SA));
12318                 }
12319             }
12320             return 0;
12321         } else {
12322             /*
12323              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12324              */
12325             mmu_idx = stage_1_mmu_idx(mmu_idx);
12326         }
12327     }
12328 
12329     /* The page table entries may downgrade secure to non-secure, but
12330      * cannot upgrade an non-secure translation regime's attributes
12331      * to secure.
12332      */
12333     attrs->secure = regime_is_secure(env, mmu_idx);
12334     attrs->user = regime_is_user(env, mmu_idx);
12335 
12336     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12337      * In v7 and earlier it affects all stage 1 translations.
12338      */
12339     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
12340         && !arm_feature(env, ARM_FEATURE_V8)) {
12341         if (regime_el(env, mmu_idx) == 3) {
12342             address += env->cp15.fcseidr_s;
12343         } else {
12344             address += env->cp15.fcseidr_ns;
12345         }
12346     }
12347 
12348     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12349         bool ret;
12350         *page_size = TARGET_PAGE_SIZE;
12351 
12352         if (arm_feature(env, ARM_FEATURE_V8)) {
12353             /* PMSAv8 */
12354             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12355                                        phys_ptr, attrs, prot, page_size, fi);
12356         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12357             /* PMSAv7 */
12358             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12359                                        phys_ptr, prot, page_size, fi);
12360         } else {
12361             /* Pre-v7 MPU */
12362             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12363                                        phys_ptr, prot, fi);
12364         }
12365         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12366                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12367                       access_type == MMU_DATA_LOAD ? "reading" :
12368                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12369                       (uint32_t)address, mmu_idx,
12370                       ret ? "Miss" : "Hit",
12371                       *prot & PAGE_READ ? 'r' : '-',
12372                       *prot & PAGE_WRITE ? 'w' : '-',
12373                       *prot & PAGE_EXEC ? 'x' : '-');
12374 
12375         return ret;
12376     }
12377 
12378     /* Definitely a real MMU, not an MPU */
12379 
12380     if (regime_translation_disabled(env, mmu_idx)) {
12381         uint64_t hcr;
12382         uint8_t memattr;
12383 
12384         /*
12385          * MMU disabled.  S1 addresses within aa64 translation regimes are
12386          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
12387          */
12388         if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
12389             int r_el = regime_el(env, mmu_idx);
12390             if (arm_el_is_aa64(env, r_el)) {
12391                 int pamax = arm_pamax(env_archcpu(env));
12392                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
12393                 int addrtop, tbi;
12394 
12395                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
12396                 if (access_type == MMU_INST_FETCH) {
12397                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
12398                 }
12399                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
12400                 addrtop = (tbi ? 55 : 63);
12401 
12402                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
12403                     fi->type = ARMFault_AddressSize;
12404                     fi->level = 0;
12405                     fi->stage2 = false;
12406                     return 1;
12407                 }
12408 
12409                 /*
12410                  * When TBI is disabled, we've just validated that all of the
12411                  * bits above PAMax are zero, so logically we only need to
12412                  * clear the top byte for TBI.  But it's clearer to follow
12413                  * the pseudocode set of addrdesc.paddress.
12414                  */
12415                 address = extract64(address, 0, 52);
12416             }
12417         }
12418         *phys_ptr = address;
12419         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12420         *page_size = TARGET_PAGE_SIZE;
12421 
12422         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
12423         hcr = arm_hcr_el2_eff(env);
12424         cacheattrs->shareability = 0;
12425         if (hcr & HCR_DC) {
12426             if (hcr & HCR_DCT) {
12427                 memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
12428             } else {
12429                 memattr = 0xff;  /* Normal, WB, RWA */
12430             }
12431         } else if (access_type == MMU_INST_FETCH) {
12432             if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
12433                 memattr = 0xee;  /* Normal, WT, RA, NT */
12434             } else {
12435                 memattr = 0x44;  /* Normal, NC, No */
12436             }
12437             cacheattrs->shareability = 2; /* outer sharable */
12438         } else {
12439             memattr = 0x00;      /* Device, nGnRnE */
12440         }
12441         cacheattrs->attrs = memattr;
12442         return 0;
12443     }
12444 
12445     if (regime_using_lpae_format(env, mmu_idx)) {
12446         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
12447                                   phys_ptr, attrs, prot, page_size,
12448                                   fi, cacheattrs);
12449     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12450         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12451                                 phys_ptr, attrs, prot, page_size, fi);
12452     } else {
12453         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12454                                     phys_ptr, prot, page_size, fi);
12455     }
12456 }
12457 
12458 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12459                                          MemTxAttrs *attrs)
12460 {
12461     ARMCPU *cpu = ARM_CPU(cs);
12462     CPUARMState *env = &cpu->env;
12463     hwaddr phys_addr;
12464     target_ulong page_size;
12465     int prot;
12466     bool ret;
12467     ARMMMUFaultInfo fi = {};
12468     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12469     ARMCacheAttrs cacheattrs = {};
12470 
12471     *attrs = (MemTxAttrs) {};
12472 
12473     ret = get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &phys_addr,
12474                         attrs, &prot, &page_size, &fi, &cacheattrs);
12475 
12476     if (ret) {
12477         return -1;
12478     }
12479     return phys_addr;
12480 }
12481 
12482 #endif
12483 
12484 /* Note that signed overflow is undefined in C.  The following routines are
12485    careful to use unsigned types where modulo arithmetic is required.
12486    Failure to do so _will_ break on newer gcc.  */
12487 
12488 /* Signed saturating arithmetic.  */
12489 
12490 /* Perform 16-bit signed saturating addition.  */
12491 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
12492 {
12493     uint16_t res;
12494 
12495     res = a + b;
12496     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
12497         if (a & 0x8000)
12498             res = 0x8000;
12499         else
12500             res = 0x7fff;
12501     }
12502     return res;
12503 }
12504 
12505 /* Perform 8-bit signed saturating addition.  */
12506 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
12507 {
12508     uint8_t res;
12509 
12510     res = a + b;
12511     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
12512         if (a & 0x80)
12513             res = 0x80;
12514         else
12515             res = 0x7f;
12516     }
12517     return res;
12518 }
12519 
12520 /* Perform 16-bit signed saturating subtraction.  */
12521 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
12522 {
12523     uint16_t res;
12524 
12525     res = a - b;
12526     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
12527         if (a & 0x8000)
12528             res = 0x8000;
12529         else
12530             res = 0x7fff;
12531     }
12532     return res;
12533 }
12534 
12535 /* Perform 8-bit signed saturating subtraction.  */
12536 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
12537 {
12538     uint8_t res;
12539 
12540     res = a - b;
12541     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
12542         if (a & 0x80)
12543             res = 0x80;
12544         else
12545             res = 0x7f;
12546     }
12547     return res;
12548 }
12549 
12550 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
12551 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
12552 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
12553 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
12554 #define PFX q
12555 
12556 #include "op_addsub.h"
12557 
12558 /* Unsigned saturating arithmetic.  */
12559 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
12560 {
12561     uint16_t res;
12562     res = a + b;
12563     if (res < a)
12564         res = 0xffff;
12565     return res;
12566 }
12567 
12568 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
12569 {
12570     if (a > b)
12571         return a - b;
12572     else
12573         return 0;
12574 }
12575 
12576 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
12577 {
12578     uint8_t res;
12579     res = a + b;
12580     if (res < a)
12581         res = 0xff;
12582     return res;
12583 }
12584 
12585 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
12586 {
12587     if (a > b)
12588         return a - b;
12589     else
12590         return 0;
12591 }
12592 
12593 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
12594 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
12595 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
12596 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
12597 #define PFX uq
12598 
12599 #include "op_addsub.h"
12600 
12601 /* Signed modulo arithmetic.  */
12602 #define SARITH16(a, b, n, op) do { \
12603     int32_t sum; \
12604     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
12605     RESULT(sum, n, 16); \
12606     if (sum >= 0) \
12607         ge |= 3 << (n * 2); \
12608     } while(0)
12609 
12610 #define SARITH8(a, b, n, op) do { \
12611     int32_t sum; \
12612     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
12613     RESULT(sum, n, 8); \
12614     if (sum >= 0) \
12615         ge |= 1 << n; \
12616     } while(0)
12617 
12618 
12619 #define ADD16(a, b, n) SARITH16(a, b, n, +)
12620 #define SUB16(a, b, n) SARITH16(a, b, n, -)
12621 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
12622 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
12623 #define PFX s
12624 #define ARITH_GE
12625 
12626 #include "op_addsub.h"
12627 
12628 /* Unsigned modulo arithmetic.  */
12629 #define ADD16(a, b, n) do { \
12630     uint32_t sum; \
12631     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
12632     RESULT(sum, n, 16); \
12633     if ((sum >> 16) == 1) \
12634         ge |= 3 << (n * 2); \
12635     } while(0)
12636 
12637 #define ADD8(a, b, n) do { \
12638     uint32_t sum; \
12639     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
12640     RESULT(sum, n, 8); \
12641     if ((sum >> 8) == 1) \
12642         ge |= 1 << n; \
12643     } while(0)
12644 
12645 #define SUB16(a, b, n) do { \
12646     uint32_t sum; \
12647     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
12648     RESULT(sum, n, 16); \
12649     if ((sum >> 16) == 0) \
12650         ge |= 3 << (n * 2); \
12651     } while(0)
12652 
12653 #define SUB8(a, b, n) do { \
12654     uint32_t sum; \
12655     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
12656     RESULT(sum, n, 8); \
12657     if ((sum >> 8) == 0) \
12658         ge |= 1 << n; \
12659     } while(0)
12660 
12661 #define PFX u
12662 #define ARITH_GE
12663 
12664 #include "op_addsub.h"
12665 
12666 /* Halved signed arithmetic.  */
12667 #define ADD16(a, b, n) \
12668   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
12669 #define SUB16(a, b, n) \
12670   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
12671 #define ADD8(a, b, n) \
12672   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
12673 #define SUB8(a, b, n) \
12674   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
12675 #define PFX sh
12676 
12677 #include "op_addsub.h"
12678 
12679 /* Halved unsigned arithmetic.  */
12680 #define ADD16(a, b, n) \
12681   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12682 #define SUB16(a, b, n) \
12683   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12684 #define ADD8(a, b, n) \
12685   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12686 #define SUB8(a, b, n) \
12687   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12688 #define PFX uh
12689 
12690 #include "op_addsub.h"
12691 
12692 static inline uint8_t do_usad(uint8_t a, uint8_t b)
12693 {
12694     if (a > b)
12695         return a - b;
12696     else
12697         return b - a;
12698 }
12699 
12700 /* Unsigned sum of absolute byte differences.  */
12701 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
12702 {
12703     uint32_t sum;
12704     sum = do_usad(a, b);
12705     sum += do_usad(a >> 8, b >> 8);
12706     sum += do_usad(a >> 16, b >> 16);
12707     sum += do_usad(a >> 24, b >> 24);
12708     return sum;
12709 }
12710 
12711 /* For ARMv6 SEL instruction.  */
12712 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
12713 {
12714     uint32_t mask;
12715 
12716     mask = 0;
12717     if (flags & 1)
12718         mask |= 0xff;
12719     if (flags & 2)
12720         mask |= 0xff00;
12721     if (flags & 4)
12722         mask |= 0xff0000;
12723     if (flags & 8)
12724         mask |= 0xff000000;
12725     return (a & mask) | (b & ~mask);
12726 }
12727 
12728 /* CRC helpers.
12729  * The upper bytes of val (above the number specified by 'bytes') must have
12730  * been zeroed out by the caller.
12731  */
12732 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12733 {
12734     uint8_t buf[4];
12735 
12736     stl_le_p(buf, val);
12737 
12738     /* zlib crc32 converts the accumulator and output to one's complement.  */
12739     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12740 }
12741 
12742 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12743 {
12744     uint8_t buf[4];
12745 
12746     stl_le_p(buf, val);
12747 
12748     /* Linux crc32c converts the output to one's complement.  */
12749     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12750 }
12751 
12752 /* Return the exception level to which FP-disabled exceptions should
12753  * be taken, or 0 if FP is enabled.
12754  */
12755 int fp_exception_el(CPUARMState *env, int cur_el)
12756 {
12757 #ifndef CONFIG_USER_ONLY
12758     /* CPACR and the CPTR registers don't exist before v6, so FP is
12759      * always accessible
12760      */
12761     if (!arm_feature(env, ARM_FEATURE_V6)) {
12762         return 0;
12763     }
12764 
12765     if (arm_feature(env, ARM_FEATURE_M)) {
12766         /* CPACR can cause a NOCP UsageFault taken to current security state */
12767         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
12768             return 1;
12769         }
12770 
12771         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
12772             if (!extract32(env->v7m.nsacr, 10, 1)) {
12773                 /* FP insns cause a NOCP UsageFault taken to Secure */
12774                 return 3;
12775             }
12776         }
12777 
12778         return 0;
12779     }
12780 
12781     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12782      * 0, 2 : trap EL0 and EL1/PL1 accesses
12783      * 1    : trap only EL0 accesses
12784      * 3    : trap no accesses
12785      * This register is ignored if E2H+TGE are both set.
12786      */
12787     if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
12788         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12789 
12790         switch (fpen) {
12791         case 0:
12792         case 2:
12793             if (cur_el == 0 || cur_el == 1) {
12794                 /* Trap to PL1, which might be EL1 or EL3 */
12795                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12796                     return 3;
12797                 }
12798                 return 1;
12799             }
12800             if (cur_el == 3 && !is_a64(env)) {
12801                 /* Secure PL1 running at EL3 */
12802                 return 3;
12803             }
12804             break;
12805         case 1:
12806             if (cur_el == 0) {
12807                 return 1;
12808             }
12809             break;
12810         case 3:
12811             break;
12812         }
12813     }
12814 
12815     /*
12816      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
12817      * to control non-secure access to the FPU. It doesn't have any
12818      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
12819      */
12820     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
12821          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
12822         if (!extract32(env->cp15.nsacr, 10, 1)) {
12823             /* FP insns act as UNDEF */
12824             return cur_el == 2 ? 2 : 1;
12825         }
12826     }
12827 
12828     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12829      * check because zero bits in the registers mean "don't trap".
12830      */
12831 
12832     /* CPTR_EL2 : present in v7VE or v8 */
12833     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12834         && arm_is_el2_enabled(env)) {
12835         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12836         return 2;
12837     }
12838 
12839     /* CPTR_EL3 : present in v8 */
12840     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12841         /* Trap all FP ops to EL3 */
12842         return 3;
12843     }
12844 #endif
12845     return 0;
12846 }
12847 
12848 /* Return the exception level we're running at if this is our mmu_idx */
12849 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
12850 {
12851     if (mmu_idx & ARM_MMU_IDX_M) {
12852         return mmu_idx & ARM_MMU_IDX_M_PRIV;
12853     }
12854 
12855     switch (mmu_idx) {
12856     case ARMMMUIdx_E10_0:
12857     case ARMMMUIdx_E20_0:
12858     case ARMMMUIdx_SE10_0:
12859     case ARMMMUIdx_SE20_0:
12860         return 0;
12861     case ARMMMUIdx_E10_1:
12862     case ARMMMUIdx_E10_1_PAN:
12863     case ARMMMUIdx_SE10_1:
12864     case ARMMMUIdx_SE10_1_PAN:
12865         return 1;
12866     case ARMMMUIdx_E2:
12867     case ARMMMUIdx_E20_2:
12868     case ARMMMUIdx_E20_2_PAN:
12869     case ARMMMUIdx_SE2:
12870     case ARMMMUIdx_SE20_2:
12871     case ARMMMUIdx_SE20_2_PAN:
12872         return 2;
12873     case ARMMMUIdx_SE3:
12874         return 3;
12875     default:
12876         g_assert_not_reached();
12877     }
12878 }
12879 
12880 #ifndef CONFIG_TCG
12881 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
12882 {
12883     g_assert_not_reached();
12884 }
12885 #endif
12886 
12887 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
12888 {
12889     ARMMMUIdx idx;
12890     uint64_t hcr;
12891 
12892     if (arm_feature(env, ARM_FEATURE_M)) {
12893         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
12894     }
12895 
12896     /* See ARM pseudo-function ELIsInHost.  */
12897     switch (el) {
12898     case 0:
12899         hcr = arm_hcr_el2_eff(env);
12900         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
12901             idx = ARMMMUIdx_E20_0;
12902         } else {
12903             idx = ARMMMUIdx_E10_0;
12904         }
12905         break;
12906     case 1:
12907         if (env->pstate & PSTATE_PAN) {
12908             idx = ARMMMUIdx_E10_1_PAN;
12909         } else {
12910             idx = ARMMMUIdx_E10_1;
12911         }
12912         break;
12913     case 2:
12914         /* Note that TGE does not apply at EL2.  */
12915         if (arm_hcr_el2_eff(env) & HCR_E2H) {
12916             if (env->pstate & PSTATE_PAN) {
12917                 idx = ARMMMUIdx_E20_2_PAN;
12918             } else {
12919                 idx = ARMMMUIdx_E20_2;
12920             }
12921         } else {
12922             idx = ARMMMUIdx_E2;
12923         }
12924         break;
12925     case 3:
12926         return ARMMMUIdx_SE3;
12927     default:
12928         g_assert_not_reached();
12929     }
12930 
12931     if (arm_is_secure_below_el3(env)) {
12932         idx &= ~ARM_MMU_IDX_A_NS;
12933     }
12934 
12935     return idx;
12936 }
12937 
12938 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
12939 {
12940     return arm_mmu_idx_el(env, arm_current_el(env));
12941 }
12942 
12943 #ifndef CONFIG_USER_ONLY
12944 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
12945 {
12946     return stage_1_mmu_idx(arm_mmu_idx(env));
12947 }
12948 #endif
12949 
12950 static uint32_t rebuild_hflags_common(CPUARMState *env, int fp_el,
12951                                       ARMMMUIdx mmu_idx, uint32_t flags)
12952 {
12953     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
12954     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX,
12955                        arm_to_core_mmu_idx(mmu_idx));
12956 
12957     if (arm_singlestep_active(env)) {
12958         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
12959     }
12960     return flags;
12961 }
12962 
12963 static uint32_t rebuild_hflags_common_32(CPUARMState *env, int fp_el,
12964                                          ARMMMUIdx mmu_idx, uint32_t flags)
12965 {
12966     bool sctlr_b = arm_sctlr_b(env);
12967 
12968     if (sctlr_b) {
12969         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, 1);
12970     }
12971     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
12972         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
12973     }
12974     flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
12975 
12976     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
12977 }
12978 
12979 static uint32_t rebuild_hflags_m32(CPUARMState *env, int fp_el,
12980                                    ARMMMUIdx mmu_idx)
12981 {
12982     uint32_t flags = 0;
12983 
12984     if (arm_v7m_is_handler_mode(env)) {
12985         flags = FIELD_DP32(flags, TBFLAG_M32, HANDLER, 1);
12986     }
12987 
12988     /*
12989      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
12990      * is suppressing them because the requested execution priority
12991      * is less than 0.
12992      */
12993     if (arm_feature(env, ARM_FEATURE_V8) &&
12994         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
12995           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
12996         flags = FIELD_DP32(flags, TBFLAG_M32, STACKCHECK, 1);
12997     }
12998 
12999     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13000 }
13001 
13002 static uint32_t rebuild_hflags_aprofile(CPUARMState *env)
13003 {
13004     int flags = 0;
13005 
13006     flags = FIELD_DP32(flags, TBFLAG_ANY, DEBUG_TARGET_EL,
13007                        arm_debug_target_el(env));
13008     return flags;
13009 }
13010 
13011 static uint32_t rebuild_hflags_a32(CPUARMState *env, int fp_el,
13012                                    ARMMMUIdx mmu_idx)
13013 {
13014     uint32_t flags = rebuild_hflags_aprofile(env);
13015 
13016     if (arm_el_is_aa64(env, 1)) {
13017         flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
13018     }
13019 
13020     if (arm_current_el(env) < 2 && env->cp15.hstr_el2 &&
13021         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13022         flags = FIELD_DP32(flags, TBFLAG_A32, HSTR_ACTIVE, 1);
13023     }
13024 
13025     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13026 }
13027 
13028 static uint32_t rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
13029                                    ARMMMUIdx mmu_idx)
13030 {
13031     uint32_t flags = rebuild_hflags_aprofile(env);
13032     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13033     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
13034     uint64_t sctlr;
13035     int tbii, tbid;
13036 
13037     flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
13038 
13039     /* Get control bits for tagged addresses.  */
13040     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
13041     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
13042 
13043     flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
13044     flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
13045 
13046     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
13047         int sve_el = sve_exception_el(env, el);
13048         uint32_t zcr_len;
13049 
13050         /*
13051          * If SVE is disabled, but FP is enabled,
13052          * then the effective len is 0.
13053          */
13054         if (sve_el != 0 && fp_el == 0) {
13055             zcr_len = 0;
13056         } else {
13057             zcr_len = sve_zcr_len_for_el(env, el);
13058         }
13059         flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
13060         flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
13061     }
13062 
13063     sctlr = regime_sctlr(env, stage1);
13064 
13065     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
13066         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
13067     }
13068 
13069     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
13070         /*
13071          * In order to save space in flags, we record only whether
13072          * pauth is "inactive", meaning all insns are implemented as
13073          * a nop, or "active" when some action must be performed.
13074          * The decision of which action to take is left to a helper.
13075          */
13076         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13077             flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
13078         }
13079     }
13080 
13081     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13082         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13083         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13084             flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
13085         }
13086     }
13087 
13088     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
13089     if (!(env->pstate & PSTATE_UAO)) {
13090         switch (mmu_idx) {
13091         case ARMMMUIdx_E10_1:
13092         case ARMMMUIdx_E10_1_PAN:
13093         case ARMMMUIdx_SE10_1:
13094         case ARMMMUIdx_SE10_1_PAN:
13095             /* TODO: ARMv8.3-NV */
13096             flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
13097             break;
13098         case ARMMMUIdx_E20_2:
13099         case ARMMMUIdx_E20_2_PAN:
13100         case ARMMMUIdx_SE20_2:
13101         case ARMMMUIdx_SE20_2_PAN:
13102             /*
13103              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
13104              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
13105              */
13106             if (env->cp15.hcr_el2 & HCR_TGE) {
13107                 flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
13108             }
13109             break;
13110         default:
13111             break;
13112         }
13113     }
13114 
13115     if (cpu_isar_feature(aa64_mte, env_archcpu(env))) {
13116         /*
13117          * Set MTE_ACTIVE if any access may be Checked, and leave clear
13118          * if all accesses must be Unchecked:
13119          * 1) If no TBI, then there are no tags in the address to check,
13120          * 2) If Tag Check Override, then all accesses are Unchecked,
13121          * 3) If Tag Check Fail == 0, then Checked access have no effect,
13122          * 4) If no Allocation Tag Access, then all accesses are Unchecked.
13123          */
13124         if (allocation_tag_access_enabled(env, el, sctlr)) {
13125             flags = FIELD_DP32(flags, TBFLAG_A64, ATA, 1);
13126             if (tbid
13127                 && !(env->pstate & PSTATE_TCO)
13128                 && (sctlr & (el == 0 ? SCTLR_TCF0 : SCTLR_TCF))) {
13129                 flags = FIELD_DP32(flags, TBFLAG_A64, MTE_ACTIVE, 1);
13130             }
13131         }
13132         /* And again for unprivileged accesses, if required.  */
13133         if (FIELD_EX32(flags, TBFLAG_A64, UNPRIV)
13134             && tbid
13135             && !(env->pstate & PSTATE_TCO)
13136             && (sctlr & SCTLR_TCF)
13137             && allocation_tag_access_enabled(env, 0, sctlr)) {
13138             flags = FIELD_DP32(flags, TBFLAG_A64, MTE0_ACTIVE, 1);
13139         }
13140         /* Cache TCMA as well as TBI. */
13141         flags = FIELD_DP32(flags, TBFLAG_A64, TCMA,
13142                            aa64_va_parameter_tcma(tcr, mmu_idx));
13143     }
13144 
13145     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13146 }
13147 
13148 static uint32_t rebuild_hflags_internal(CPUARMState *env)
13149 {
13150     int el = arm_current_el(env);
13151     int fp_el = fp_exception_el(env, el);
13152     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13153 
13154     if (is_a64(env)) {
13155         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13156     } else if (arm_feature(env, ARM_FEATURE_M)) {
13157         return rebuild_hflags_m32(env, fp_el, mmu_idx);
13158     } else {
13159         return rebuild_hflags_a32(env, fp_el, mmu_idx);
13160     }
13161 }
13162 
13163 void arm_rebuild_hflags(CPUARMState *env)
13164 {
13165     env->hflags = rebuild_hflags_internal(env);
13166 }
13167 
13168 /*
13169  * If we have triggered a EL state change we can't rely on the
13170  * translator having passed it to us, we need to recompute.
13171  */
13172 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
13173 {
13174     int el = arm_current_el(env);
13175     int fp_el = fp_exception_el(env, el);
13176     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13177     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13178 }
13179 
13180 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
13181 {
13182     int fp_el = fp_exception_el(env, el);
13183     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13184 
13185     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13186 }
13187 
13188 /*
13189  * If we have triggered a EL state change we can't rely on the
13190  * translator having passed it to us, we need to recompute.
13191  */
13192 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
13193 {
13194     int el = arm_current_el(env);
13195     int fp_el = fp_exception_el(env, el);
13196     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13197     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13198 }
13199 
13200 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
13201 {
13202     int fp_el = fp_exception_el(env, el);
13203     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13204 
13205     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13206 }
13207 
13208 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
13209 {
13210     int fp_el = fp_exception_el(env, el);
13211     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13212 
13213     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13214 }
13215 
13216 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
13217 {
13218 #ifdef CONFIG_DEBUG_TCG
13219     uint32_t env_flags_current = env->hflags;
13220     uint32_t env_flags_rebuilt = rebuild_hflags_internal(env);
13221 
13222     if (unlikely(env_flags_current != env_flags_rebuilt)) {
13223         fprintf(stderr, "TCG hflags mismatch (current:0x%08x rebuilt:0x%08x)\n",
13224                 env_flags_current, env_flags_rebuilt);
13225         abort();
13226     }
13227 #endif
13228 }
13229 
13230 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13231                           target_ulong *cs_base, uint32_t *pflags)
13232 {
13233     uint32_t flags = env->hflags;
13234 
13235     *cs_base = 0;
13236     assert_hflags_rebuild_correctly(env);
13237 
13238     if (FIELD_EX32(flags, TBFLAG_ANY, AARCH64_STATE)) {
13239         *pc = env->pc;
13240         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13241             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
13242         }
13243     } else {
13244         *pc = env->regs[15];
13245 
13246         if (arm_feature(env, ARM_FEATURE_M)) {
13247             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13248                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
13249                 != env->v7m.secure) {
13250                 flags = FIELD_DP32(flags, TBFLAG_M32, FPCCR_S_WRONG, 1);
13251             }
13252 
13253             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13254                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13255                  (env->v7m.secure &&
13256                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13257                 /*
13258                  * ASPEN is set, but FPCA/SFPA indicate that there is no
13259                  * active FP context; we must create a new FP context before
13260                  * executing any FP insn.
13261                  */
13262                 flags = FIELD_DP32(flags, TBFLAG_M32, NEW_FP_CTXT_NEEDED, 1);
13263             }
13264 
13265             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13266             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13267                 flags = FIELD_DP32(flags, TBFLAG_M32, LSPACT, 1);
13268             }
13269         } else {
13270             /*
13271              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
13272              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
13273              */
13274             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13275                 flags = FIELD_DP32(flags, TBFLAG_A32,
13276                                    XSCALE_CPAR, env->cp15.c15_cpar);
13277             } else {
13278                 flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN,
13279                                    env->vfp.vec_len);
13280                 flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE,
13281                                    env->vfp.vec_stride);
13282             }
13283             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
13284                 flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
13285             }
13286         }
13287 
13288         flags = FIELD_DP32(flags, TBFLAG_AM32, THUMB, env->thumb);
13289         flags = FIELD_DP32(flags, TBFLAG_AM32, CONDEXEC, env->condexec_bits);
13290     }
13291 
13292     /*
13293      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13294      * states defined in the ARM ARM for software singlestep:
13295      *  SS_ACTIVE   PSTATE.SS   State
13296      *     0            x       Inactive (the TB flag for SS is always 0)
13297      *     1            0       Active-pending
13298      *     1            1       Active-not-pending
13299      * SS_ACTIVE is set in hflags; PSTATE_SS is computed every TB.
13300      */
13301     if (FIELD_EX32(flags, TBFLAG_ANY, SS_ACTIVE) &&
13302         (env->pstate & PSTATE_SS)) {
13303         flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
13304     }
13305 
13306     *pflags = flags;
13307 }
13308 
13309 #ifdef TARGET_AARCH64
13310 /*
13311  * The manual says that when SVE is enabled and VQ is widened the
13312  * implementation is allowed to zero the previously inaccessible
13313  * portion of the registers.  The corollary to that is that when
13314  * SVE is enabled and VQ is narrowed we are also allowed to zero
13315  * the now inaccessible portion of the registers.
13316  *
13317  * The intent of this is that no predicate bit beyond VQ is ever set.
13318  * Which means that some operations on predicate registers themselves
13319  * may operate on full uint64_t or even unrolled across the maximum
13320  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13321  * may well be cheaper than conditionals to restrict the operation
13322  * to the relevant portion of a uint16_t[16].
13323  */
13324 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13325 {
13326     int i, j;
13327     uint64_t pmask;
13328 
13329     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13330     assert(vq <= env_archcpu(env)->sve_max_vq);
13331 
13332     /* Zap the high bits of the zregs.  */
13333     for (i = 0; i < 32; i++) {
13334         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13335     }
13336 
13337     /* Zap the high bits of the pregs and ffr.  */
13338     pmask = 0;
13339     if (vq & 3) {
13340         pmask = ~(-1ULL << (16 * (vq & 3)));
13341     }
13342     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13343         for (i = 0; i < 17; ++i) {
13344             env->vfp.pregs[i].p[j] &= pmask;
13345         }
13346         pmask = 0;
13347     }
13348 }
13349 
13350 /*
13351  * Notice a change in SVE vector size when changing EL.
13352  */
13353 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13354                            int new_el, bool el0_a64)
13355 {
13356     ARMCPU *cpu = env_archcpu(env);
13357     int old_len, new_len;
13358     bool old_a64, new_a64;
13359 
13360     /* Nothing to do if no SVE.  */
13361     if (!cpu_isar_feature(aa64_sve, cpu)) {
13362         return;
13363     }
13364 
13365     /* Nothing to do if FP is disabled in either EL.  */
13366     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13367         return;
13368     }
13369 
13370     /*
13371      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13372      * at ELx, or not available because the EL is in AArch32 state, then
13373      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13374      * has an effective value of 0".
13375      *
13376      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13377      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13378      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13379      * we already have the correct register contents when encountering the
13380      * vq0->vq0 transition between EL0->EL1.
13381      */
13382     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13383     old_len = (old_a64 && !sve_exception_el(env, old_el)
13384                ? sve_zcr_len_for_el(env, old_el) : 0);
13385     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13386     new_len = (new_a64 && !sve_exception_el(env, new_el)
13387                ? sve_zcr_len_for_el(env, new_el) : 0);
13388 
13389     /* When changing vector length, clear inaccessible state.  */
13390     if (new_len < old_len) {
13391         aarch64_sve_narrow_vq(env, new_len + 1);
13392     }
13393 }
13394 #endif
13395