xref: /openbmc/qemu/target/arm/helper.c (revision 831734cc)
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 
42 #ifndef CONFIG_USER_ONLY
43 
44 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
45                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
46                                bool s1_is_el0,
47                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
48                                target_ulong *page_size_ptr,
49                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
50     __attribute__((nonnull));
51 #endif
52 
53 static void switch_mode(CPUARMState *env, int mode);
54 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx);
55 
56 static int vfp_gdb_get_reg(CPUARMState *env, GByteArray *buf, int reg)
57 {
58     ARMCPU *cpu = env_archcpu(env);
59     int nregs = cpu_isar_feature(aa32_simd_r32, cpu) ? 32 : 16;
60 
61     /* VFP data registers are always little-endian.  */
62     if (reg < nregs) {
63         return gdb_get_reg64(buf, *aa32_vfp_dreg(env, reg));
64     }
65     if (arm_feature(env, ARM_FEATURE_NEON)) {
66         /* Aliases for Q regs.  */
67         nregs += 16;
68         if (reg < nregs) {
69             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
70             return gdb_get_reg128(buf, q[0], q[1]);
71         }
72     }
73     switch (reg - nregs) {
74     case 0: return gdb_get_reg32(buf, env->vfp.xregs[ARM_VFP_FPSID]); break;
75     case 1: return gdb_get_reg32(buf, vfp_get_fpscr(env)); break;
76     case 2: return gdb_get_reg32(buf, env->vfp.xregs[ARM_VFP_FPEXC]); break;
77     }
78     return 0;
79 }
80 
81 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
82 {
83     ARMCPU *cpu = env_archcpu(env);
84     int nregs = cpu_isar_feature(aa32_simd_r32, cpu) ? 32 : 16;
85 
86     if (reg < nregs) {
87         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
88         return 8;
89     }
90     if (arm_feature(env, ARM_FEATURE_NEON)) {
91         nregs += 16;
92         if (reg < nregs) {
93             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
94             q[0] = ldq_le_p(buf);
95             q[1] = ldq_le_p(buf + 8);
96             return 16;
97         }
98     }
99     switch (reg - nregs) {
100     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
101     case 1: vfp_set_fpscr(env, ldl_p(buf)); return 4;
102     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
103     }
104     return 0;
105 }
106 
107 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, GByteArray *buf, int reg)
108 {
109     switch (reg) {
110     case 0 ... 31:
111     {
112         /* 128 bit FP register - quads are in LE order */
113         uint64_t *q = aa64_vfp_qreg(env, reg);
114         return gdb_get_reg128(buf, q[1], q[0]);
115     }
116     case 32:
117         /* FPSR */
118         return gdb_get_reg32(buf, vfp_get_fpsr(env));
119     case 33:
120         /* FPCR */
121         return gdb_get_reg32(buf,vfp_get_fpcr(env));
122     default:
123         return 0;
124     }
125 }
126 
127 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
128 {
129     switch (reg) {
130     case 0 ... 31:
131         /* 128 bit FP register */
132         {
133             uint64_t *q = aa64_vfp_qreg(env, reg);
134             q[0] = ldq_le_p(buf);
135             q[1] = ldq_le_p(buf + 8);
136             return 16;
137         }
138     case 32:
139         /* FPSR */
140         vfp_set_fpsr(env, ldl_p(buf));
141         return 4;
142     case 33:
143         /* FPCR */
144         vfp_set_fpcr(env, ldl_p(buf));
145         return 4;
146     default:
147         return 0;
148     }
149 }
150 
151 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
152 {
153     assert(ri->fieldoffset);
154     if (cpreg_field_is_64bit(ri)) {
155         return CPREG_FIELD64(env, ri);
156     } else {
157         return CPREG_FIELD32(env, ri);
158     }
159 }
160 
161 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
162                       uint64_t value)
163 {
164     assert(ri->fieldoffset);
165     if (cpreg_field_is_64bit(ri)) {
166         CPREG_FIELD64(env, ri) = value;
167     } else {
168         CPREG_FIELD32(env, ri) = value;
169     }
170 }
171 
172 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
173 {
174     return (char *)env + ri->fieldoffset;
175 }
176 
177 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
178 {
179     /* Raw read of a coprocessor register (as needed for migration, etc). */
180     if (ri->type & ARM_CP_CONST) {
181         return ri->resetvalue;
182     } else if (ri->raw_readfn) {
183         return ri->raw_readfn(env, ri);
184     } else if (ri->readfn) {
185         return ri->readfn(env, ri);
186     } else {
187         return raw_read(env, ri);
188     }
189 }
190 
191 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
192                              uint64_t v)
193 {
194     /* Raw write of a coprocessor register (as needed for migration, etc).
195      * Note that constant registers are treated as write-ignored; the
196      * caller should check for success by whether a readback gives the
197      * value written.
198      */
199     if (ri->type & ARM_CP_CONST) {
200         return;
201     } else if (ri->raw_writefn) {
202         ri->raw_writefn(env, ri, v);
203     } else if (ri->writefn) {
204         ri->writefn(env, ri, v);
205     } else {
206         raw_write(env, ri, v);
207     }
208 }
209 
210 /**
211  * arm_get/set_gdb_*: get/set a gdb register
212  * @env: the CPU state
213  * @buf: a buffer to copy to/from
214  * @reg: register number (offset from start of group)
215  *
216  * We return the number of bytes copied
217  */
218 
219 static int arm_gdb_get_sysreg(CPUARMState *env, GByteArray *buf, int reg)
220 {
221     ARMCPU *cpu = env_archcpu(env);
222     const ARMCPRegInfo *ri;
223     uint32_t key;
224 
225     key = cpu->dyn_sysreg_xml.data.cpregs.keys[reg];
226     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
227     if (ri) {
228         if (cpreg_field_is_64bit(ri)) {
229             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
230         } else {
231             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
232         }
233     }
234     return 0;
235 }
236 
237 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
238 {
239     return 0;
240 }
241 
242 #ifdef TARGET_AARCH64
243 static int arm_gdb_get_svereg(CPUARMState *env, GByteArray *buf, int reg)
244 {
245     ARMCPU *cpu = env_archcpu(env);
246 
247     switch (reg) {
248     /* The first 32 registers are the zregs */
249     case 0 ... 31:
250     {
251         int vq, len = 0;
252         for (vq = 0; vq < cpu->sve_max_vq; vq++) {
253             len += gdb_get_reg128(buf,
254                                   env->vfp.zregs[reg].d[vq * 2 + 1],
255                                   env->vfp.zregs[reg].d[vq * 2]);
256         }
257         return len;
258     }
259     case 32:
260         return gdb_get_reg32(buf, vfp_get_fpsr(env));
261     case 33:
262         return gdb_get_reg32(buf, vfp_get_fpcr(env));
263     /* then 16 predicates and the ffr */
264     case 34 ... 50:
265     {
266         int preg = reg - 34;
267         int vq, len = 0;
268         for (vq = 0; vq < cpu->sve_max_vq; vq = vq + 4) {
269             len += gdb_get_reg64(buf, env->vfp.pregs[preg].p[vq / 4]);
270         }
271         return len;
272     }
273     case 51:
274     {
275         /*
276          * We report in Vector Granules (VG) which is 64bit in a Z reg
277          * while the ZCR works in Vector Quads (VQ) which is 128bit chunks.
278          */
279         int vq = sve_zcr_len_for_el(env, arm_current_el(env)) + 1;
280         return gdb_get_reg64(buf, vq * 2);
281     }
282     default:
283         /* gdbstub asked for something out our range */
284         qemu_log_mask(LOG_UNIMP, "%s: out of range register %d", __func__, reg);
285         break;
286     }
287 
288     return 0;
289 }
290 
291 static int arm_gdb_set_svereg(CPUARMState *env, uint8_t *buf, int reg)
292 {
293     ARMCPU *cpu = env_archcpu(env);
294 
295     /* The first 32 registers are the zregs */
296     switch (reg) {
297     /* The first 32 registers are the zregs */
298     case 0 ... 31:
299     {
300         int vq, len = 0;
301         uint64_t *p = (uint64_t *) buf;
302         for (vq = 0; vq < cpu->sve_max_vq; vq++) {
303             env->vfp.zregs[reg].d[vq * 2 + 1] = *p++;
304             env->vfp.zregs[reg].d[vq * 2] = *p++;
305             len += 16;
306         }
307         return len;
308     }
309     case 32:
310         vfp_set_fpsr(env, *(uint32_t *)buf);
311         return 4;
312     case 33:
313         vfp_set_fpcr(env, *(uint32_t *)buf);
314         return 4;
315     case 34 ... 50:
316     {
317         int preg = reg - 34;
318         int vq, len = 0;
319         uint64_t *p = (uint64_t *) buf;
320         for (vq = 0; vq < cpu->sve_max_vq; vq = vq + 4) {
321             env->vfp.pregs[preg].p[vq / 4] = *p++;
322             len += 8;
323         }
324         return len;
325     }
326     case 51:
327         /* cannot set vg via gdbstub */
328         return 0;
329     default:
330         /* gdbstub asked for something out our range */
331         break;
332     }
333 
334     return 0;
335 }
336 #endif /* TARGET_AARCH64 */
337 
338 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
339 {
340    /* Return true if the regdef would cause an assertion if you called
341     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
342     * program bug for it not to have the NO_RAW flag).
343     * NB that returning false here doesn't necessarily mean that calling
344     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
345     * read/write access functions which are safe for raw use" from "has
346     * read/write access functions which have side effects but has forgotten
347     * to provide raw access functions".
348     * The tests here line up with the conditions in read/write_raw_cp_reg()
349     * and assertions in raw_read()/raw_write().
350     */
351     if ((ri->type & ARM_CP_CONST) ||
352         ri->fieldoffset ||
353         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
354         return false;
355     }
356     return true;
357 }
358 
359 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
360 {
361     /* Write the coprocessor state from cpu->env to the (index,value) list. */
362     int i;
363     bool ok = true;
364 
365     for (i = 0; i < cpu->cpreg_array_len; i++) {
366         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
367         const ARMCPRegInfo *ri;
368         uint64_t newval;
369 
370         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
371         if (!ri) {
372             ok = false;
373             continue;
374         }
375         if (ri->type & ARM_CP_NO_RAW) {
376             continue;
377         }
378 
379         newval = read_raw_cp_reg(&cpu->env, ri);
380         if (kvm_sync) {
381             /*
382              * Only sync if the previous list->cpustate sync succeeded.
383              * Rather than tracking the success/failure state for every
384              * item in the list, we just recheck "does the raw write we must
385              * have made in write_list_to_cpustate() read back OK" here.
386              */
387             uint64_t oldval = cpu->cpreg_values[i];
388 
389             if (oldval == newval) {
390                 continue;
391             }
392 
393             write_raw_cp_reg(&cpu->env, ri, oldval);
394             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
395                 continue;
396             }
397 
398             write_raw_cp_reg(&cpu->env, ri, newval);
399         }
400         cpu->cpreg_values[i] = newval;
401     }
402     return ok;
403 }
404 
405 bool write_list_to_cpustate(ARMCPU *cpu)
406 {
407     int i;
408     bool ok = true;
409 
410     for (i = 0; i < cpu->cpreg_array_len; i++) {
411         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
412         uint64_t v = cpu->cpreg_values[i];
413         const ARMCPRegInfo *ri;
414 
415         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
416         if (!ri) {
417             ok = false;
418             continue;
419         }
420         if (ri->type & ARM_CP_NO_RAW) {
421             continue;
422         }
423         /* Write value and confirm it reads back as written
424          * (to catch read-only registers and partially read-only
425          * registers where the incoming migration value doesn't match)
426          */
427         write_raw_cp_reg(&cpu->env, ri, v);
428         if (read_raw_cp_reg(&cpu->env, ri) != v) {
429             ok = false;
430         }
431     }
432     return ok;
433 }
434 
435 static void add_cpreg_to_list(gpointer key, gpointer opaque)
436 {
437     ARMCPU *cpu = opaque;
438     uint64_t regidx;
439     const ARMCPRegInfo *ri;
440 
441     regidx = *(uint32_t *)key;
442     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
443 
444     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
445         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
446         /* The value array need not be initialized at this point */
447         cpu->cpreg_array_len++;
448     }
449 }
450 
451 static void count_cpreg(gpointer key, gpointer opaque)
452 {
453     ARMCPU *cpu = opaque;
454     uint64_t regidx;
455     const ARMCPRegInfo *ri;
456 
457     regidx = *(uint32_t *)key;
458     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
459 
460     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
461         cpu->cpreg_array_len++;
462     }
463 }
464 
465 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
466 {
467     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
468     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
469 
470     if (aidx > bidx) {
471         return 1;
472     }
473     if (aidx < bidx) {
474         return -1;
475     }
476     return 0;
477 }
478 
479 void init_cpreg_list(ARMCPU *cpu)
480 {
481     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
482      * Note that we require cpreg_tuples[] to be sorted by key ID.
483      */
484     GList *keys;
485     int arraylen;
486 
487     keys = g_hash_table_get_keys(cpu->cp_regs);
488     keys = g_list_sort(keys, cpreg_key_compare);
489 
490     cpu->cpreg_array_len = 0;
491 
492     g_list_foreach(keys, count_cpreg, cpu);
493 
494     arraylen = cpu->cpreg_array_len;
495     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
496     cpu->cpreg_values = g_new(uint64_t, arraylen);
497     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
498     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
499     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
500     cpu->cpreg_array_len = 0;
501 
502     g_list_foreach(keys, add_cpreg_to_list, cpu);
503 
504     assert(cpu->cpreg_array_len == arraylen);
505 
506     g_list_free(keys);
507 }
508 
509 /*
510  * Some registers are not accessible from AArch32 EL3 if SCR.NS == 0.
511  */
512 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
513                                         const ARMCPRegInfo *ri,
514                                         bool isread)
515 {
516     if (!is_a64(env) && arm_current_el(env) == 3 &&
517         arm_is_secure_below_el3(env)) {
518         return CP_ACCESS_TRAP_UNCATEGORIZED;
519     }
520     return CP_ACCESS_OK;
521 }
522 
523 /* Some secure-only AArch32 registers trap to EL3 if used from
524  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
525  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
526  * We assume that the .access field is set to PL1_RW.
527  */
528 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
529                                             const ARMCPRegInfo *ri,
530                                             bool isread)
531 {
532     if (arm_current_el(env) == 3) {
533         return CP_ACCESS_OK;
534     }
535     if (arm_is_secure_below_el3(env)) {
536         if (env->cp15.scr_el3 & SCR_EEL2) {
537             return CP_ACCESS_TRAP_EL2;
538         }
539         return CP_ACCESS_TRAP_EL3;
540     }
541     /* This will be EL1 NS and EL2 NS, which just UNDEF */
542     return CP_ACCESS_TRAP_UNCATEGORIZED;
543 }
544 
545 static uint64_t arm_mdcr_el2_eff(CPUARMState *env)
546 {
547     return arm_is_el2_enabled(env) ? env->cp15.mdcr_el2 : 0;
548 }
549 
550 /* Check for traps to "powerdown debug" registers, which are controlled
551  * by MDCR.TDOSA
552  */
553 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
554                                    bool isread)
555 {
556     int el = arm_current_el(env);
557     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
558     bool mdcr_el2_tdosa = (mdcr_el2 & MDCR_TDOSA) || (mdcr_el2 & MDCR_TDE) ||
559         (arm_hcr_el2_eff(env) & HCR_TGE);
560 
561     if (el < 2 && mdcr_el2_tdosa) {
562         return CP_ACCESS_TRAP_EL2;
563     }
564     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
565         return CP_ACCESS_TRAP_EL3;
566     }
567     return CP_ACCESS_OK;
568 }
569 
570 /* Check for traps to "debug ROM" registers, which are controlled
571  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
572  */
573 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
574                                   bool isread)
575 {
576     int el = arm_current_el(env);
577     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
578     bool mdcr_el2_tdra = (mdcr_el2 & MDCR_TDRA) || (mdcr_el2 & MDCR_TDE) ||
579         (arm_hcr_el2_eff(env) & HCR_TGE);
580 
581     if (el < 2 && mdcr_el2_tdra) {
582         return CP_ACCESS_TRAP_EL2;
583     }
584     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
585         return CP_ACCESS_TRAP_EL3;
586     }
587     return CP_ACCESS_OK;
588 }
589 
590 /* Check for traps to general debug registers, which are controlled
591  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
592  */
593 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
594                                   bool isread)
595 {
596     int el = arm_current_el(env);
597     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
598     bool mdcr_el2_tda = (mdcr_el2 & MDCR_TDA) || (mdcr_el2 & MDCR_TDE) ||
599         (arm_hcr_el2_eff(env) & HCR_TGE);
600 
601     if (el < 2 && mdcr_el2_tda) {
602         return CP_ACCESS_TRAP_EL2;
603     }
604     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
605         return CP_ACCESS_TRAP_EL3;
606     }
607     return CP_ACCESS_OK;
608 }
609 
610 /* Check for traps to performance monitor registers, which are controlled
611  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
612  */
613 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
614                                  bool isread)
615 {
616     int el = arm_current_el(env);
617     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
618 
619     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
620         return CP_ACCESS_TRAP_EL2;
621     }
622     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
623         return CP_ACCESS_TRAP_EL3;
624     }
625     return CP_ACCESS_OK;
626 }
627 
628 /* Check for traps from EL1 due to HCR_EL2.TVM and HCR_EL2.TRVM.  */
629 static CPAccessResult access_tvm_trvm(CPUARMState *env, const ARMCPRegInfo *ri,
630                                       bool isread)
631 {
632     if (arm_current_el(env) == 1) {
633         uint64_t trap = isread ? HCR_TRVM : HCR_TVM;
634         if (arm_hcr_el2_eff(env) & trap) {
635             return CP_ACCESS_TRAP_EL2;
636         }
637     }
638     return CP_ACCESS_OK;
639 }
640 
641 /* Check for traps from EL1 due to HCR_EL2.TSW.  */
642 static CPAccessResult access_tsw(CPUARMState *env, const ARMCPRegInfo *ri,
643                                  bool isread)
644 {
645     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TSW)) {
646         return CP_ACCESS_TRAP_EL2;
647     }
648     return CP_ACCESS_OK;
649 }
650 
651 /* Check for traps from EL1 due to HCR_EL2.TACR.  */
652 static CPAccessResult access_tacr(CPUARMState *env, const ARMCPRegInfo *ri,
653                                   bool isread)
654 {
655     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TACR)) {
656         return CP_ACCESS_TRAP_EL2;
657     }
658     return CP_ACCESS_OK;
659 }
660 
661 /* Check for traps from EL1 due to HCR_EL2.TTLB. */
662 static CPAccessResult access_ttlb(CPUARMState *env, const ARMCPRegInfo *ri,
663                                   bool isread)
664 {
665     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TTLB)) {
666         return CP_ACCESS_TRAP_EL2;
667     }
668     return CP_ACCESS_OK;
669 }
670 
671 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
672 {
673     ARMCPU *cpu = env_archcpu(env);
674 
675     raw_write(env, ri, value);
676     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
677 }
678 
679 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
680 {
681     ARMCPU *cpu = env_archcpu(env);
682 
683     if (raw_read(env, ri) != value) {
684         /* Unlike real hardware the qemu TLB uses virtual addresses,
685          * not modified virtual addresses, so this causes a TLB flush.
686          */
687         tlb_flush(CPU(cpu));
688         raw_write(env, ri, value);
689     }
690 }
691 
692 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
693                              uint64_t value)
694 {
695     ARMCPU *cpu = env_archcpu(env);
696 
697     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
698         && !extended_addresses_enabled(env)) {
699         /* For VMSA (when not using the LPAE long descriptor page table
700          * format) this register includes the ASID, so do a TLB flush.
701          * For PMSA it is purely a process ID and no action is needed.
702          */
703         tlb_flush(CPU(cpu));
704     }
705     raw_write(env, ri, value);
706 }
707 
708 /* IS variants of TLB operations must affect all cores */
709 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
710                              uint64_t value)
711 {
712     CPUState *cs = env_cpu(env);
713 
714     tlb_flush_all_cpus_synced(cs);
715 }
716 
717 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
718                              uint64_t value)
719 {
720     CPUState *cs = env_cpu(env);
721 
722     tlb_flush_all_cpus_synced(cs);
723 }
724 
725 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
726                              uint64_t value)
727 {
728     CPUState *cs = env_cpu(env);
729 
730     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
731 }
732 
733 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
734                              uint64_t value)
735 {
736     CPUState *cs = env_cpu(env);
737 
738     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
739 }
740 
741 /*
742  * Non-IS variants of TLB operations are upgraded to
743  * IS versions if we are at EL1 and HCR_EL2.FB is effectively set to
744  * force broadcast of these operations.
745  */
746 static bool tlb_force_broadcast(CPUARMState *env)
747 {
748     return arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_FB);
749 }
750 
751 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
752                           uint64_t value)
753 {
754     /* Invalidate all (TLBIALL) */
755     CPUState *cs = env_cpu(env);
756 
757     if (tlb_force_broadcast(env)) {
758         tlb_flush_all_cpus_synced(cs);
759     } else {
760         tlb_flush(cs);
761     }
762 }
763 
764 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
765                           uint64_t value)
766 {
767     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
768     CPUState *cs = env_cpu(env);
769 
770     value &= TARGET_PAGE_MASK;
771     if (tlb_force_broadcast(env)) {
772         tlb_flush_page_all_cpus_synced(cs, value);
773     } else {
774         tlb_flush_page(cs, value);
775     }
776 }
777 
778 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
779                            uint64_t value)
780 {
781     /* Invalidate by ASID (TLBIASID) */
782     CPUState *cs = env_cpu(env);
783 
784     if (tlb_force_broadcast(env)) {
785         tlb_flush_all_cpus_synced(cs);
786     } else {
787         tlb_flush(cs);
788     }
789 }
790 
791 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
792                            uint64_t value)
793 {
794     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
795     CPUState *cs = env_cpu(env);
796 
797     value &= TARGET_PAGE_MASK;
798     if (tlb_force_broadcast(env)) {
799         tlb_flush_page_all_cpus_synced(cs, value);
800     } else {
801         tlb_flush_page(cs, value);
802     }
803 }
804 
805 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
806                                uint64_t value)
807 {
808     CPUState *cs = env_cpu(env);
809 
810     tlb_flush_by_mmuidx(cs,
811                         ARMMMUIdxBit_E10_1 |
812                         ARMMMUIdxBit_E10_1_PAN |
813                         ARMMMUIdxBit_E10_0);
814 }
815 
816 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
817                                   uint64_t value)
818 {
819     CPUState *cs = env_cpu(env);
820 
821     tlb_flush_by_mmuidx_all_cpus_synced(cs,
822                                         ARMMMUIdxBit_E10_1 |
823                                         ARMMMUIdxBit_E10_1_PAN |
824                                         ARMMMUIdxBit_E10_0);
825 }
826 
827 
828 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
829                               uint64_t value)
830 {
831     CPUState *cs = env_cpu(env);
832 
833     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_E2);
834 }
835 
836 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
837                                  uint64_t value)
838 {
839     CPUState *cs = env_cpu(env);
840 
841     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_E2);
842 }
843 
844 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
845                               uint64_t value)
846 {
847     CPUState *cs = env_cpu(env);
848     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
849 
850     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_E2);
851 }
852 
853 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
854                                  uint64_t value)
855 {
856     CPUState *cs = env_cpu(env);
857     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
858 
859     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
860                                              ARMMMUIdxBit_E2);
861 }
862 
863 static const ARMCPRegInfo cp_reginfo[] = {
864     /* Define the secure and non-secure FCSE identifier CP registers
865      * separately because there is no secure bank in V8 (no _EL3).  This allows
866      * the secure register to be properly reset and migrated. There is also no
867      * v8 EL1 version of the register so the non-secure instance stands alone.
868      */
869     { .name = "FCSEIDR",
870       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
871       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
872       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
873       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
874     { .name = "FCSEIDR_S",
875       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
876       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
877       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
878       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
879     /* Define the secure and non-secure context identifier CP registers
880      * separately because there is no secure bank in V8 (no _EL3).  This allows
881      * the secure register to be properly reset and migrated.  In the
882      * non-secure case, the 32-bit register will have reset and migration
883      * disabled during registration as it is handled by the 64-bit instance.
884      */
885     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
886       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
887       .access = PL1_RW, .accessfn = access_tvm_trvm,
888       .secure = ARM_CP_SECSTATE_NS,
889       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
890       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
891     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
892       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
893       .access = PL1_RW, .accessfn = access_tvm_trvm,
894       .secure = ARM_CP_SECSTATE_S,
895       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
896       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
897     REGINFO_SENTINEL
898 };
899 
900 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
901     /* NB: Some of these registers exist in v8 but with more precise
902      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
903      */
904     /* MMU Domain access control / MPU write buffer control */
905     { .name = "DACR",
906       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
907       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
908       .writefn = dacr_write, .raw_writefn = raw_write,
909       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
910                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
911     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
912      * For v6 and v5, these mappings are overly broad.
913      */
914     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
915       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
916     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
917       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
918     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
919       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
920     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
921       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
922     /* Cache maintenance ops; some of this space may be overridden later. */
923     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
924       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
925       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
926     REGINFO_SENTINEL
927 };
928 
929 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
930     /* Not all pre-v6 cores implemented this WFI, so this is slightly
931      * over-broad.
932      */
933     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
934       .access = PL1_W, .type = ARM_CP_WFI },
935     REGINFO_SENTINEL
936 };
937 
938 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
939     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
940      * is UNPREDICTABLE; we choose to NOP as most implementations do).
941      */
942     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
943       .access = PL1_W, .type = ARM_CP_WFI },
944     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
945      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
946      * OMAPCP will override this space.
947      */
948     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
949       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
950       .resetvalue = 0 },
951     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
952       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
953       .resetvalue = 0 },
954     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
955     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
956       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
957       .resetvalue = 0 },
958     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
959      * implementing it as RAZ means the "debug architecture version" bits
960      * will read as a reserved value, which should cause Linux to not try
961      * to use the debug hardware.
962      */
963     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
964       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
965     /* MMU TLB control. Note that the wildcarding means we cover not just
966      * the unified TLB ops but also the dside/iside/inner-shareable variants.
967      */
968     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
969       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
970       .type = ARM_CP_NO_RAW },
971     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
972       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
973       .type = ARM_CP_NO_RAW },
974     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
975       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
976       .type = ARM_CP_NO_RAW },
977     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
978       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
979       .type = ARM_CP_NO_RAW },
980     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
981       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
982     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
983       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
984     REGINFO_SENTINEL
985 };
986 
987 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
988                         uint64_t value)
989 {
990     uint32_t mask = 0;
991 
992     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
993     if (!arm_feature(env, ARM_FEATURE_V8)) {
994         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
995          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
996          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
997          */
998         if (cpu_isar_feature(aa32_vfp_simd, env_archcpu(env))) {
999             /* VFP coprocessor: cp10 & cp11 [23:20] */
1000             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
1001 
1002             if (!arm_feature(env, ARM_FEATURE_NEON)) {
1003                 /* ASEDIS [31] bit is RAO/WI */
1004                 value |= (1 << 31);
1005             }
1006 
1007             /* VFPv3 and upwards with NEON implement 32 double precision
1008              * registers (D0-D31).
1009              */
1010             if (!cpu_isar_feature(aa32_simd_r32, env_archcpu(env))) {
1011                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
1012                 value |= (1 << 30);
1013             }
1014         }
1015         value &= mask;
1016     }
1017 
1018     /*
1019      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
1020      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
1021      */
1022     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
1023         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
1024         value &= ~(0xf << 20);
1025         value |= env->cp15.cpacr_el1 & (0xf << 20);
1026     }
1027 
1028     env->cp15.cpacr_el1 = value;
1029 }
1030 
1031 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1032 {
1033     /*
1034      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
1035      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
1036      */
1037     uint64_t value = env->cp15.cpacr_el1;
1038 
1039     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
1040         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
1041         value &= ~(0xf << 20);
1042     }
1043     return value;
1044 }
1045 
1046 
1047 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1048 {
1049     /* Call cpacr_write() so that we reset with the correct RAO bits set
1050      * for our CPU features.
1051      */
1052     cpacr_write(env, ri, 0);
1053 }
1054 
1055 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1056                                    bool isread)
1057 {
1058     if (arm_feature(env, ARM_FEATURE_V8)) {
1059         /* Check if CPACR accesses are to be trapped to EL2 */
1060         if (arm_current_el(env) == 1 && arm_is_el2_enabled(env) &&
1061             (env->cp15.cptr_el[2] & CPTR_TCPAC)) {
1062             return CP_ACCESS_TRAP_EL2;
1063         /* Check if CPACR accesses are to be trapped to EL3 */
1064         } else if (arm_current_el(env) < 3 &&
1065                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
1066             return CP_ACCESS_TRAP_EL3;
1067         }
1068     }
1069 
1070     return CP_ACCESS_OK;
1071 }
1072 
1073 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1074                                   bool isread)
1075 {
1076     /* Check if CPTR accesses are set to trap to EL3 */
1077     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
1078         return CP_ACCESS_TRAP_EL3;
1079     }
1080 
1081     return CP_ACCESS_OK;
1082 }
1083 
1084 static const ARMCPRegInfo v6_cp_reginfo[] = {
1085     /* prefetch by MVA in v6, NOP in v7 */
1086     { .name = "MVA_prefetch",
1087       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
1088       .access = PL1_W, .type = ARM_CP_NOP },
1089     /* We need to break the TB after ISB to execute self-modifying code
1090      * correctly and also to take any pending interrupts immediately.
1091      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
1092      */
1093     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
1094       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
1095     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
1096       .access = PL0_W, .type = ARM_CP_NOP },
1097     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
1098       .access = PL0_W, .type = ARM_CP_NOP },
1099     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
1100       .access = PL1_RW, .accessfn = access_tvm_trvm,
1101       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
1102                              offsetof(CPUARMState, cp15.ifar_ns) },
1103       .resetvalue = 0, },
1104     /* Watchpoint Fault Address Register : should actually only be present
1105      * for 1136, 1176, 11MPCore.
1106      */
1107     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
1108       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
1109     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
1110       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
1111       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
1112       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
1113     REGINFO_SENTINEL
1114 };
1115 
1116 /* Definitions for the PMU registers */
1117 #define PMCRN_MASK  0xf800
1118 #define PMCRN_SHIFT 11
1119 #define PMCRLC  0x40
1120 #define PMCRDP  0x20
1121 #define PMCRX   0x10
1122 #define PMCRD   0x8
1123 #define PMCRC   0x4
1124 #define PMCRP   0x2
1125 #define PMCRE   0x1
1126 /*
1127  * Mask of PMCR bits writeable by guest (not including WO bits like C, P,
1128  * which can be written as 1 to trigger behaviour but which stay RAZ).
1129  */
1130 #define PMCR_WRITEABLE_MASK (PMCRLC | PMCRDP | PMCRX | PMCRD | PMCRE)
1131 
1132 #define PMXEVTYPER_P          0x80000000
1133 #define PMXEVTYPER_U          0x40000000
1134 #define PMXEVTYPER_NSK        0x20000000
1135 #define PMXEVTYPER_NSU        0x10000000
1136 #define PMXEVTYPER_NSH        0x08000000
1137 #define PMXEVTYPER_M          0x04000000
1138 #define PMXEVTYPER_MT         0x02000000
1139 #define PMXEVTYPER_EVTCOUNT   0x0000ffff
1140 #define PMXEVTYPER_MASK       (PMXEVTYPER_P | PMXEVTYPER_U | PMXEVTYPER_NSK | \
1141                                PMXEVTYPER_NSU | PMXEVTYPER_NSH | \
1142                                PMXEVTYPER_M | PMXEVTYPER_MT | \
1143                                PMXEVTYPER_EVTCOUNT)
1144 
1145 #define PMCCFILTR             0xf8000000
1146 #define PMCCFILTR_M           PMXEVTYPER_M
1147 #define PMCCFILTR_EL0         (PMCCFILTR | PMCCFILTR_M)
1148 
1149 static inline uint32_t pmu_num_counters(CPUARMState *env)
1150 {
1151   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
1152 }
1153 
1154 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1155 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1156 {
1157   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1158 }
1159 
1160 typedef struct pm_event {
1161     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1162     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1163     bool (*supported)(CPUARMState *);
1164     /*
1165      * Retrieve the current count of the underlying event. The programmed
1166      * counters hold a difference from the return value from this function
1167      */
1168     uint64_t (*get_count)(CPUARMState *);
1169     /*
1170      * Return how many nanoseconds it will take (at a minimum) for count events
1171      * to occur. A negative value indicates the counter will never overflow, or
1172      * that the counter has otherwise arranged for the overflow bit to be set
1173      * and the PMU interrupt to be raised on overflow.
1174      */
1175     int64_t (*ns_per_count)(uint64_t);
1176 } pm_event;
1177 
1178 static bool event_always_supported(CPUARMState *env)
1179 {
1180     return true;
1181 }
1182 
1183 static uint64_t swinc_get_count(CPUARMState *env)
1184 {
1185     /*
1186      * SW_INCR events are written directly to the pmevcntr's by writes to
1187      * PMSWINC, so there is no underlying count maintained by the PMU itself
1188      */
1189     return 0;
1190 }
1191 
1192 static int64_t swinc_ns_per(uint64_t ignored)
1193 {
1194     return -1;
1195 }
1196 
1197 /*
1198  * Return the underlying cycle count for the PMU cycle counters. If we're in
1199  * usermode, simply return 0.
1200  */
1201 static uint64_t cycles_get_count(CPUARMState *env)
1202 {
1203 #ifndef CONFIG_USER_ONLY
1204     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1205                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1206 #else
1207     return cpu_get_host_ticks();
1208 #endif
1209 }
1210 
1211 #ifndef CONFIG_USER_ONLY
1212 static int64_t cycles_ns_per(uint64_t cycles)
1213 {
1214     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1215 }
1216 
1217 static bool instructions_supported(CPUARMState *env)
1218 {
1219     return icount_enabled() == 1; /* Precise instruction counting */
1220 }
1221 
1222 static uint64_t instructions_get_count(CPUARMState *env)
1223 {
1224     return (uint64_t)icount_get_raw();
1225 }
1226 
1227 static int64_t instructions_ns_per(uint64_t icount)
1228 {
1229     return icount_to_ns((int64_t)icount);
1230 }
1231 #endif
1232 
1233 static bool pmu_8_1_events_supported(CPUARMState *env)
1234 {
1235     /* For events which are supported in any v8.1 PMU */
1236     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
1237 }
1238 
1239 static bool pmu_8_4_events_supported(CPUARMState *env)
1240 {
1241     /* For events which are supported in any v8.1 PMU */
1242     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
1243 }
1244 
1245 static uint64_t zero_event_get_count(CPUARMState *env)
1246 {
1247     /* For events which on QEMU never fire, so their count is always zero */
1248     return 0;
1249 }
1250 
1251 static int64_t zero_event_ns_per(uint64_t cycles)
1252 {
1253     /* An event which never fires can never overflow */
1254     return -1;
1255 }
1256 
1257 static const pm_event pm_events[] = {
1258     { .number = 0x000, /* SW_INCR */
1259       .supported = event_always_supported,
1260       .get_count = swinc_get_count,
1261       .ns_per_count = swinc_ns_per,
1262     },
1263 #ifndef CONFIG_USER_ONLY
1264     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1265       .supported = instructions_supported,
1266       .get_count = instructions_get_count,
1267       .ns_per_count = instructions_ns_per,
1268     },
1269     { .number = 0x011, /* CPU_CYCLES, Cycle */
1270       .supported = event_always_supported,
1271       .get_count = cycles_get_count,
1272       .ns_per_count = cycles_ns_per,
1273     },
1274 #endif
1275     { .number = 0x023, /* STALL_FRONTEND */
1276       .supported = pmu_8_1_events_supported,
1277       .get_count = zero_event_get_count,
1278       .ns_per_count = zero_event_ns_per,
1279     },
1280     { .number = 0x024, /* STALL_BACKEND */
1281       .supported = pmu_8_1_events_supported,
1282       .get_count = zero_event_get_count,
1283       .ns_per_count = zero_event_ns_per,
1284     },
1285     { .number = 0x03c, /* STALL */
1286       .supported = pmu_8_4_events_supported,
1287       .get_count = zero_event_get_count,
1288       .ns_per_count = zero_event_ns_per,
1289     },
1290 };
1291 
1292 /*
1293  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1294  * events (i.e. the statistical profiling extension), this implementation
1295  * should first be updated to something sparse instead of the current
1296  * supported_event_map[] array.
1297  */
1298 #define MAX_EVENT_ID 0x3c
1299 #define UNSUPPORTED_EVENT UINT16_MAX
1300 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1301 
1302 /*
1303  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1304  * of ARM event numbers to indices in our pm_events array.
1305  *
1306  * Note: Events in the 0x40XX range are not currently supported.
1307  */
1308 void pmu_init(ARMCPU *cpu)
1309 {
1310     unsigned int i;
1311 
1312     /*
1313      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1314      * events to them
1315      */
1316     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1317         supported_event_map[i] = UNSUPPORTED_EVENT;
1318     }
1319     cpu->pmceid0 = 0;
1320     cpu->pmceid1 = 0;
1321 
1322     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1323         const pm_event *cnt = &pm_events[i];
1324         assert(cnt->number <= MAX_EVENT_ID);
1325         /* We do not currently support events in the 0x40xx range */
1326         assert(cnt->number <= 0x3f);
1327 
1328         if (cnt->supported(&cpu->env)) {
1329             supported_event_map[cnt->number] = i;
1330             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1331             if (cnt->number & 0x20) {
1332                 cpu->pmceid1 |= event_mask;
1333             } else {
1334                 cpu->pmceid0 |= event_mask;
1335             }
1336         }
1337     }
1338 }
1339 
1340 /*
1341  * Check at runtime whether a PMU event is supported for the current machine
1342  */
1343 static bool event_supported(uint16_t number)
1344 {
1345     if (number > MAX_EVENT_ID) {
1346         return false;
1347     }
1348     return supported_event_map[number] != UNSUPPORTED_EVENT;
1349 }
1350 
1351 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1352                                    bool isread)
1353 {
1354     /* Performance monitor registers user accessibility is controlled
1355      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1356      * trapping to EL2 or EL3 for other accesses.
1357      */
1358     int el = arm_current_el(env);
1359     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1360 
1361     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1362         return CP_ACCESS_TRAP;
1363     }
1364     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
1365         return CP_ACCESS_TRAP_EL2;
1366     }
1367     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1368         return CP_ACCESS_TRAP_EL3;
1369     }
1370 
1371     return CP_ACCESS_OK;
1372 }
1373 
1374 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1375                                            const ARMCPRegInfo *ri,
1376                                            bool isread)
1377 {
1378     /* ER: event counter read trap control */
1379     if (arm_feature(env, ARM_FEATURE_V8)
1380         && arm_current_el(env) == 0
1381         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1382         && isread) {
1383         return CP_ACCESS_OK;
1384     }
1385 
1386     return pmreg_access(env, ri, isread);
1387 }
1388 
1389 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1390                                          const ARMCPRegInfo *ri,
1391                                          bool isread)
1392 {
1393     /* SW: software increment write trap control */
1394     if (arm_feature(env, ARM_FEATURE_V8)
1395         && arm_current_el(env) == 0
1396         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1397         && !isread) {
1398         return CP_ACCESS_OK;
1399     }
1400 
1401     return pmreg_access(env, ri, isread);
1402 }
1403 
1404 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1405                                         const ARMCPRegInfo *ri,
1406                                         bool isread)
1407 {
1408     /* ER: event counter read trap control */
1409     if (arm_feature(env, ARM_FEATURE_V8)
1410         && arm_current_el(env) == 0
1411         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1412         return CP_ACCESS_OK;
1413     }
1414 
1415     return pmreg_access(env, ri, isread);
1416 }
1417 
1418 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1419                                          const ARMCPRegInfo *ri,
1420                                          bool isread)
1421 {
1422     /* CR: cycle counter read trap control */
1423     if (arm_feature(env, ARM_FEATURE_V8)
1424         && arm_current_el(env) == 0
1425         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1426         && isread) {
1427         return CP_ACCESS_OK;
1428     }
1429 
1430     return pmreg_access(env, ri, isread);
1431 }
1432 
1433 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1434  * the current EL, security state, and register configuration.
1435  */
1436 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1437 {
1438     uint64_t filter;
1439     bool e, p, u, nsk, nsu, nsh, m;
1440     bool enabled, prohibited, filtered;
1441     bool secure = arm_is_secure(env);
1442     int el = arm_current_el(env);
1443     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1444     uint8_t hpmn = mdcr_el2 & MDCR_HPMN;
1445 
1446     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1447         return false;
1448     }
1449 
1450     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1451             (counter < hpmn || counter == 31)) {
1452         e = env->cp15.c9_pmcr & PMCRE;
1453     } else {
1454         e = mdcr_el2 & MDCR_HPME;
1455     }
1456     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1457 
1458     if (!secure) {
1459         if (el == 2 && (counter < hpmn || counter == 31)) {
1460             prohibited = mdcr_el2 & MDCR_HPMD;
1461         } else {
1462             prohibited = false;
1463         }
1464     } else {
1465         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1466            !(env->cp15.mdcr_el3 & MDCR_SPME);
1467     }
1468 
1469     if (prohibited && counter == 31) {
1470         prohibited = env->cp15.c9_pmcr & PMCRDP;
1471     }
1472 
1473     if (counter == 31) {
1474         filter = env->cp15.pmccfiltr_el0;
1475     } else {
1476         filter = env->cp15.c14_pmevtyper[counter];
1477     }
1478 
1479     p   = filter & PMXEVTYPER_P;
1480     u   = filter & PMXEVTYPER_U;
1481     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1482     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1483     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1484     m   = arm_el_is_aa64(env, 1) &&
1485               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1486 
1487     if (el == 0) {
1488         filtered = secure ? u : u != nsu;
1489     } else if (el == 1) {
1490         filtered = secure ? p : p != nsk;
1491     } else if (el == 2) {
1492         filtered = !nsh;
1493     } else { /* EL3 */
1494         filtered = m != p;
1495     }
1496 
1497     if (counter != 31) {
1498         /*
1499          * If not checking PMCCNTR, ensure the counter is setup to an event we
1500          * support
1501          */
1502         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1503         if (!event_supported(event)) {
1504             return false;
1505         }
1506     }
1507 
1508     return enabled && !prohibited && !filtered;
1509 }
1510 
1511 static void pmu_update_irq(CPUARMState *env)
1512 {
1513     ARMCPU *cpu = env_archcpu(env);
1514     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1515             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1516 }
1517 
1518 /*
1519  * Ensure c15_ccnt is the guest-visible count so that operations such as
1520  * enabling/disabling the counter or filtering, modifying the count itself,
1521  * etc. can be done logically. This is essentially a no-op if the counter is
1522  * not enabled at the time of the call.
1523  */
1524 static void pmccntr_op_start(CPUARMState *env)
1525 {
1526     uint64_t cycles = cycles_get_count(env);
1527 
1528     if (pmu_counter_enabled(env, 31)) {
1529         uint64_t eff_cycles = cycles;
1530         if (env->cp15.c9_pmcr & PMCRD) {
1531             /* Increment once every 64 processor clock cycles */
1532             eff_cycles /= 64;
1533         }
1534 
1535         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1536 
1537         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1538                                  1ull << 63 : 1ull << 31;
1539         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1540             env->cp15.c9_pmovsr |= (1 << 31);
1541             pmu_update_irq(env);
1542         }
1543 
1544         env->cp15.c15_ccnt = new_pmccntr;
1545     }
1546     env->cp15.c15_ccnt_delta = cycles;
1547 }
1548 
1549 /*
1550  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1551  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1552  * pmccntr_op_start.
1553  */
1554 static void pmccntr_op_finish(CPUARMState *env)
1555 {
1556     if (pmu_counter_enabled(env, 31)) {
1557 #ifndef CONFIG_USER_ONLY
1558         /* Calculate when the counter will next overflow */
1559         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1560         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1561             remaining_cycles = (uint32_t)remaining_cycles;
1562         }
1563         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1564 
1565         if (overflow_in > 0) {
1566             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1567                 overflow_in;
1568             ARMCPU *cpu = env_archcpu(env);
1569             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1570         }
1571 #endif
1572 
1573         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1574         if (env->cp15.c9_pmcr & PMCRD) {
1575             /* Increment once every 64 processor clock cycles */
1576             prev_cycles /= 64;
1577         }
1578         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1579     }
1580 }
1581 
1582 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1583 {
1584 
1585     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1586     uint64_t count = 0;
1587     if (event_supported(event)) {
1588         uint16_t event_idx = supported_event_map[event];
1589         count = pm_events[event_idx].get_count(env);
1590     }
1591 
1592     if (pmu_counter_enabled(env, counter)) {
1593         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1594 
1595         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1596             env->cp15.c9_pmovsr |= (1 << counter);
1597             pmu_update_irq(env);
1598         }
1599         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1600     }
1601     env->cp15.c14_pmevcntr_delta[counter] = count;
1602 }
1603 
1604 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1605 {
1606     if (pmu_counter_enabled(env, counter)) {
1607 #ifndef CONFIG_USER_ONLY
1608         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1609         uint16_t event_idx = supported_event_map[event];
1610         uint64_t delta = UINT32_MAX -
1611             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1612         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1613 
1614         if (overflow_in > 0) {
1615             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1616                 overflow_in;
1617             ARMCPU *cpu = env_archcpu(env);
1618             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1619         }
1620 #endif
1621 
1622         env->cp15.c14_pmevcntr_delta[counter] -=
1623             env->cp15.c14_pmevcntr[counter];
1624     }
1625 }
1626 
1627 void pmu_op_start(CPUARMState *env)
1628 {
1629     unsigned int i;
1630     pmccntr_op_start(env);
1631     for (i = 0; i < pmu_num_counters(env); i++) {
1632         pmevcntr_op_start(env, i);
1633     }
1634 }
1635 
1636 void pmu_op_finish(CPUARMState *env)
1637 {
1638     unsigned int i;
1639     pmccntr_op_finish(env);
1640     for (i = 0; i < pmu_num_counters(env); i++) {
1641         pmevcntr_op_finish(env, i);
1642     }
1643 }
1644 
1645 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1646 {
1647     pmu_op_start(&cpu->env);
1648 }
1649 
1650 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1651 {
1652     pmu_op_finish(&cpu->env);
1653 }
1654 
1655 void arm_pmu_timer_cb(void *opaque)
1656 {
1657     ARMCPU *cpu = opaque;
1658 
1659     /*
1660      * Update all the counter values based on the current underlying counts,
1661      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1662      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1663      * counter may expire.
1664      */
1665     pmu_op_start(&cpu->env);
1666     pmu_op_finish(&cpu->env);
1667 }
1668 
1669 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1670                        uint64_t value)
1671 {
1672     pmu_op_start(env);
1673 
1674     if (value & PMCRC) {
1675         /* The counter has been reset */
1676         env->cp15.c15_ccnt = 0;
1677     }
1678 
1679     if (value & PMCRP) {
1680         unsigned int i;
1681         for (i = 0; i < pmu_num_counters(env); i++) {
1682             env->cp15.c14_pmevcntr[i] = 0;
1683         }
1684     }
1685 
1686     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1687     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1688 
1689     pmu_op_finish(env);
1690 }
1691 
1692 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1693                           uint64_t value)
1694 {
1695     unsigned int i;
1696     for (i = 0; i < pmu_num_counters(env); i++) {
1697         /* Increment a counter's count iff: */
1698         if ((value & (1 << i)) && /* counter's bit is set */
1699                 /* counter is enabled and not filtered */
1700                 pmu_counter_enabled(env, i) &&
1701                 /* counter is SW_INCR */
1702                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1703             pmevcntr_op_start(env, i);
1704 
1705             /*
1706              * Detect if this write causes an overflow since we can't predict
1707              * PMSWINC overflows like we can for other events
1708              */
1709             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1710 
1711             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1712                 env->cp15.c9_pmovsr |= (1 << i);
1713                 pmu_update_irq(env);
1714             }
1715 
1716             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1717 
1718             pmevcntr_op_finish(env, i);
1719         }
1720     }
1721 }
1722 
1723 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1724 {
1725     uint64_t ret;
1726     pmccntr_op_start(env);
1727     ret = env->cp15.c15_ccnt;
1728     pmccntr_op_finish(env);
1729     return ret;
1730 }
1731 
1732 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1733                          uint64_t value)
1734 {
1735     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1736      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1737      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1738      * accessed.
1739      */
1740     env->cp15.c9_pmselr = value & 0x1f;
1741 }
1742 
1743 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1744                         uint64_t value)
1745 {
1746     pmccntr_op_start(env);
1747     env->cp15.c15_ccnt = value;
1748     pmccntr_op_finish(env);
1749 }
1750 
1751 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1752                             uint64_t value)
1753 {
1754     uint64_t cur_val = pmccntr_read(env, NULL);
1755 
1756     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1757 }
1758 
1759 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1760                             uint64_t value)
1761 {
1762     pmccntr_op_start(env);
1763     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1764     pmccntr_op_finish(env);
1765 }
1766 
1767 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1768                             uint64_t value)
1769 {
1770     pmccntr_op_start(env);
1771     /* M is not accessible from AArch32 */
1772     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1773         (value & PMCCFILTR);
1774     pmccntr_op_finish(env);
1775 }
1776 
1777 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1778 {
1779     /* M is not visible in AArch32 */
1780     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1781 }
1782 
1783 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1784                             uint64_t value)
1785 {
1786     value &= pmu_counter_mask(env);
1787     env->cp15.c9_pmcnten |= value;
1788 }
1789 
1790 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1791                              uint64_t value)
1792 {
1793     value &= pmu_counter_mask(env);
1794     env->cp15.c9_pmcnten &= ~value;
1795 }
1796 
1797 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1798                          uint64_t value)
1799 {
1800     value &= pmu_counter_mask(env);
1801     env->cp15.c9_pmovsr &= ~value;
1802     pmu_update_irq(env);
1803 }
1804 
1805 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1806                          uint64_t value)
1807 {
1808     value &= pmu_counter_mask(env);
1809     env->cp15.c9_pmovsr |= value;
1810     pmu_update_irq(env);
1811 }
1812 
1813 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1814                              uint64_t value, const uint8_t counter)
1815 {
1816     if (counter == 31) {
1817         pmccfiltr_write(env, ri, value);
1818     } else if (counter < pmu_num_counters(env)) {
1819         pmevcntr_op_start(env, counter);
1820 
1821         /*
1822          * If this counter's event type is changing, store the current
1823          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1824          * pmevcntr_op_finish has the correct baseline when it converts back to
1825          * a delta.
1826          */
1827         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1828             PMXEVTYPER_EVTCOUNT;
1829         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1830         if (old_event != new_event) {
1831             uint64_t count = 0;
1832             if (event_supported(new_event)) {
1833                 uint16_t event_idx = supported_event_map[new_event];
1834                 count = pm_events[event_idx].get_count(env);
1835             }
1836             env->cp15.c14_pmevcntr_delta[counter] = count;
1837         }
1838 
1839         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1840         pmevcntr_op_finish(env, counter);
1841     }
1842     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1843      * PMSELR value is equal to or greater than the number of implemented
1844      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1845      */
1846 }
1847 
1848 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1849                                const uint8_t counter)
1850 {
1851     if (counter == 31) {
1852         return env->cp15.pmccfiltr_el0;
1853     } else if (counter < pmu_num_counters(env)) {
1854         return env->cp15.c14_pmevtyper[counter];
1855     } else {
1856       /*
1857        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1858        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1859        */
1860         return 0;
1861     }
1862 }
1863 
1864 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1865                               uint64_t value)
1866 {
1867     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1868     pmevtyper_write(env, ri, value, counter);
1869 }
1870 
1871 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1872                                uint64_t value)
1873 {
1874     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1875     env->cp15.c14_pmevtyper[counter] = value;
1876 
1877     /*
1878      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1879      * pmu_op_finish calls when loading saved state for a migration. Because
1880      * we're potentially updating the type of event here, the value written to
1881      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1882      * different counter type. Therefore, we need to set this value to the
1883      * current count for the counter type we're writing so that pmu_op_finish
1884      * has the correct count for its calculation.
1885      */
1886     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1887     if (event_supported(event)) {
1888         uint16_t event_idx = supported_event_map[event];
1889         env->cp15.c14_pmevcntr_delta[counter] =
1890             pm_events[event_idx].get_count(env);
1891     }
1892 }
1893 
1894 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1895 {
1896     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1897     return pmevtyper_read(env, ri, counter);
1898 }
1899 
1900 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1901                              uint64_t value)
1902 {
1903     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1904 }
1905 
1906 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1907 {
1908     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1909 }
1910 
1911 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1912                              uint64_t value, uint8_t counter)
1913 {
1914     if (counter < pmu_num_counters(env)) {
1915         pmevcntr_op_start(env, counter);
1916         env->cp15.c14_pmevcntr[counter] = value;
1917         pmevcntr_op_finish(env, counter);
1918     }
1919     /*
1920      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1921      * are CONSTRAINED UNPREDICTABLE.
1922      */
1923 }
1924 
1925 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1926                               uint8_t counter)
1927 {
1928     if (counter < pmu_num_counters(env)) {
1929         uint64_t ret;
1930         pmevcntr_op_start(env, counter);
1931         ret = env->cp15.c14_pmevcntr[counter];
1932         pmevcntr_op_finish(env, counter);
1933         return ret;
1934     } else {
1935       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1936        * are CONSTRAINED UNPREDICTABLE. */
1937         return 0;
1938     }
1939 }
1940 
1941 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1942                              uint64_t value)
1943 {
1944     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1945     pmevcntr_write(env, ri, value, counter);
1946 }
1947 
1948 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1949 {
1950     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1951     return pmevcntr_read(env, ri, counter);
1952 }
1953 
1954 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1955                              uint64_t value)
1956 {
1957     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1958     assert(counter < pmu_num_counters(env));
1959     env->cp15.c14_pmevcntr[counter] = value;
1960     pmevcntr_write(env, ri, value, counter);
1961 }
1962 
1963 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1964 {
1965     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1966     assert(counter < pmu_num_counters(env));
1967     return env->cp15.c14_pmevcntr[counter];
1968 }
1969 
1970 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1971                              uint64_t value)
1972 {
1973     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1974 }
1975 
1976 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1977 {
1978     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1979 }
1980 
1981 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1982                             uint64_t value)
1983 {
1984     if (arm_feature(env, ARM_FEATURE_V8)) {
1985         env->cp15.c9_pmuserenr = value & 0xf;
1986     } else {
1987         env->cp15.c9_pmuserenr = value & 1;
1988     }
1989 }
1990 
1991 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1992                              uint64_t value)
1993 {
1994     /* We have no event counters so only the C bit can be changed */
1995     value &= pmu_counter_mask(env);
1996     env->cp15.c9_pminten |= value;
1997     pmu_update_irq(env);
1998 }
1999 
2000 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2001                              uint64_t value)
2002 {
2003     value &= pmu_counter_mask(env);
2004     env->cp15.c9_pminten &= ~value;
2005     pmu_update_irq(env);
2006 }
2007 
2008 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
2009                        uint64_t value)
2010 {
2011     /* Note that even though the AArch64 view of this register has bits
2012      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
2013      * architectural requirements for bits which are RES0 only in some
2014      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
2015      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
2016      */
2017     raw_write(env, ri, value & ~0x1FULL);
2018 }
2019 
2020 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2021 {
2022     /* Begin with base v8.0 state.  */
2023     uint32_t valid_mask = 0x3fff;
2024     ARMCPU *cpu = env_archcpu(env);
2025 
2026     if (ri->state == ARM_CP_STATE_AA64) {
2027         value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
2028         valid_mask &= ~SCR_NET;
2029 
2030         if (cpu_isar_feature(aa64_lor, cpu)) {
2031             valid_mask |= SCR_TLOR;
2032         }
2033         if (cpu_isar_feature(aa64_pauth, cpu)) {
2034             valid_mask |= SCR_API | SCR_APK;
2035         }
2036         if (cpu_isar_feature(aa64_sel2, cpu)) {
2037             valid_mask |= SCR_EEL2;
2038         }
2039         if (cpu_isar_feature(aa64_mte, cpu)) {
2040             valid_mask |= SCR_ATA;
2041         }
2042     } else {
2043         valid_mask &= ~(SCR_RW | SCR_ST);
2044     }
2045 
2046     if (!arm_feature(env, ARM_FEATURE_EL2)) {
2047         valid_mask &= ~SCR_HCE;
2048 
2049         /* On ARMv7, SMD (or SCD as it is called in v7) is only
2050          * supported if EL2 exists. The bit is UNK/SBZP when
2051          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
2052          * when EL2 is unavailable.
2053          * On ARMv8, this bit is always available.
2054          */
2055         if (arm_feature(env, ARM_FEATURE_V7) &&
2056             !arm_feature(env, ARM_FEATURE_V8)) {
2057             valid_mask &= ~SCR_SMD;
2058         }
2059     }
2060 
2061     /* Clear all-context RES0 bits.  */
2062     value &= valid_mask;
2063     raw_write(env, ri, value);
2064 }
2065 
2066 static CPAccessResult access_aa64_tid2(CPUARMState *env,
2067                                        const ARMCPRegInfo *ri,
2068                                        bool isread)
2069 {
2070     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
2071         return CP_ACCESS_TRAP_EL2;
2072     }
2073 
2074     return CP_ACCESS_OK;
2075 }
2076 
2077 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2078 {
2079     ARMCPU *cpu = env_archcpu(env);
2080 
2081     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
2082      * bank
2083      */
2084     uint32_t index = A32_BANKED_REG_GET(env, csselr,
2085                                         ri->secure & ARM_CP_SECSTATE_S);
2086 
2087     return cpu->ccsidr[index];
2088 }
2089 
2090 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2091                          uint64_t value)
2092 {
2093     raw_write(env, ri, value & 0xf);
2094 }
2095 
2096 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2097 {
2098     CPUState *cs = env_cpu(env);
2099     bool el1 = arm_current_el(env) == 1;
2100     uint64_t hcr_el2 = el1 ? arm_hcr_el2_eff(env) : 0;
2101     uint64_t ret = 0;
2102 
2103     if (hcr_el2 & HCR_IMO) {
2104         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
2105             ret |= CPSR_I;
2106         }
2107     } else {
2108         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
2109             ret |= CPSR_I;
2110         }
2111     }
2112 
2113     if (hcr_el2 & HCR_FMO) {
2114         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
2115             ret |= CPSR_F;
2116         }
2117     } else {
2118         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
2119             ret |= CPSR_F;
2120         }
2121     }
2122 
2123     /* External aborts are not possible in QEMU so A bit is always clear */
2124     return ret;
2125 }
2126 
2127 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2128                                        bool isread)
2129 {
2130     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
2131         return CP_ACCESS_TRAP_EL2;
2132     }
2133 
2134     return CP_ACCESS_OK;
2135 }
2136 
2137 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2138                                        bool isread)
2139 {
2140     if (arm_feature(env, ARM_FEATURE_V8)) {
2141         return access_aa64_tid1(env, ri, isread);
2142     }
2143 
2144     return CP_ACCESS_OK;
2145 }
2146 
2147 static const ARMCPRegInfo v7_cp_reginfo[] = {
2148     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
2149     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
2150       .access = PL1_W, .type = ARM_CP_NOP },
2151     /* Performance monitors are implementation defined in v7,
2152      * but with an ARM recommended set of registers, which we
2153      * follow.
2154      *
2155      * Performance registers fall into three categories:
2156      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
2157      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
2158      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
2159      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
2160      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
2161      */
2162     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
2163       .access = PL0_RW, .type = ARM_CP_ALIAS,
2164       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2165       .writefn = pmcntenset_write,
2166       .accessfn = pmreg_access,
2167       .raw_writefn = raw_write },
2168     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
2169       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
2170       .access = PL0_RW, .accessfn = pmreg_access,
2171       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
2172       .writefn = pmcntenset_write, .raw_writefn = raw_write },
2173     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
2174       .access = PL0_RW,
2175       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2176       .accessfn = pmreg_access,
2177       .writefn = pmcntenclr_write,
2178       .type = ARM_CP_ALIAS },
2179     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
2180       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
2181       .access = PL0_RW, .accessfn = pmreg_access,
2182       .type = ARM_CP_ALIAS,
2183       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
2184       .writefn = pmcntenclr_write },
2185     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
2186       .access = PL0_RW, .type = ARM_CP_IO,
2187       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2188       .accessfn = pmreg_access,
2189       .writefn = pmovsr_write,
2190       .raw_writefn = raw_write },
2191     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2192       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2193       .access = PL0_RW, .accessfn = pmreg_access,
2194       .type = ARM_CP_ALIAS | ARM_CP_IO,
2195       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2196       .writefn = pmovsr_write,
2197       .raw_writefn = raw_write },
2198     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2199       .access = PL0_W, .accessfn = pmreg_access_swinc,
2200       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2201       .writefn = pmswinc_write },
2202     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2203       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2204       .access = PL0_W, .accessfn = pmreg_access_swinc,
2205       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2206       .writefn = pmswinc_write },
2207     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2208       .access = PL0_RW, .type = ARM_CP_ALIAS,
2209       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2210       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2211       .raw_writefn = raw_write},
2212     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2213       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2214       .access = PL0_RW, .accessfn = pmreg_access_selr,
2215       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2216       .writefn = pmselr_write, .raw_writefn = raw_write, },
2217     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2218       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2219       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2220       .accessfn = pmreg_access_ccntr },
2221     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2222       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2223       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2224       .type = ARM_CP_IO,
2225       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2226       .readfn = pmccntr_read, .writefn = pmccntr_write,
2227       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2228     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2229       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2230       .access = PL0_RW, .accessfn = pmreg_access,
2231       .type = ARM_CP_ALIAS | ARM_CP_IO,
2232       .resetvalue = 0, },
2233     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2234       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2235       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2236       .access = PL0_RW, .accessfn = pmreg_access,
2237       .type = ARM_CP_IO,
2238       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2239       .resetvalue = 0, },
2240     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2241       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2242       .accessfn = pmreg_access,
2243       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2244     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2245       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2246       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2247       .accessfn = pmreg_access,
2248       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2249     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2250       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2251       .accessfn = pmreg_access_xevcntr,
2252       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2253     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2254       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2255       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2256       .accessfn = pmreg_access_xevcntr,
2257       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2258     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2259       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2260       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2261       .resetvalue = 0,
2262       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2263     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2264       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2265       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2266       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2267       .resetvalue = 0,
2268       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2269     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2270       .access = PL1_RW, .accessfn = access_tpm,
2271       .type = ARM_CP_ALIAS | ARM_CP_IO,
2272       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2273       .resetvalue = 0,
2274       .writefn = pmintenset_write, .raw_writefn = raw_write },
2275     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2276       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2277       .access = PL1_RW, .accessfn = access_tpm,
2278       .type = ARM_CP_IO,
2279       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2280       .writefn = pmintenset_write, .raw_writefn = raw_write,
2281       .resetvalue = 0x0 },
2282     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2283       .access = PL1_RW, .accessfn = access_tpm,
2284       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2285       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2286       .writefn = pmintenclr_write, },
2287     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2288       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2289       .access = PL1_RW, .accessfn = access_tpm,
2290       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2291       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2292       .writefn = pmintenclr_write },
2293     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2294       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2295       .access = PL1_R,
2296       .accessfn = access_aa64_tid2,
2297       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2298     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2299       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2300       .access = PL1_RW,
2301       .accessfn = access_aa64_tid2,
2302       .writefn = csselr_write, .resetvalue = 0,
2303       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2304                              offsetof(CPUARMState, cp15.csselr_ns) } },
2305     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2306      * just RAZ for all cores:
2307      */
2308     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2309       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2310       .access = PL1_R, .type = ARM_CP_CONST,
2311       .accessfn = access_aa64_tid1,
2312       .resetvalue = 0 },
2313     /* Auxiliary fault status registers: these also are IMPDEF, and we
2314      * choose to RAZ/WI for all cores.
2315      */
2316     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2317       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2318       .access = PL1_RW, .accessfn = access_tvm_trvm,
2319       .type = ARM_CP_CONST, .resetvalue = 0 },
2320     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2321       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2322       .access = PL1_RW, .accessfn = access_tvm_trvm,
2323       .type = ARM_CP_CONST, .resetvalue = 0 },
2324     /* MAIR can just read-as-written because we don't implement caches
2325      * and so don't need to care about memory attributes.
2326      */
2327     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2328       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2329       .access = PL1_RW, .accessfn = access_tvm_trvm,
2330       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2331       .resetvalue = 0 },
2332     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2333       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2334       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2335       .resetvalue = 0 },
2336     /* For non-long-descriptor page tables these are PRRR and NMRR;
2337      * regardless they still act as reads-as-written for QEMU.
2338      */
2339      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2340       * allows them to assign the correct fieldoffset based on the endianness
2341       * handled in the field definitions.
2342       */
2343     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2344       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2345       .access = PL1_RW, .accessfn = access_tvm_trvm,
2346       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2347                              offsetof(CPUARMState, cp15.mair0_ns) },
2348       .resetfn = arm_cp_reset_ignore },
2349     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2350       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2351       .access = PL1_RW, .accessfn = access_tvm_trvm,
2352       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2353                              offsetof(CPUARMState, cp15.mair1_ns) },
2354       .resetfn = arm_cp_reset_ignore },
2355     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2356       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2357       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2358     /* 32 bit ITLB invalidates */
2359     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2360       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2361       .writefn = tlbiall_write },
2362     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2363       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2364       .writefn = tlbimva_write },
2365     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2366       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2367       .writefn = tlbiasid_write },
2368     /* 32 bit DTLB invalidates */
2369     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2370       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2371       .writefn = tlbiall_write },
2372     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2373       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2374       .writefn = tlbimva_write },
2375     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2376       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2377       .writefn = tlbiasid_write },
2378     /* 32 bit TLB invalidates */
2379     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2380       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2381       .writefn = tlbiall_write },
2382     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2383       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2384       .writefn = tlbimva_write },
2385     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2386       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2387       .writefn = tlbiasid_write },
2388     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2389       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2390       .writefn = tlbimvaa_write },
2391     REGINFO_SENTINEL
2392 };
2393 
2394 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2395     /* 32 bit TLB invalidates, Inner Shareable */
2396     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2397       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2398       .writefn = tlbiall_is_write },
2399     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2400       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2401       .writefn = tlbimva_is_write },
2402     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2403       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2404       .writefn = tlbiasid_is_write },
2405     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2406       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2407       .writefn = tlbimvaa_is_write },
2408     REGINFO_SENTINEL
2409 };
2410 
2411 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2412     /* PMOVSSET is not implemented in v7 before v7ve */
2413     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2414       .access = PL0_RW, .accessfn = pmreg_access,
2415       .type = ARM_CP_ALIAS | ARM_CP_IO,
2416       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2417       .writefn = pmovsset_write,
2418       .raw_writefn = raw_write },
2419     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2420       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2421       .access = PL0_RW, .accessfn = pmreg_access,
2422       .type = ARM_CP_ALIAS | ARM_CP_IO,
2423       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2424       .writefn = pmovsset_write,
2425       .raw_writefn = raw_write },
2426     REGINFO_SENTINEL
2427 };
2428 
2429 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2430                         uint64_t value)
2431 {
2432     value &= 1;
2433     env->teecr = value;
2434 }
2435 
2436 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2437                                     bool isread)
2438 {
2439     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2440         return CP_ACCESS_TRAP;
2441     }
2442     return CP_ACCESS_OK;
2443 }
2444 
2445 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2446     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2447       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2448       .resetvalue = 0,
2449       .writefn = teecr_write },
2450     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2451       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2452       .accessfn = teehbr_access, .resetvalue = 0 },
2453     REGINFO_SENTINEL
2454 };
2455 
2456 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2457     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2458       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2459       .access = PL0_RW,
2460       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2461     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2462       .access = PL0_RW,
2463       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2464                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2465       .resetfn = arm_cp_reset_ignore },
2466     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2467       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2468       .access = PL0_R|PL1_W,
2469       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2470       .resetvalue = 0},
2471     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2472       .access = PL0_R|PL1_W,
2473       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2474                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2475       .resetfn = arm_cp_reset_ignore },
2476     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2477       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2478       .access = PL1_RW,
2479       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2480     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2481       .access = PL1_RW,
2482       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2483                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2484       .resetvalue = 0 },
2485     REGINFO_SENTINEL
2486 };
2487 
2488 #ifndef CONFIG_USER_ONLY
2489 
2490 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2491                                        bool isread)
2492 {
2493     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2494      * Writable only at the highest implemented exception level.
2495      */
2496     int el = arm_current_el(env);
2497     uint64_t hcr;
2498     uint32_t cntkctl;
2499 
2500     switch (el) {
2501     case 0:
2502         hcr = arm_hcr_el2_eff(env);
2503         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2504             cntkctl = env->cp15.cnthctl_el2;
2505         } else {
2506             cntkctl = env->cp15.c14_cntkctl;
2507         }
2508         if (!extract32(cntkctl, 0, 2)) {
2509             return CP_ACCESS_TRAP;
2510         }
2511         break;
2512     case 1:
2513         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2514             arm_is_secure_below_el3(env)) {
2515             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2516             return CP_ACCESS_TRAP_UNCATEGORIZED;
2517         }
2518         break;
2519     case 2:
2520     case 3:
2521         break;
2522     }
2523 
2524     if (!isread && el < arm_highest_el(env)) {
2525         return CP_ACCESS_TRAP_UNCATEGORIZED;
2526     }
2527 
2528     return CP_ACCESS_OK;
2529 }
2530 
2531 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2532                                         bool isread)
2533 {
2534     unsigned int cur_el = arm_current_el(env);
2535     bool has_el2 = arm_is_el2_enabled(env);
2536     uint64_t hcr = arm_hcr_el2_eff(env);
2537 
2538     switch (cur_el) {
2539     case 0:
2540         /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2541         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2542             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2543                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2544         }
2545 
2546         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2547         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2548             return CP_ACCESS_TRAP;
2549         }
2550 
2551         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2552         if (hcr & HCR_E2H) {
2553             if (timeridx == GTIMER_PHYS &&
2554                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2555                 return CP_ACCESS_TRAP_EL2;
2556             }
2557         } else {
2558             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2559             if (has_el2 && timeridx == GTIMER_PHYS &&
2560                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2561                 return CP_ACCESS_TRAP_EL2;
2562             }
2563         }
2564         break;
2565 
2566     case 1:
2567         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2568         if (has_el2 && timeridx == GTIMER_PHYS &&
2569             (hcr & HCR_E2H
2570              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2571              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2572             return CP_ACCESS_TRAP_EL2;
2573         }
2574         break;
2575     }
2576     return CP_ACCESS_OK;
2577 }
2578 
2579 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2580                                       bool isread)
2581 {
2582     unsigned int cur_el = arm_current_el(env);
2583     bool has_el2 = arm_is_el2_enabled(env);
2584     uint64_t hcr = arm_hcr_el2_eff(env);
2585 
2586     switch (cur_el) {
2587     case 0:
2588         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2589             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2590             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2591                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2592         }
2593 
2594         /*
2595          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2596          * EL0 if EL0[PV]TEN is zero.
2597          */
2598         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2599             return CP_ACCESS_TRAP;
2600         }
2601         /* fall through */
2602 
2603     case 1:
2604         if (has_el2 && timeridx == GTIMER_PHYS) {
2605             if (hcr & HCR_E2H) {
2606                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2607                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2608                     return CP_ACCESS_TRAP_EL2;
2609                 }
2610             } else {
2611                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2612                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2613                     return CP_ACCESS_TRAP_EL2;
2614                 }
2615             }
2616         }
2617         break;
2618     }
2619     return CP_ACCESS_OK;
2620 }
2621 
2622 static CPAccessResult gt_pct_access(CPUARMState *env,
2623                                     const ARMCPRegInfo *ri,
2624                                     bool isread)
2625 {
2626     return gt_counter_access(env, GTIMER_PHYS, isread);
2627 }
2628 
2629 static CPAccessResult gt_vct_access(CPUARMState *env,
2630                                     const ARMCPRegInfo *ri,
2631                                     bool isread)
2632 {
2633     return gt_counter_access(env, GTIMER_VIRT, isread);
2634 }
2635 
2636 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2637                                        bool isread)
2638 {
2639     return gt_timer_access(env, GTIMER_PHYS, isread);
2640 }
2641 
2642 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2643                                        bool isread)
2644 {
2645     return gt_timer_access(env, GTIMER_VIRT, isread);
2646 }
2647 
2648 static CPAccessResult gt_stimer_access(CPUARMState *env,
2649                                        const ARMCPRegInfo *ri,
2650                                        bool isread)
2651 {
2652     /* The AArch64 register view of the secure physical timer is
2653      * always accessible from EL3, and configurably accessible from
2654      * Secure EL1.
2655      */
2656     switch (arm_current_el(env)) {
2657     case 1:
2658         if (!arm_is_secure(env)) {
2659             return CP_ACCESS_TRAP;
2660         }
2661         if (!(env->cp15.scr_el3 & SCR_ST)) {
2662             return CP_ACCESS_TRAP_EL3;
2663         }
2664         return CP_ACCESS_OK;
2665     case 0:
2666     case 2:
2667         return CP_ACCESS_TRAP;
2668     case 3:
2669         return CP_ACCESS_OK;
2670     default:
2671         g_assert_not_reached();
2672     }
2673 }
2674 
2675 static uint64_t gt_get_countervalue(CPUARMState *env)
2676 {
2677     ARMCPU *cpu = env_archcpu(env);
2678 
2679     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2680 }
2681 
2682 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2683 {
2684     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2685 
2686     if (gt->ctl & 1) {
2687         /* Timer enabled: calculate and set current ISTATUS, irq, and
2688          * reset timer to when ISTATUS next has to change
2689          */
2690         uint64_t offset = timeridx == GTIMER_VIRT ?
2691                                       cpu->env.cp15.cntvoff_el2 : 0;
2692         uint64_t count = gt_get_countervalue(&cpu->env);
2693         /* Note that this must be unsigned 64 bit arithmetic: */
2694         int istatus = count - offset >= gt->cval;
2695         uint64_t nexttick;
2696         int irqstate;
2697 
2698         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2699 
2700         irqstate = (istatus && !(gt->ctl & 2));
2701         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2702 
2703         if (istatus) {
2704             /* Next transition is when count rolls back over to zero */
2705             nexttick = UINT64_MAX;
2706         } else {
2707             /* Next transition is when we hit cval */
2708             nexttick = gt->cval + offset;
2709         }
2710         /* Note that the desired next expiry time might be beyond the
2711          * signed-64-bit range of a QEMUTimer -- in this case we just
2712          * set the timer for as far in the future as possible. When the
2713          * timer expires we will reset the timer for any remaining period.
2714          */
2715         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2716             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2717         } else {
2718             timer_mod(cpu->gt_timer[timeridx], nexttick);
2719         }
2720         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2721     } else {
2722         /* Timer disabled: ISTATUS and timer output always clear */
2723         gt->ctl &= ~4;
2724         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2725         timer_del(cpu->gt_timer[timeridx]);
2726         trace_arm_gt_recalc_disabled(timeridx);
2727     }
2728 }
2729 
2730 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2731                            int timeridx)
2732 {
2733     ARMCPU *cpu = env_archcpu(env);
2734 
2735     timer_del(cpu->gt_timer[timeridx]);
2736 }
2737 
2738 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2739 {
2740     return gt_get_countervalue(env);
2741 }
2742 
2743 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2744 {
2745     uint64_t hcr;
2746 
2747     switch (arm_current_el(env)) {
2748     case 2:
2749         hcr = arm_hcr_el2_eff(env);
2750         if (hcr & HCR_E2H) {
2751             return 0;
2752         }
2753         break;
2754     case 0:
2755         hcr = arm_hcr_el2_eff(env);
2756         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2757             return 0;
2758         }
2759         break;
2760     }
2761 
2762     return env->cp15.cntvoff_el2;
2763 }
2764 
2765 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2766 {
2767     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2768 }
2769 
2770 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2771                           int timeridx,
2772                           uint64_t value)
2773 {
2774     trace_arm_gt_cval_write(timeridx, value);
2775     env->cp15.c14_timer[timeridx].cval = value;
2776     gt_recalc_timer(env_archcpu(env), timeridx);
2777 }
2778 
2779 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2780                              int timeridx)
2781 {
2782     uint64_t offset = 0;
2783 
2784     switch (timeridx) {
2785     case GTIMER_VIRT:
2786     case GTIMER_HYPVIRT:
2787         offset = gt_virt_cnt_offset(env);
2788         break;
2789     }
2790 
2791     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2792                       (gt_get_countervalue(env) - offset));
2793 }
2794 
2795 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2796                           int timeridx,
2797                           uint64_t value)
2798 {
2799     uint64_t offset = 0;
2800 
2801     switch (timeridx) {
2802     case GTIMER_VIRT:
2803     case GTIMER_HYPVIRT:
2804         offset = gt_virt_cnt_offset(env);
2805         break;
2806     }
2807 
2808     trace_arm_gt_tval_write(timeridx, value);
2809     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2810                                          sextract64(value, 0, 32);
2811     gt_recalc_timer(env_archcpu(env), timeridx);
2812 }
2813 
2814 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2815                          int timeridx,
2816                          uint64_t value)
2817 {
2818     ARMCPU *cpu = env_archcpu(env);
2819     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2820 
2821     trace_arm_gt_ctl_write(timeridx, value);
2822     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2823     if ((oldval ^ value) & 1) {
2824         /* Enable toggled */
2825         gt_recalc_timer(cpu, timeridx);
2826     } else if ((oldval ^ value) & 2) {
2827         /* IMASK toggled: don't need to recalculate,
2828          * just set the interrupt line based on ISTATUS
2829          */
2830         int irqstate = (oldval & 4) && !(value & 2);
2831 
2832         trace_arm_gt_imask_toggle(timeridx, irqstate);
2833         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2834     }
2835 }
2836 
2837 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2838 {
2839     gt_timer_reset(env, ri, GTIMER_PHYS);
2840 }
2841 
2842 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2843                                uint64_t value)
2844 {
2845     gt_cval_write(env, ri, GTIMER_PHYS, value);
2846 }
2847 
2848 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2849 {
2850     return gt_tval_read(env, ri, GTIMER_PHYS);
2851 }
2852 
2853 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2854                                uint64_t value)
2855 {
2856     gt_tval_write(env, ri, GTIMER_PHYS, value);
2857 }
2858 
2859 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2860                               uint64_t value)
2861 {
2862     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2863 }
2864 
2865 static int gt_phys_redir_timeridx(CPUARMState *env)
2866 {
2867     switch (arm_mmu_idx(env)) {
2868     case ARMMMUIdx_E20_0:
2869     case ARMMMUIdx_E20_2:
2870     case ARMMMUIdx_E20_2_PAN:
2871     case ARMMMUIdx_SE20_0:
2872     case ARMMMUIdx_SE20_2:
2873     case ARMMMUIdx_SE20_2_PAN:
2874         return GTIMER_HYP;
2875     default:
2876         return GTIMER_PHYS;
2877     }
2878 }
2879 
2880 static int gt_virt_redir_timeridx(CPUARMState *env)
2881 {
2882     switch (arm_mmu_idx(env)) {
2883     case ARMMMUIdx_E20_0:
2884     case ARMMMUIdx_E20_2:
2885     case ARMMMUIdx_E20_2_PAN:
2886     case ARMMMUIdx_SE20_0:
2887     case ARMMMUIdx_SE20_2:
2888     case ARMMMUIdx_SE20_2_PAN:
2889         return GTIMER_HYPVIRT;
2890     default:
2891         return GTIMER_VIRT;
2892     }
2893 }
2894 
2895 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2896                                         const ARMCPRegInfo *ri)
2897 {
2898     int timeridx = gt_phys_redir_timeridx(env);
2899     return env->cp15.c14_timer[timeridx].cval;
2900 }
2901 
2902 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2903                                      uint64_t value)
2904 {
2905     int timeridx = gt_phys_redir_timeridx(env);
2906     gt_cval_write(env, ri, timeridx, value);
2907 }
2908 
2909 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2910                                         const ARMCPRegInfo *ri)
2911 {
2912     int timeridx = gt_phys_redir_timeridx(env);
2913     return gt_tval_read(env, ri, timeridx);
2914 }
2915 
2916 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2917                                      uint64_t value)
2918 {
2919     int timeridx = gt_phys_redir_timeridx(env);
2920     gt_tval_write(env, ri, timeridx, value);
2921 }
2922 
2923 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2924                                        const ARMCPRegInfo *ri)
2925 {
2926     int timeridx = gt_phys_redir_timeridx(env);
2927     return env->cp15.c14_timer[timeridx].ctl;
2928 }
2929 
2930 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2931                                     uint64_t value)
2932 {
2933     int timeridx = gt_phys_redir_timeridx(env);
2934     gt_ctl_write(env, ri, timeridx, value);
2935 }
2936 
2937 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2938 {
2939     gt_timer_reset(env, ri, GTIMER_VIRT);
2940 }
2941 
2942 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2943                                uint64_t value)
2944 {
2945     gt_cval_write(env, ri, GTIMER_VIRT, value);
2946 }
2947 
2948 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2949 {
2950     return gt_tval_read(env, ri, GTIMER_VIRT);
2951 }
2952 
2953 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2954                                uint64_t value)
2955 {
2956     gt_tval_write(env, ri, GTIMER_VIRT, value);
2957 }
2958 
2959 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2960                               uint64_t value)
2961 {
2962     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2963 }
2964 
2965 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2966                               uint64_t value)
2967 {
2968     ARMCPU *cpu = env_archcpu(env);
2969 
2970     trace_arm_gt_cntvoff_write(value);
2971     raw_write(env, ri, value);
2972     gt_recalc_timer(cpu, GTIMER_VIRT);
2973 }
2974 
2975 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
2976                                         const ARMCPRegInfo *ri)
2977 {
2978     int timeridx = gt_virt_redir_timeridx(env);
2979     return env->cp15.c14_timer[timeridx].cval;
2980 }
2981 
2982 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2983                                      uint64_t value)
2984 {
2985     int timeridx = gt_virt_redir_timeridx(env);
2986     gt_cval_write(env, ri, timeridx, value);
2987 }
2988 
2989 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
2990                                         const ARMCPRegInfo *ri)
2991 {
2992     int timeridx = gt_virt_redir_timeridx(env);
2993     return gt_tval_read(env, ri, timeridx);
2994 }
2995 
2996 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2997                                      uint64_t value)
2998 {
2999     int timeridx = gt_virt_redir_timeridx(env);
3000     gt_tval_write(env, ri, timeridx, value);
3001 }
3002 
3003 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
3004                                        const ARMCPRegInfo *ri)
3005 {
3006     int timeridx = gt_virt_redir_timeridx(env);
3007     return env->cp15.c14_timer[timeridx].ctl;
3008 }
3009 
3010 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3011                                     uint64_t value)
3012 {
3013     int timeridx = gt_virt_redir_timeridx(env);
3014     gt_ctl_write(env, ri, timeridx, value);
3015 }
3016 
3017 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3018 {
3019     gt_timer_reset(env, ri, GTIMER_HYP);
3020 }
3021 
3022 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3023                               uint64_t value)
3024 {
3025     gt_cval_write(env, ri, GTIMER_HYP, value);
3026 }
3027 
3028 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3029 {
3030     return gt_tval_read(env, ri, GTIMER_HYP);
3031 }
3032 
3033 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3034                               uint64_t value)
3035 {
3036     gt_tval_write(env, ri, GTIMER_HYP, value);
3037 }
3038 
3039 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3040                               uint64_t value)
3041 {
3042     gt_ctl_write(env, ri, GTIMER_HYP, value);
3043 }
3044 
3045 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3046 {
3047     gt_timer_reset(env, ri, GTIMER_SEC);
3048 }
3049 
3050 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3051                               uint64_t value)
3052 {
3053     gt_cval_write(env, ri, GTIMER_SEC, value);
3054 }
3055 
3056 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3057 {
3058     return gt_tval_read(env, ri, GTIMER_SEC);
3059 }
3060 
3061 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3062                               uint64_t value)
3063 {
3064     gt_tval_write(env, ri, GTIMER_SEC, value);
3065 }
3066 
3067 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3068                               uint64_t value)
3069 {
3070     gt_ctl_write(env, ri, GTIMER_SEC, value);
3071 }
3072 
3073 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3074 {
3075     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
3076 }
3077 
3078 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3079                              uint64_t value)
3080 {
3081     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
3082 }
3083 
3084 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3085 {
3086     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
3087 }
3088 
3089 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3090                              uint64_t value)
3091 {
3092     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
3093 }
3094 
3095 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3096                             uint64_t value)
3097 {
3098     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
3099 }
3100 
3101 void arm_gt_ptimer_cb(void *opaque)
3102 {
3103     ARMCPU *cpu = opaque;
3104 
3105     gt_recalc_timer(cpu, GTIMER_PHYS);
3106 }
3107 
3108 void arm_gt_vtimer_cb(void *opaque)
3109 {
3110     ARMCPU *cpu = opaque;
3111 
3112     gt_recalc_timer(cpu, GTIMER_VIRT);
3113 }
3114 
3115 void arm_gt_htimer_cb(void *opaque)
3116 {
3117     ARMCPU *cpu = opaque;
3118 
3119     gt_recalc_timer(cpu, GTIMER_HYP);
3120 }
3121 
3122 void arm_gt_stimer_cb(void *opaque)
3123 {
3124     ARMCPU *cpu = opaque;
3125 
3126     gt_recalc_timer(cpu, GTIMER_SEC);
3127 }
3128 
3129 void arm_gt_hvtimer_cb(void *opaque)
3130 {
3131     ARMCPU *cpu = opaque;
3132 
3133     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
3134 }
3135 
3136 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
3137 {
3138     ARMCPU *cpu = env_archcpu(env);
3139 
3140     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
3141 }
3142 
3143 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3144     /* Note that CNTFRQ is purely reads-as-written for the benefit
3145      * of software; writing it doesn't actually change the timer frequency.
3146      * Our reset value matches the fixed frequency we implement the timer at.
3147      */
3148     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
3149       .type = ARM_CP_ALIAS,
3150       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3151       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
3152     },
3153     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3154       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3155       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3156       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3157       .resetfn = arm_gt_cntfrq_reset,
3158     },
3159     /* overall control: mostly access permissions */
3160     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
3161       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
3162       .access = PL1_RW,
3163       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
3164       .resetvalue = 0,
3165     },
3166     /* per-timer control */
3167     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3168       .secure = ARM_CP_SECSTATE_NS,
3169       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3170       .accessfn = gt_ptimer_access,
3171       .fieldoffset = offsetoflow32(CPUARMState,
3172                                    cp15.c14_timer[GTIMER_PHYS].ctl),
3173       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3174       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3175     },
3176     { .name = "CNTP_CTL_S",
3177       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3178       .secure = ARM_CP_SECSTATE_S,
3179       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3180       .accessfn = gt_ptimer_access,
3181       .fieldoffset = offsetoflow32(CPUARMState,
3182                                    cp15.c14_timer[GTIMER_SEC].ctl),
3183       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3184     },
3185     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
3186       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
3187       .type = ARM_CP_IO, .access = PL0_RW,
3188       .accessfn = gt_ptimer_access,
3189       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
3190       .resetvalue = 0,
3191       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3192       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3193     },
3194     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
3195       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3196       .accessfn = gt_vtimer_access,
3197       .fieldoffset = offsetoflow32(CPUARMState,
3198                                    cp15.c14_timer[GTIMER_VIRT].ctl),
3199       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3200       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3201     },
3202     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
3203       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
3204       .type = ARM_CP_IO, .access = PL0_RW,
3205       .accessfn = gt_vtimer_access,
3206       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
3207       .resetvalue = 0,
3208       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3209       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3210     },
3211     /* TimerValue views: a 32 bit downcounting view of the underlying state */
3212     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3213       .secure = ARM_CP_SECSTATE_NS,
3214       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3215       .accessfn = gt_ptimer_access,
3216       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3217     },
3218     { .name = "CNTP_TVAL_S",
3219       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3220       .secure = ARM_CP_SECSTATE_S,
3221       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3222       .accessfn = gt_ptimer_access,
3223       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
3224     },
3225     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3226       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
3227       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3228       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
3229       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3230     },
3231     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
3232       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3233       .accessfn = gt_vtimer_access,
3234       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3235     },
3236     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3237       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
3238       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3239       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
3240       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3241     },
3242     /* The counter itself */
3243     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
3244       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3245       .accessfn = gt_pct_access,
3246       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
3247     },
3248     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
3249       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
3250       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3251       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
3252     },
3253     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3254       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3255       .accessfn = gt_vct_access,
3256       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3257     },
3258     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3259       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3260       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3261       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3262     },
3263     /* Comparison value, indicating when the timer goes off */
3264     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3265       .secure = ARM_CP_SECSTATE_NS,
3266       .access = PL0_RW,
3267       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3268       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3269       .accessfn = gt_ptimer_access,
3270       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3271       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3272     },
3273     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3274       .secure = ARM_CP_SECSTATE_S,
3275       .access = PL0_RW,
3276       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3277       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3278       .accessfn = gt_ptimer_access,
3279       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3280     },
3281     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3282       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3283       .access = PL0_RW,
3284       .type = ARM_CP_IO,
3285       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3286       .resetvalue = 0, .accessfn = gt_ptimer_access,
3287       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3288       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3289     },
3290     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3291       .access = PL0_RW,
3292       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3293       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3294       .accessfn = gt_vtimer_access,
3295       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3296       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3297     },
3298     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3299       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3300       .access = PL0_RW,
3301       .type = ARM_CP_IO,
3302       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3303       .resetvalue = 0, .accessfn = gt_vtimer_access,
3304       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3305       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3306     },
3307     /* Secure timer -- this is actually restricted to only EL3
3308      * and configurably Secure-EL1 via the accessfn.
3309      */
3310     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3311       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3312       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3313       .accessfn = gt_stimer_access,
3314       .readfn = gt_sec_tval_read,
3315       .writefn = gt_sec_tval_write,
3316       .resetfn = gt_sec_timer_reset,
3317     },
3318     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3319       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3320       .type = ARM_CP_IO, .access = PL1_RW,
3321       .accessfn = gt_stimer_access,
3322       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3323       .resetvalue = 0,
3324       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3325     },
3326     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3327       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3328       .type = ARM_CP_IO, .access = PL1_RW,
3329       .accessfn = gt_stimer_access,
3330       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3331       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3332     },
3333     REGINFO_SENTINEL
3334 };
3335 
3336 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3337                                  bool isread)
3338 {
3339     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3340         return CP_ACCESS_TRAP;
3341     }
3342     return CP_ACCESS_OK;
3343 }
3344 
3345 #else
3346 
3347 /* In user-mode most of the generic timer registers are inaccessible
3348  * however modern kernels (4.12+) allow access to cntvct_el0
3349  */
3350 
3351 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3352 {
3353     ARMCPU *cpu = env_archcpu(env);
3354 
3355     /* Currently we have no support for QEMUTimer in linux-user so we
3356      * can't call gt_get_countervalue(env), instead we directly
3357      * call the lower level functions.
3358      */
3359     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3360 }
3361 
3362 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3363     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3364       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3365       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3366       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3367       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3368     },
3369     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3370       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3371       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3372       .readfn = gt_virt_cnt_read,
3373     },
3374     REGINFO_SENTINEL
3375 };
3376 
3377 #endif
3378 
3379 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3380 {
3381     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3382         raw_write(env, ri, value);
3383     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3384         raw_write(env, ri, value & 0xfffff6ff);
3385     } else {
3386         raw_write(env, ri, value & 0xfffff1ff);
3387     }
3388 }
3389 
3390 #ifndef CONFIG_USER_ONLY
3391 /* get_phys_addr() isn't present for user-mode-only targets */
3392 
3393 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3394                                  bool isread)
3395 {
3396     if (ri->opc2 & 4) {
3397         /* The ATS12NSO* operations must trap to EL3 or EL2 if executed in
3398          * Secure EL1 (which can only happen if EL3 is AArch64).
3399          * They are simply UNDEF if executed from NS EL1.
3400          * They function normally from EL2 or EL3.
3401          */
3402         if (arm_current_el(env) == 1) {
3403             if (arm_is_secure_below_el3(env)) {
3404                 if (env->cp15.scr_el3 & SCR_EEL2) {
3405                     return CP_ACCESS_TRAP_UNCATEGORIZED_EL2;
3406                 }
3407                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3408             }
3409             return CP_ACCESS_TRAP_UNCATEGORIZED;
3410         }
3411     }
3412     return CP_ACCESS_OK;
3413 }
3414 
3415 #ifdef CONFIG_TCG
3416 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3417                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3418 {
3419     hwaddr phys_addr;
3420     target_ulong page_size;
3421     int prot;
3422     bool ret;
3423     uint64_t par64;
3424     bool format64 = false;
3425     MemTxAttrs attrs = {};
3426     ARMMMUFaultInfo fi = {};
3427     ARMCacheAttrs cacheattrs = {};
3428 
3429     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3430                         &prot, &page_size, &fi, &cacheattrs);
3431 
3432     if (ret) {
3433         /*
3434          * Some kinds of translation fault must cause exceptions rather
3435          * than being reported in the PAR.
3436          */
3437         int current_el = arm_current_el(env);
3438         int target_el;
3439         uint32_t syn, fsr, fsc;
3440         bool take_exc = false;
3441 
3442         if (fi.s1ptw && current_el == 1
3443             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3444             /*
3445              * Synchronous stage 2 fault on an access made as part of the
3446              * translation table walk for AT S1E0* or AT S1E1* insn
3447              * executed from NS EL1. If this is a synchronous external abort
3448              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3449              * to EL3. Otherwise the fault is taken as an exception to EL2,
3450              * and HPFAR_EL2 holds the faulting IPA.
3451              */
3452             if (fi.type == ARMFault_SyncExternalOnWalk &&
3453                 (env->cp15.scr_el3 & SCR_EA)) {
3454                 target_el = 3;
3455             } else {
3456                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3457                 if (arm_is_secure_below_el3(env) && fi.s1ns) {
3458                     env->cp15.hpfar_el2 |= HPFAR_NS;
3459                 }
3460                 target_el = 2;
3461             }
3462             take_exc = true;
3463         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3464             /*
3465              * Synchronous external aborts during a translation table walk
3466              * are taken as Data Abort exceptions.
3467              */
3468             if (fi.stage2) {
3469                 if (current_el == 3) {
3470                     target_el = 3;
3471                 } else {
3472                     target_el = 2;
3473                 }
3474             } else {
3475                 target_el = exception_target_el(env);
3476             }
3477             take_exc = true;
3478         }
3479 
3480         if (take_exc) {
3481             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3482             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3483                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3484                 fsr = arm_fi_to_lfsc(&fi);
3485                 fsc = extract32(fsr, 0, 6);
3486             } else {
3487                 fsr = arm_fi_to_sfsc(&fi);
3488                 fsc = 0x3f;
3489             }
3490             /*
3491              * Report exception with ESR indicating a fault due to a
3492              * translation table walk for a cache maintenance instruction.
3493              */
3494             syn = syn_data_abort_no_iss(current_el == target_el, 0,
3495                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3496             env->exception.vaddress = value;
3497             env->exception.fsr = fsr;
3498             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3499         }
3500     }
3501 
3502     if (is_a64(env)) {
3503         format64 = true;
3504     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3505         /*
3506          * ATS1Cxx:
3507          * * TTBCR.EAE determines whether the result is returned using the
3508          *   32-bit or the 64-bit PAR format
3509          * * Instructions executed in Hyp mode always use the 64bit format
3510          *
3511          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3512          * * The Non-secure TTBCR.EAE bit is set to 1
3513          * * The implementation includes EL2, and the value of HCR.VM is 1
3514          *
3515          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3516          *
3517          * ATS1Hx always uses the 64bit format.
3518          */
3519         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3520 
3521         if (arm_feature(env, ARM_FEATURE_EL2)) {
3522             if (mmu_idx == ARMMMUIdx_E10_0 ||
3523                 mmu_idx == ARMMMUIdx_E10_1 ||
3524                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3525                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3526             } else {
3527                 format64 |= arm_current_el(env) == 2;
3528             }
3529         }
3530     }
3531 
3532     if (format64) {
3533         /* Create a 64-bit PAR */
3534         par64 = (1 << 11); /* LPAE bit always set */
3535         if (!ret) {
3536             par64 |= phys_addr & ~0xfffULL;
3537             if (!attrs.secure) {
3538                 par64 |= (1 << 9); /* NS */
3539             }
3540             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3541             par64 |= cacheattrs.shareability << 7; /* SH */
3542         } else {
3543             uint32_t fsr = arm_fi_to_lfsc(&fi);
3544 
3545             par64 |= 1; /* F */
3546             par64 |= (fsr & 0x3f) << 1; /* FS */
3547             if (fi.stage2) {
3548                 par64 |= (1 << 9); /* S */
3549             }
3550             if (fi.s1ptw) {
3551                 par64 |= (1 << 8); /* PTW */
3552             }
3553         }
3554     } else {
3555         /* fsr is a DFSR/IFSR value for the short descriptor
3556          * translation table format (with WnR always clear).
3557          * Convert it to a 32-bit PAR.
3558          */
3559         if (!ret) {
3560             /* We do not set any attribute bits in the PAR */
3561             if (page_size == (1 << 24)
3562                 && arm_feature(env, ARM_FEATURE_V7)) {
3563                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3564             } else {
3565                 par64 = phys_addr & 0xfffff000;
3566             }
3567             if (!attrs.secure) {
3568                 par64 |= (1 << 9); /* NS */
3569             }
3570         } else {
3571             uint32_t fsr = arm_fi_to_sfsc(&fi);
3572 
3573             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3574                     ((fsr & 0xf) << 1) | 1;
3575         }
3576     }
3577     return par64;
3578 }
3579 #endif /* CONFIG_TCG */
3580 
3581 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3582 {
3583 #ifdef CONFIG_TCG
3584     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3585     uint64_t par64;
3586     ARMMMUIdx mmu_idx;
3587     int el = arm_current_el(env);
3588     bool secure = arm_is_secure_below_el3(env);
3589 
3590     switch (ri->opc2 & 6) {
3591     case 0:
3592         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3593         switch (el) {
3594         case 3:
3595             mmu_idx = ARMMMUIdx_SE3;
3596             break;
3597         case 2:
3598             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3599             /* fall through */
3600         case 1:
3601             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3602                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3603                            : ARMMMUIdx_Stage1_E1_PAN);
3604             } else {
3605                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3606             }
3607             break;
3608         default:
3609             g_assert_not_reached();
3610         }
3611         break;
3612     case 2:
3613         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3614         switch (el) {
3615         case 3:
3616             mmu_idx = ARMMMUIdx_SE10_0;
3617             break;
3618         case 2:
3619             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3620             mmu_idx = ARMMMUIdx_Stage1_E0;
3621             break;
3622         case 1:
3623             mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3624             break;
3625         default:
3626             g_assert_not_reached();
3627         }
3628         break;
3629     case 4:
3630         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3631         mmu_idx = ARMMMUIdx_E10_1;
3632         break;
3633     case 6:
3634         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3635         mmu_idx = ARMMMUIdx_E10_0;
3636         break;
3637     default:
3638         g_assert_not_reached();
3639     }
3640 
3641     par64 = do_ats_write(env, value, access_type, mmu_idx);
3642 
3643     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3644 #else
3645     /* Handled by hardware accelerator. */
3646     g_assert_not_reached();
3647 #endif /* CONFIG_TCG */
3648 }
3649 
3650 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3651                         uint64_t value)
3652 {
3653 #ifdef CONFIG_TCG
3654     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3655     uint64_t par64;
3656 
3657     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3658 
3659     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3660 #else
3661     /* Handled by hardware accelerator. */
3662     g_assert_not_reached();
3663 #endif /* CONFIG_TCG */
3664 }
3665 
3666 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3667                                      bool isread)
3668 {
3669     if (arm_current_el(env) == 3 &&
3670         !(env->cp15.scr_el3 & (SCR_NS | SCR_EEL2))) {
3671         return CP_ACCESS_TRAP;
3672     }
3673     return CP_ACCESS_OK;
3674 }
3675 
3676 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3677                         uint64_t value)
3678 {
3679 #ifdef CONFIG_TCG
3680     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3681     ARMMMUIdx mmu_idx;
3682     int secure = arm_is_secure_below_el3(env);
3683 
3684     switch (ri->opc2 & 6) {
3685     case 0:
3686         switch (ri->opc1) {
3687         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3688             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3689                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3690                            : ARMMMUIdx_Stage1_E1_PAN);
3691             } else {
3692                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3693             }
3694             break;
3695         case 4: /* AT S1E2R, AT S1E2W */
3696             mmu_idx = secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2;
3697             break;
3698         case 6: /* AT S1E3R, AT S1E3W */
3699             mmu_idx = ARMMMUIdx_SE3;
3700             break;
3701         default:
3702             g_assert_not_reached();
3703         }
3704         break;
3705     case 2: /* AT S1E0R, AT S1E0W */
3706         mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3707         break;
3708     case 4: /* AT S12E1R, AT S12E1W */
3709         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3710         break;
3711     case 6: /* AT S12E0R, AT S12E0W */
3712         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3713         break;
3714     default:
3715         g_assert_not_reached();
3716     }
3717 
3718     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3719 #else
3720     /* Handled by hardware accelerator. */
3721     g_assert_not_reached();
3722 #endif /* CONFIG_TCG */
3723 }
3724 #endif
3725 
3726 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3727     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3728       .access = PL1_RW, .resetvalue = 0,
3729       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3730                              offsetoflow32(CPUARMState, cp15.par_ns) },
3731       .writefn = par_write },
3732 #ifndef CONFIG_USER_ONLY
3733     /* This underdecoding is safe because the reginfo is NO_RAW. */
3734     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3735       .access = PL1_W, .accessfn = ats_access,
3736       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3737 #endif
3738     REGINFO_SENTINEL
3739 };
3740 
3741 /* Return basic MPU access permission bits.  */
3742 static uint32_t simple_mpu_ap_bits(uint32_t val)
3743 {
3744     uint32_t ret;
3745     uint32_t mask;
3746     int i;
3747     ret = 0;
3748     mask = 3;
3749     for (i = 0; i < 16; i += 2) {
3750         ret |= (val >> i) & mask;
3751         mask <<= 2;
3752     }
3753     return ret;
3754 }
3755 
3756 /* Pad basic MPU access permission bits to extended format.  */
3757 static uint32_t extended_mpu_ap_bits(uint32_t val)
3758 {
3759     uint32_t ret;
3760     uint32_t mask;
3761     int i;
3762     ret = 0;
3763     mask = 3;
3764     for (i = 0; i < 16; i += 2) {
3765         ret |= (val & mask) << i;
3766         mask <<= 2;
3767     }
3768     return ret;
3769 }
3770 
3771 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3772                                  uint64_t value)
3773 {
3774     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3775 }
3776 
3777 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3778 {
3779     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3780 }
3781 
3782 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3783                                  uint64_t value)
3784 {
3785     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3786 }
3787 
3788 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3789 {
3790     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3791 }
3792 
3793 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3794 {
3795     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3796 
3797     if (!u32p) {
3798         return 0;
3799     }
3800 
3801     u32p += env->pmsav7.rnr[M_REG_NS];
3802     return *u32p;
3803 }
3804 
3805 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3806                          uint64_t value)
3807 {
3808     ARMCPU *cpu = env_archcpu(env);
3809     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3810 
3811     if (!u32p) {
3812         return;
3813     }
3814 
3815     u32p += env->pmsav7.rnr[M_REG_NS];
3816     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3817     *u32p = value;
3818 }
3819 
3820 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3821                               uint64_t value)
3822 {
3823     ARMCPU *cpu = env_archcpu(env);
3824     uint32_t nrgs = cpu->pmsav7_dregion;
3825 
3826     if (value >= nrgs) {
3827         qemu_log_mask(LOG_GUEST_ERROR,
3828                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3829                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3830         return;
3831     }
3832 
3833     raw_write(env, ri, value);
3834 }
3835 
3836 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3837     /* Reset for all these registers is handled in arm_cpu_reset(),
3838      * because the PMSAv7 is also used by M-profile CPUs, which do
3839      * not register cpregs but still need the state to be reset.
3840      */
3841     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3842       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3843       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3844       .readfn = pmsav7_read, .writefn = pmsav7_write,
3845       .resetfn = arm_cp_reset_ignore },
3846     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3847       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3848       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3849       .readfn = pmsav7_read, .writefn = pmsav7_write,
3850       .resetfn = arm_cp_reset_ignore },
3851     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3852       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3853       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3854       .readfn = pmsav7_read, .writefn = pmsav7_write,
3855       .resetfn = arm_cp_reset_ignore },
3856     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3857       .access = PL1_RW,
3858       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3859       .writefn = pmsav7_rgnr_write,
3860       .resetfn = arm_cp_reset_ignore },
3861     REGINFO_SENTINEL
3862 };
3863 
3864 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3865     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3866       .access = PL1_RW, .type = ARM_CP_ALIAS,
3867       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3868       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3869     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3870       .access = PL1_RW, .type = ARM_CP_ALIAS,
3871       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3872       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3873     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3874       .access = PL1_RW,
3875       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3876       .resetvalue = 0, },
3877     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3878       .access = PL1_RW,
3879       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3880       .resetvalue = 0, },
3881     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3882       .access = PL1_RW,
3883       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3884     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3885       .access = PL1_RW,
3886       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3887     /* Protection region base and size registers */
3888     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3889       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3890       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3891     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3892       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3893       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3894     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3895       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3896       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3897     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3898       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3899       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3900     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3901       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3902       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3903     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3904       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3905       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3906     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3907       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3908       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3909     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3910       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3911       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3912     REGINFO_SENTINEL
3913 };
3914 
3915 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3916                                  uint64_t value)
3917 {
3918     TCR *tcr = raw_ptr(env, ri);
3919     int maskshift = extract32(value, 0, 3);
3920 
3921     if (!arm_feature(env, ARM_FEATURE_V8)) {
3922         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3923             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3924              * using Long-desciptor translation table format */
3925             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3926         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3927             /* In an implementation that includes the Security Extensions
3928              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3929              * Short-descriptor translation table format.
3930              */
3931             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3932         } else {
3933             value &= TTBCR_N;
3934         }
3935     }
3936 
3937     /* Update the masks corresponding to the TCR bank being written
3938      * Note that we always calculate mask and base_mask, but
3939      * they are only used for short-descriptor tables (ie if EAE is 0);
3940      * for long-descriptor tables the TCR fields are used differently
3941      * and the mask and base_mask values are meaningless.
3942      */
3943     tcr->raw_tcr = value;
3944     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3945     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3946 }
3947 
3948 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3949                              uint64_t value)
3950 {
3951     ARMCPU *cpu = env_archcpu(env);
3952     TCR *tcr = raw_ptr(env, ri);
3953 
3954     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3955         /* With LPAE the TTBCR could result in a change of ASID
3956          * via the TTBCR.A1 bit, so do a TLB flush.
3957          */
3958         tlb_flush(CPU(cpu));
3959     }
3960     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3961     value = deposit64(tcr->raw_tcr, 0, 32, value);
3962     vmsa_ttbcr_raw_write(env, ri, value);
3963 }
3964 
3965 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3966 {
3967     TCR *tcr = raw_ptr(env, ri);
3968 
3969     /* Reset both the TCR as well as the masks corresponding to the bank of
3970      * the TCR being reset.
3971      */
3972     tcr->raw_tcr = 0;
3973     tcr->mask = 0;
3974     tcr->base_mask = 0xffffc000u;
3975 }
3976 
3977 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3978                                uint64_t value)
3979 {
3980     ARMCPU *cpu = env_archcpu(env);
3981     TCR *tcr = raw_ptr(env, ri);
3982 
3983     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3984     tlb_flush(CPU(cpu));
3985     tcr->raw_tcr = value;
3986 }
3987 
3988 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3989                             uint64_t value)
3990 {
3991     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3992     if (cpreg_field_is_64bit(ri) &&
3993         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3994         ARMCPU *cpu = env_archcpu(env);
3995         tlb_flush(CPU(cpu));
3996     }
3997     raw_write(env, ri, value);
3998 }
3999 
4000 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4001                                     uint64_t value)
4002 {
4003     /*
4004      * If we are running with E2&0 regime, then an ASID is active.
4005      * Flush if that might be changing.  Note we're not checking
4006      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
4007      * holds the active ASID, only checking the field that might.
4008      */
4009     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
4010         (arm_hcr_el2_eff(env) & HCR_E2H)) {
4011         uint16_t mask = ARMMMUIdxBit_E20_2 |
4012                         ARMMMUIdxBit_E20_2_PAN |
4013                         ARMMMUIdxBit_E20_0;
4014 
4015         if (arm_is_secure_below_el3(env)) {
4016             mask >>= ARM_MMU_IDX_A_NS;
4017         }
4018 
4019         tlb_flush_by_mmuidx(env_cpu(env), mask);
4020     }
4021     raw_write(env, ri, value);
4022 }
4023 
4024 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4025                         uint64_t value)
4026 {
4027     ARMCPU *cpu = env_archcpu(env);
4028     CPUState *cs = CPU(cpu);
4029 
4030     /*
4031      * A change in VMID to the stage2 page table (Stage2) invalidates
4032      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
4033      */
4034     if (raw_read(env, ri) != value) {
4035         uint16_t mask = ARMMMUIdxBit_E10_1 |
4036                         ARMMMUIdxBit_E10_1_PAN |
4037                         ARMMMUIdxBit_E10_0;
4038 
4039         if (arm_is_secure_below_el3(env)) {
4040             mask >>= ARM_MMU_IDX_A_NS;
4041         }
4042 
4043         tlb_flush_by_mmuidx(cs, mask);
4044         raw_write(env, ri, value);
4045     }
4046 }
4047 
4048 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
4049     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
4050       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
4051       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
4052                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
4053     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
4054       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4055       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
4056                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
4057     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
4058       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4059       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
4060                              offsetof(CPUARMState, cp15.dfar_ns) } },
4061     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
4062       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
4063       .access = PL1_RW, .accessfn = access_tvm_trvm,
4064       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
4065       .resetvalue = 0, },
4066     REGINFO_SENTINEL
4067 };
4068 
4069 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
4070     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
4071       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
4072       .access = PL1_RW, .accessfn = access_tvm_trvm,
4073       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
4074     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
4075       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
4076       .access = PL1_RW, .accessfn = access_tvm_trvm,
4077       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4078       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4079                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
4080     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
4081       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
4082       .access = PL1_RW, .accessfn = access_tvm_trvm,
4083       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4084       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4085                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
4086     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
4087       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4088       .access = PL1_RW, .accessfn = access_tvm_trvm,
4089       .writefn = vmsa_tcr_el12_write,
4090       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
4091       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
4092     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4093       .access = PL1_RW, .accessfn = access_tvm_trvm,
4094       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
4095       .raw_writefn = vmsa_ttbcr_raw_write,
4096       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
4097                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
4098     REGINFO_SENTINEL
4099 };
4100 
4101 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
4102  * qemu tlbs nor adjusting cached masks.
4103  */
4104 static const ARMCPRegInfo ttbcr2_reginfo = {
4105     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
4106     .access = PL1_RW, .accessfn = access_tvm_trvm,
4107     .type = ARM_CP_ALIAS,
4108     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
4109                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
4110 };
4111 
4112 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
4113                                 uint64_t value)
4114 {
4115     env->cp15.c15_ticonfig = value & 0xe7;
4116     /* The OS_TYPE bit in this register changes the reported CPUID! */
4117     env->cp15.c0_cpuid = (value & (1 << 5)) ?
4118         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
4119 }
4120 
4121 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
4122                                 uint64_t value)
4123 {
4124     env->cp15.c15_threadid = value & 0xffff;
4125 }
4126 
4127 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
4128                            uint64_t value)
4129 {
4130     /* Wait-for-interrupt (deprecated) */
4131     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
4132 }
4133 
4134 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
4135                                   uint64_t value)
4136 {
4137     /* On OMAP there are registers indicating the max/min index of dcache lines
4138      * containing a dirty line; cache flush operations have to reset these.
4139      */
4140     env->cp15.c15_i_max = 0x000;
4141     env->cp15.c15_i_min = 0xff0;
4142 }
4143 
4144 static const ARMCPRegInfo omap_cp_reginfo[] = {
4145     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
4146       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
4147       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
4148       .resetvalue = 0, },
4149     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
4150       .access = PL1_RW, .type = ARM_CP_NOP },
4151     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
4152       .access = PL1_RW,
4153       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
4154       .writefn = omap_ticonfig_write },
4155     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
4156       .access = PL1_RW,
4157       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
4158     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
4159       .access = PL1_RW, .resetvalue = 0xff0,
4160       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
4161     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
4162       .access = PL1_RW,
4163       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
4164       .writefn = omap_threadid_write },
4165     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
4166       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4167       .type = ARM_CP_NO_RAW,
4168       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
4169     /* TODO: Peripheral port remap register:
4170      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
4171      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
4172      * when MMU is off.
4173      */
4174     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
4175       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
4176       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
4177       .writefn = omap_cachemaint_write },
4178     { .name = "C9", .cp = 15, .crn = 9,
4179       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
4180       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
4181     REGINFO_SENTINEL
4182 };
4183 
4184 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4185                               uint64_t value)
4186 {
4187     env->cp15.c15_cpar = value & 0x3fff;
4188 }
4189 
4190 static const ARMCPRegInfo xscale_cp_reginfo[] = {
4191     { .name = "XSCALE_CPAR",
4192       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4193       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
4194       .writefn = xscale_cpar_write, },
4195     { .name = "XSCALE_AUXCR",
4196       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
4197       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
4198       .resetvalue = 0, },
4199     /* XScale specific cache-lockdown: since we have no cache we NOP these
4200      * and hope the guest does not really rely on cache behaviour.
4201      */
4202     { .name = "XSCALE_LOCK_ICACHE_LINE",
4203       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
4204       .access = PL1_W, .type = ARM_CP_NOP },
4205     { .name = "XSCALE_UNLOCK_ICACHE",
4206       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
4207       .access = PL1_W, .type = ARM_CP_NOP },
4208     { .name = "XSCALE_DCACHE_LOCK",
4209       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
4210       .access = PL1_RW, .type = ARM_CP_NOP },
4211     { .name = "XSCALE_UNLOCK_DCACHE",
4212       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
4213       .access = PL1_W, .type = ARM_CP_NOP },
4214     REGINFO_SENTINEL
4215 };
4216 
4217 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
4218     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
4219      * implementation of this implementation-defined space.
4220      * Ideally this should eventually disappear in favour of actually
4221      * implementing the correct behaviour for all cores.
4222      */
4223     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
4224       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4225       .access = PL1_RW,
4226       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
4227       .resetvalue = 0 },
4228     REGINFO_SENTINEL
4229 };
4230 
4231 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
4232     /* Cache status: RAZ because we have no cache so it's always clean */
4233     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
4234       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4235       .resetvalue = 0 },
4236     REGINFO_SENTINEL
4237 };
4238 
4239 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
4240     /* We never have a a block transfer operation in progress */
4241     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
4242       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4243       .resetvalue = 0 },
4244     /* The cache ops themselves: these all NOP for QEMU */
4245     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
4246       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4247     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
4248       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4249     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
4250       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4251     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4252       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4253     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4254       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4255     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4256       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4257     REGINFO_SENTINEL
4258 };
4259 
4260 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4261     /* The cache test-and-clean instructions always return (1 << 30)
4262      * to indicate that there are no dirty cache lines.
4263      */
4264     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4265       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4266       .resetvalue = (1 << 30) },
4267     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4268       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4269       .resetvalue = (1 << 30) },
4270     REGINFO_SENTINEL
4271 };
4272 
4273 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4274     /* Ignore ReadBuffer accesses */
4275     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4276       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4277       .access = PL1_RW, .resetvalue = 0,
4278       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4279     REGINFO_SENTINEL
4280 };
4281 
4282 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4283 {
4284     unsigned int cur_el = arm_current_el(env);
4285 
4286     if (arm_is_el2_enabled(env) && cur_el == 1) {
4287         return env->cp15.vpidr_el2;
4288     }
4289     return raw_read(env, ri);
4290 }
4291 
4292 static uint64_t mpidr_read_val(CPUARMState *env)
4293 {
4294     ARMCPU *cpu = env_archcpu(env);
4295     uint64_t mpidr = cpu->mp_affinity;
4296 
4297     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4298         mpidr |= (1U << 31);
4299         /* Cores which are uniprocessor (non-coherent)
4300          * but still implement the MP extensions set
4301          * bit 30. (For instance, Cortex-R5).
4302          */
4303         if (cpu->mp_is_up) {
4304             mpidr |= (1u << 30);
4305         }
4306     }
4307     return mpidr;
4308 }
4309 
4310 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4311 {
4312     unsigned int cur_el = arm_current_el(env);
4313 
4314     if (arm_is_el2_enabled(env) && cur_el == 1) {
4315         return env->cp15.vmpidr_el2;
4316     }
4317     return mpidr_read_val(env);
4318 }
4319 
4320 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4321     /* NOP AMAIR0/1 */
4322     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4323       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4324       .access = PL1_RW, .accessfn = access_tvm_trvm,
4325       .type = ARM_CP_CONST, .resetvalue = 0 },
4326     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4327     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4328       .access = PL1_RW, .accessfn = access_tvm_trvm,
4329       .type = ARM_CP_CONST, .resetvalue = 0 },
4330     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4331       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4332       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4333                              offsetof(CPUARMState, cp15.par_ns)} },
4334     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4335       .access = PL1_RW, .accessfn = access_tvm_trvm,
4336       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4337       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4338                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4339       .writefn = vmsa_ttbr_write, },
4340     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4341       .access = PL1_RW, .accessfn = access_tvm_trvm,
4342       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4343       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4344                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4345       .writefn = vmsa_ttbr_write, },
4346     REGINFO_SENTINEL
4347 };
4348 
4349 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4350 {
4351     return vfp_get_fpcr(env);
4352 }
4353 
4354 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4355                             uint64_t value)
4356 {
4357     vfp_set_fpcr(env, value);
4358 }
4359 
4360 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4361 {
4362     return vfp_get_fpsr(env);
4363 }
4364 
4365 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4366                             uint64_t value)
4367 {
4368     vfp_set_fpsr(env, value);
4369 }
4370 
4371 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4372                                        bool isread)
4373 {
4374     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4375         return CP_ACCESS_TRAP;
4376     }
4377     return CP_ACCESS_OK;
4378 }
4379 
4380 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4381                             uint64_t value)
4382 {
4383     env->daif = value & PSTATE_DAIF;
4384 }
4385 
4386 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4387 {
4388     return env->pstate & PSTATE_PAN;
4389 }
4390 
4391 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4392                            uint64_t value)
4393 {
4394     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4395 }
4396 
4397 static const ARMCPRegInfo pan_reginfo = {
4398     .name = "PAN", .state = ARM_CP_STATE_AA64,
4399     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4400     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4401     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4402 };
4403 
4404 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4405 {
4406     return env->pstate & PSTATE_UAO;
4407 }
4408 
4409 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4410                            uint64_t value)
4411 {
4412     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4413 }
4414 
4415 static const ARMCPRegInfo uao_reginfo = {
4416     .name = "UAO", .state = ARM_CP_STATE_AA64,
4417     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4418     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4419     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4420 };
4421 
4422 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4423                                               const ARMCPRegInfo *ri,
4424                                               bool isread)
4425 {
4426     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4427     switch (arm_current_el(env)) {
4428     case 0:
4429         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4430         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4431             return CP_ACCESS_TRAP;
4432         }
4433         /* fall through */
4434     case 1:
4435         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4436         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4437             return CP_ACCESS_TRAP_EL2;
4438         }
4439         break;
4440     }
4441     return CP_ACCESS_OK;
4442 }
4443 
4444 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4445                                               const ARMCPRegInfo *ri,
4446                                               bool isread)
4447 {
4448     /* Cache invalidate/clean to Point of Unification... */
4449     switch (arm_current_el(env)) {
4450     case 0:
4451         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4452         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4453             return CP_ACCESS_TRAP;
4454         }
4455         /* fall through */
4456     case 1:
4457         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4458         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4459             return CP_ACCESS_TRAP_EL2;
4460         }
4461         break;
4462     }
4463     return CP_ACCESS_OK;
4464 }
4465 
4466 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4467  * Page D4-1736 (DDI0487A.b)
4468  */
4469 
4470 static int vae1_tlbmask(CPUARMState *env)
4471 {
4472     uint64_t hcr = arm_hcr_el2_eff(env);
4473     uint16_t mask;
4474 
4475     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4476         mask = ARMMMUIdxBit_E20_2 |
4477                ARMMMUIdxBit_E20_2_PAN |
4478                ARMMMUIdxBit_E20_0;
4479     } else {
4480         mask = ARMMMUIdxBit_E10_1 |
4481                ARMMMUIdxBit_E10_1_PAN |
4482                ARMMMUIdxBit_E10_0;
4483     }
4484 
4485     if (arm_is_secure_below_el3(env)) {
4486         mask >>= ARM_MMU_IDX_A_NS;
4487     }
4488 
4489     return mask;
4490 }
4491 
4492 /* Return 56 if TBI is enabled, 64 otherwise. */
4493 static int tlbbits_for_regime(CPUARMState *env, ARMMMUIdx mmu_idx,
4494                               uint64_t addr)
4495 {
4496     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
4497     int tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
4498     int select = extract64(addr, 55, 1);
4499 
4500     return (tbi >> select) & 1 ? 56 : 64;
4501 }
4502 
4503 static int vae1_tlbbits(CPUARMState *env, uint64_t addr)
4504 {
4505     uint64_t hcr = arm_hcr_el2_eff(env);
4506     ARMMMUIdx mmu_idx;
4507 
4508     /* Only the regime of the mmu_idx below is significant. */
4509     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4510         mmu_idx = ARMMMUIdx_E20_0;
4511     } else {
4512         mmu_idx = ARMMMUIdx_E10_0;
4513     }
4514 
4515     if (arm_is_secure_below_el3(env)) {
4516         mmu_idx &= ~ARM_MMU_IDX_A_NS;
4517     }
4518 
4519     return tlbbits_for_regime(env, mmu_idx, addr);
4520 }
4521 
4522 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4523                                       uint64_t value)
4524 {
4525     CPUState *cs = env_cpu(env);
4526     int mask = vae1_tlbmask(env);
4527 
4528     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4529 }
4530 
4531 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4532                                     uint64_t value)
4533 {
4534     CPUState *cs = env_cpu(env);
4535     int mask = vae1_tlbmask(env);
4536 
4537     if (tlb_force_broadcast(env)) {
4538         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4539     } else {
4540         tlb_flush_by_mmuidx(cs, mask);
4541     }
4542 }
4543 
4544 static int alle1_tlbmask(CPUARMState *env)
4545 {
4546     /*
4547      * Note that the 'ALL' scope must invalidate both stage 1 and
4548      * stage 2 translations, whereas most other scopes only invalidate
4549      * stage 1 translations.
4550      */
4551     if (arm_is_secure_below_el3(env)) {
4552         return ARMMMUIdxBit_SE10_1 |
4553                ARMMMUIdxBit_SE10_1_PAN |
4554                ARMMMUIdxBit_SE10_0;
4555     } else {
4556         return ARMMMUIdxBit_E10_1 |
4557                ARMMMUIdxBit_E10_1_PAN |
4558                ARMMMUIdxBit_E10_0;
4559     }
4560 }
4561 
4562 static int e2_tlbmask(CPUARMState *env)
4563 {
4564     if (arm_is_secure_below_el3(env)) {
4565         return ARMMMUIdxBit_SE20_0 |
4566                ARMMMUIdxBit_SE20_2 |
4567                ARMMMUIdxBit_SE20_2_PAN |
4568                ARMMMUIdxBit_SE2;
4569     } else {
4570         return ARMMMUIdxBit_E20_0 |
4571                ARMMMUIdxBit_E20_2 |
4572                ARMMMUIdxBit_E20_2_PAN |
4573                ARMMMUIdxBit_E2;
4574     }
4575 }
4576 
4577 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4578                                   uint64_t value)
4579 {
4580     CPUState *cs = env_cpu(env);
4581     int mask = alle1_tlbmask(env);
4582 
4583     tlb_flush_by_mmuidx(cs, mask);
4584 }
4585 
4586 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4587                                   uint64_t value)
4588 {
4589     CPUState *cs = env_cpu(env);
4590     int mask = e2_tlbmask(env);
4591 
4592     tlb_flush_by_mmuidx(cs, mask);
4593 }
4594 
4595 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4596                                   uint64_t value)
4597 {
4598     ARMCPU *cpu = env_archcpu(env);
4599     CPUState *cs = CPU(cpu);
4600 
4601     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4602 }
4603 
4604 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4605                                     uint64_t value)
4606 {
4607     CPUState *cs = env_cpu(env);
4608     int mask = alle1_tlbmask(env);
4609 
4610     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4611 }
4612 
4613 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4614                                     uint64_t value)
4615 {
4616     CPUState *cs = env_cpu(env);
4617     int mask = e2_tlbmask(env);
4618 
4619     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4620 }
4621 
4622 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4623                                     uint64_t value)
4624 {
4625     CPUState *cs = env_cpu(env);
4626 
4627     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4628 }
4629 
4630 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4631                                  uint64_t value)
4632 {
4633     /* Invalidate by VA, EL2
4634      * Currently handles both VAE2 and VALE2, since we don't support
4635      * flush-last-level-only.
4636      */
4637     CPUState *cs = env_cpu(env);
4638     int mask = e2_tlbmask(env);
4639     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4640 
4641     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4642 }
4643 
4644 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4645                                  uint64_t value)
4646 {
4647     /* Invalidate by VA, EL3
4648      * Currently handles both VAE3 and VALE3, since we don't support
4649      * flush-last-level-only.
4650      */
4651     ARMCPU *cpu = env_archcpu(env);
4652     CPUState *cs = CPU(cpu);
4653     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4654 
4655     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4656 }
4657 
4658 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4659                                    uint64_t value)
4660 {
4661     CPUState *cs = env_cpu(env);
4662     int mask = vae1_tlbmask(env);
4663     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4664     int bits = vae1_tlbbits(env, pageaddr);
4665 
4666     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4667 }
4668 
4669 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4670                                  uint64_t value)
4671 {
4672     /* Invalidate by VA, EL1&0 (AArch64 version).
4673      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4674      * since we don't support flush-for-specific-ASID-only or
4675      * flush-last-level-only.
4676      */
4677     CPUState *cs = env_cpu(env);
4678     int mask = vae1_tlbmask(env);
4679     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4680     int bits = vae1_tlbbits(env, pageaddr);
4681 
4682     if (tlb_force_broadcast(env)) {
4683         tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4684     } else {
4685         tlb_flush_page_bits_by_mmuidx(cs, pageaddr, mask, bits);
4686     }
4687 }
4688 
4689 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4690                                    uint64_t value)
4691 {
4692     CPUState *cs = env_cpu(env);
4693     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4694     bool secure = arm_is_secure_below_el3(env);
4695     int mask = secure ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2;
4696     int bits = tlbbits_for_regime(env, secure ? ARMMMUIdx_E2 : ARMMMUIdx_SE2,
4697                                   pageaddr);
4698 
4699     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4700 }
4701 
4702 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4703                                    uint64_t value)
4704 {
4705     CPUState *cs = env_cpu(env);
4706     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4707     int bits = tlbbits_for_regime(env, ARMMMUIdx_SE3, pageaddr);
4708 
4709     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr,
4710                                                   ARMMMUIdxBit_SE3, bits);
4711 }
4712 
4713 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4714                                       bool isread)
4715 {
4716     int cur_el = arm_current_el(env);
4717 
4718     if (cur_el < 2) {
4719         uint64_t hcr = arm_hcr_el2_eff(env);
4720 
4721         if (cur_el == 0) {
4722             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4723                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4724                     return CP_ACCESS_TRAP_EL2;
4725                 }
4726             } else {
4727                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4728                     return CP_ACCESS_TRAP;
4729                 }
4730                 if (hcr & HCR_TDZ) {
4731                     return CP_ACCESS_TRAP_EL2;
4732                 }
4733             }
4734         } else if (hcr & HCR_TDZ) {
4735             return CP_ACCESS_TRAP_EL2;
4736         }
4737     }
4738     return CP_ACCESS_OK;
4739 }
4740 
4741 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4742 {
4743     ARMCPU *cpu = env_archcpu(env);
4744     int dzp_bit = 1 << 4;
4745 
4746     /* DZP indicates whether DC ZVA access is allowed */
4747     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4748         dzp_bit = 0;
4749     }
4750     return cpu->dcz_blocksize | dzp_bit;
4751 }
4752 
4753 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4754                                     bool isread)
4755 {
4756     if (!(env->pstate & PSTATE_SP)) {
4757         /* Access to SP_EL0 is undefined if it's being used as
4758          * the stack pointer.
4759          */
4760         return CP_ACCESS_TRAP_UNCATEGORIZED;
4761     }
4762     return CP_ACCESS_OK;
4763 }
4764 
4765 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4766 {
4767     return env->pstate & PSTATE_SP;
4768 }
4769 
4770 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4771 {
4772     update_spsel(env, val);
4773 }
4774 
4775 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4776                         uint64_t value)
4777 {
4778     ARMCPU *cpu = env_archcpu(env);
4779 
4780     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4781         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4782         value &= ~SCTLR_M;
4783     }
4784 
4785     /* ??? Lots of these bits are not implemented.  */
4786 
4787     if (ri->state == ARM_CP_STATE_AA64 && !cpu_isar_feature(aa64_mte, cpu)) {
4788         if (ri->opc1 == 6) { /* SCTLR_EL3 */
4789             value &= ~(SCTLR_ITFSB | SCTLR_TCF | SCTLR_ATA);
4790         } else {
4791             value &= ~(SCTLR_ITFSB | SCTLR_TCF0 | SCTLR_TCF |
4792                        SCTLR_ATA0 | SCTLR_ATA);
4793         }
4794     }
4795 
4796     if (raw_read(env, ri) == value) {
4797         /* Skip the TLB flush if nothing actually changed; Linux likes
4798          * to do a lot of pointless SCTLR writes.
4799          */
4800         return;
4801     }
4802 
4803     raw_write(env, ri, value);
4804 
4805     /* This may enable/disable the MMU, so do a TLB flush.  */
4806     tlb_flush(CPU(cpu));
4807 
4808     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4809         /*
4810          * Normally we would always end the TB on an SCTLR write; see the
4811          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4812          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4813          * of hflags from the translator, so do it here.
4814          */
4815         arm_rebuild_hflags(env);
4816     }
4817 }
4818 
4819 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4820                                      bool isread)
4821 {
4822     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4823         return CP_ACCESS_TRAP_FP_EL2;
4824     }
4825     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4826         return CP_ACCESS_TRAP_FP_EL3;
4827     }
4828     return CP_ACCESS_OK;
4829 }
4830 
4831 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4832                        uint64_t value)
4833 {
4834     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4835 }
4836 
4837 static const ARMCPRegInfo v8_cp_reginfo[] = {
4838     /* Minimal set of EL0-visible registers. This will need to be expanded
4839      * significantly for system emulation of AArch64 CPUs.
4840      */
4841     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4842       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4843       .access = PL0_RW, .type = ARM_CP_NZCV },
4844     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4845       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4846       .type = ARM_CP_NO_RAW,
4847       .access = PL0_RW, .accessfn = aa64_daif_access,
4848       .fieldoffset = offsetof(CPUARMState, daif),
4849       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4850     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4851       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4852       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4853       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4854     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4855       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4856       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4857       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4858     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4859       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4860       .access = PL0_R, .type = ARM_CP_NO_RAW,
4861       .readfn = aa64_dczid_read },
4862     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4863       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4864       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4865 #ifndef CONFIG_USER_ONLY
4866       /* Avoid overhead of an access check that always passes in user-mode */
4867       .accessfn = aa64_zva_access,
4868 #endif
4869     },
4870     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4871       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4872       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4873     /* Cache ops: all NOPs since we don't emulate caches */
4874     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4875       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4876       .access = PL1_W, .type = ARM_CP_NOP,
4877       .accessfn = aa64_cacheop_pou_access },
4878     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4879       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4880       .access = PL1_W, .type = ARM_CP_NOP,
4881       .accessfn = aa64_cacheop_pou_access },
4882     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4883       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4884       .access = PL0_W, .type = ARM_CP_NOP,
4885       .accessfn = aa64_cacheop_pou_access },
4886     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4887       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4888       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4889       .type = ARM_CP_NOP },
4890     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4891       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4892       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4893     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4894       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4895       .access = PL0_W, .type = ARM_CP_NOP,
4896       .accessfn = aa64_cacheop_poc_access },
4897     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4898       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4899       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4900     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4901       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4902       .access = PL0_W, .type = ARM_CP_NOP,
4903       .accessfn = aa64_cacheop_pou_access },
4904     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4905       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4906       .access = PL0_W, .type = ARM_CP_NOP,
4907       .accessfn = aa64_cacheop_poc_access },
4908     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4909       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4910       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4911     /* TLBI operations */
4912     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4913       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4914       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4915       .writefn = tlbi_aa64_vmalle1is_write },
4916     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4917       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4918       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4919       .writefn = tlbi_aa64_vae1is_write },
4920     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4921       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4922       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4923       .writefn = tlbi_aa64_vmalle1is_write },
4924     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4925       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4926       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4927       .writefn = tlbi_aa64_vae1is_write },
4928     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4929       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4930       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4931       .writefn = tlbi_aa64_vae1is_write },
4932     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4933       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4934       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4935       .writefn = tlbi_aa64_vae1is_write },
4936     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4937       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4938       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4939       .writefn = tlbi_aa64_vmalle1_write },
4940     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4941       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4942       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4943       .writefn = tlbi_aa64_vae1_write },
4944     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4945       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4946       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4947       .writefn = tlbi_aa64_vmalle1_write },
4948     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4949       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
4950       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4951       .writefn = tlbi_aa64_vae1_write },
4952     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
4953       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
4954       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4955       .writefn = tlbi_aa64_vae1_write },
4956     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
4957       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
4958       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4959       .writefn = tlbi_aa64_vae1_write },
4960     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
4961       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
4962       .access = PL2_W, .type = ARM_CP_NOP },
4963     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
4964       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
4965       .access = PL2_W, .type = ARM_CP_NOP },
4966     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
4967       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
4968       .access = PL2_W, .type = ARM_CP_NO_RAW,
4969       .writefn = tlbi_aa64_alle1is_write },
4970     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
4971       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
4972       .access = PL2_W, .type = ARM_CP_NO_RAW,
4973       .writefn = tlbi_aa64_alle1is_write },
4974     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
4975       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
4976       .access = PL2_W, .type = ARM_CP_NOP },
4977     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
4978       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
4979       .access = PL2_W, .type = ARM_CP_NOP },
4980     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
4981       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
4982       .access = PL2_W, .type = ARM_CP_NO_RAW,
4983       .writefn = tlbi_aa64_alle1_write },
4984     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
4985       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
4986       .access = PL2_W, .type = ARM_CP_NO_RAW,
4987       .writefn = tlbi_aa64_alle1is_write },
4988 #ifndef CONFIG_USER_ONLY
4989     /* 64 bit address translation operations */
4990     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
4991       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
4992       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4993       .writefn = ats_write64 },
4994     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
4995       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
4996       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
4997       .writefn = ats_write64 },
4998     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
4999       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
5000       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5001       .writefn = ats_write64 },
5002     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
5003       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
5004       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5005       .writefn = ats_write64 },
5006     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
5007       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
5008       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5009       .writefn = ats_write64 },
5010     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
5011       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
5012       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5013       .writefn = ats_write64 },
5014     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
5015       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
5016       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5017       .writefn = ats_write64 },
5018     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
5019       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
5020       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5021       .writefn = ats_write64 },
5022     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
5023     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
5024       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
5025       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5026       .writefn = ats_write64 },
5027     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
5028       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
5029       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5030       .writefn = ats_write64 },
5031     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
5032       .type = ARM_CP_ALIAS,
5033       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
5034       .access = PL1_RW, .resetvalue = 0,
5035       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
5036       .writefn = par_write },
5037 #endif
5038     /* TLB invalidate last level of translation table walk */
5039     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
5040       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5041       .writefn = tlbimva_is_write },
5042     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
5043       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5044       .writefn = tlbimvaa_is_write },
5045     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
5046       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5047       .writefn = tlbimva_write },
5048     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
5049       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5050       .writefn = tlbimvaa_write },
5051     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5052       .type = ARM_CP_NO_RAW, .access = PL2_W,
5053       .writefn = tlbimva_hyp_write },
5054     { .name = "TLBIMVALHIS",
5055       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5056       .type = ARM_CP_NO_RAW, .access = PL2_W,
5057       .writefn = tlbimva_hyp_is_write },
5058     { .name = "TLBIIPAS2",
5059       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5060       .type = ARM_CP_NOP, .access = PL2_W },
5061     { .name = "TLBIIPAS2IS",
5062       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5063       .type = ARM_CP_NOP, .access = PL2_W },
5064     { .name = "TLBIIPAS2L",
5065       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5066       .type = ARM_CP_NOP, .access = PL2_W },
5067     { .name = "TLBIIPAS2LIS",
5068       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5069       .type = ARM_CP_NOP, .access = PL2_W },
5070     /* 32 bit cache operations */
5071     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5072       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5073     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5074       .type = ARM_CP_NOP, .access = PL1_W },
5075     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5076       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5077     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5078       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5079     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5080       .type = ARM_CP_NOP, .access = PL1_W },
5081     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5082       .type = ARM_CP_NOP, .access = PL1_W },
5083     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5084       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5085     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5086       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5087     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5088       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5089     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5090       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5091     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5092       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5093     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5094       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5095     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5096       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5097     /* MMU Domain access control / MPU write buffer control */
5098     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5099       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5100       .writefn = dacr_write, .raw_writefn = raw_write,
5101       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5102                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5103     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5104       .type = ARM_CP_ALIAS,
5105       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5106       .access = PL1_RW,
5107       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5108     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5109       .type = ARM_CP_ALIAS,
5110       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5111       .access = PL1_RW,
5112       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5113     /* We rely on the access checks not allowing the guest to write to the
5114      * state field when SPSel indicates that it's being used as the stack
5115      * pointer.
5116      */
5117     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5118       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5119       .access = PL1_RW, .accessfn = sp_el0_access,
5120       .type = ARM_CP_ALIAS,
5121       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5122     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5123       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5124       .access = PL2_RW, .type = ARM_CP_ALIAS,
5125       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5126     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5127       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5128       .type = ARM_CP_NO_RAW,
5129       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5130     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5131       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5132       .type = ARM_CP_ALIAS,
5133       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
5134       .access = PL2_RW, .accessfn = fpexc32_access },
5135     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5136       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5137       .access = PL2_RW, .resetvalue = 0,
5138       .writefn = dacr_write, .raw_writefn = raw_write,
5139       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5140     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5141       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5142       .access = PL2_RW, .resetvalue = 0,
5143       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5144     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5145       .type = ARM_CP_ALIAS,
5146       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5147       .access = PL2_RW,
5148       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5149     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5150       .type = ARM_CP_ALIAS,
5151       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5152       .access = PL2_RW,
5153       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5154     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5155       .type = ARM_CP_ALIAS,
5156       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5157       .access = PL2_RW,
5158       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5159     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5160       .type = ARM_CP_ALIAS,
5161       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5162       .access = PL2_RW,
5163       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5164     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5165       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5166       .resetvalue = 0,
5167       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5168     { .name = "SDCR", .type = ARM_CP_ALIAS,
5169       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5170       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5171       .writefn = sdcr_write,
5172       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5173     REGINFO_SENTINEL
5174 };
5175 
5176 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
5177 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
5178     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5179       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5180       .access = PL2_RW,
5181       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
5182     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
5183       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5184       .access = PL2_RW,
5185       .type = ARM_CP_CONST, .resetvalue = 0 },
5186     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5187       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5188       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5189     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5190       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5191       .access = PL2_RW,
5192       .type = ARM_CP_CONST, .resetvalue = 0 },
5193     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5194       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5195       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5196     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5197       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5198       .access = PL2_RW, .type = ARM_CP_CONST,
5199       .resetvalue = 0 },
5200     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5201       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5202       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5203     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5204       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5205       .access = PL2_RW, .type = ARM_CP_CONST,
5206       .resetvalue = 0 },
5207     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5208       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5209       .access = PL2_RW, .type = ARM_CP_CONST,
5210       .resetvalue = 0 },
5211     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5212       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5213       .access = PL2_RW, .type = ARM_CP_CONST,
5214       .resetvalue = 0 },
5215     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5216       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5217       .access = PL2_RW, .type = ARM_CP_CONST,
5218       .resetvalue = 0 },
5219     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5220       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5221       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5222     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
5223       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5224       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5225       .type = ARM_CP_CONST, .resetvalue = 0 },
5226     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5227       .cp = 15, .opc1 = 6, .crm = 2,
5228       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5229       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
5230     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5231       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5232       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5233     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5234       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5235       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5236     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5237       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5238       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5239     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5240       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5241       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5242     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5243       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5244       .resetvalue = 0 },
5245     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5246       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5247       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5248     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5249       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5250       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5251     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5252       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5253       .resetvalue = 0 },
5254     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5255       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5256       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5257     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5258       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5259       .resetvalue = 0 },
5260     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5261       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5262       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5263     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5264       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5265       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5266     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5267       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5268       .access = PL2_RW, .accessfn = access_tda,
5269       .type = ARM_CP_CONST, .resetvalue = 0 },
5270     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
5271       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5272       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5273       .type = ARM_CP_CONST, .resetvalue = 0 },
5274     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5275       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5276       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5277     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5278       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5279       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5280     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5281       .type = ARM_CP_CONST,
5282       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5283       .access = PL2_RW, .resetvalue = 0 },
5284     REGINFO_SENTINEL
5285 };
5286 
5287 /* Ditto, but for registers which exist in ARMv8 but not v7 */
5288 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
5289     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5290       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5291       .access = PL2_RW,
5292       .type = ARM_CP_CONST, .resetvalue = 0 },
5293     REGINFO_SENTINEL
5294 };
5295 
5296 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5297 {
5298     ARMCPU *cpu = env_archcpu(env);
5299 
5300     if (arm_feature(env, ARM_FEATURE_V8)) {
5301         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5302     } else {
5303         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5304     }
5305 
5306     if (arm_feature(env, ARM_FEATURE_EL3)) {
5307         valid_mask &= ~HCR_HCD;
5308     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5309         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5310          * However, if we're using the SMC PSCI conduit then QEMU is
5311          * effectively acting like EL3 firmware and so the guest at
5312          * EL2 should retain the ability to prevent EL1 from being
5313          * able to make SMC calls into the ersatz firmware, so in
5314          * that case HCR.TSC should be read/write.
5315          */
5316         valid_mask &= ~HCR_TSC;
5317     }
5318 
5319     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5320         if (cpu_isar_feature(aa64_vh, cpu)) {
5321             valid_mask |= HCR_E2H;
5322         }
5323         if (cpu_isar_feature(aa64_lor, cpu)) {
5324             valid_mask |= HCR_TLOR;
5325         }
5326         if (cpu_isar_feature(aa64_pauth, cpu)) {
5327             valid_mask |= HCR_API | HCR_APK;
5328         }
5329         if (cpu_isar_feature(aa64_mte, cpu)) {
5330             valid_mask |= HCR_ATA | HCR_DCT | HCR_TID5;
5331         }
5332     }
5333 
5334     /* Clear RES0 bits.  */
5335     value &= valid_mask;
5336 
5337     /*
5338      * These bits change the MMU setup:
5339      * HCR_VM enables stage 2 translation
5340      * HCR_PTW forbids certain page-table setups
5341      * HCR_DC disables stage1 and enables stage2 translation
5342      * HCR_DCT enables tagging on (disabled) stage1 translation
5343      */
5344     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC | HCR_DCT)) {
5345         tlb_flush(CPU(cpu));
5346     }
5347     env->cp15.hcr_el2 = value;
5348 
5349     /*
5350      * Updates to VI and VF require us to update the status of
5351      * virtual interrupts, which are the logical OR of these bits
5352      * and the state of the input lines from the GIC. (This requires
5353      * that we have the iothread lock, which is done by marking the
5354      * reginfo structs as ARM_CP_IO.)
5355      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5356      * possible for it to be taken immediately, because VIRQ and
5357      * VFIQ are masked unless running at EL0 or EL1, and HCR
5358      * can only be written at EL2.
5359      */
5360     g_assert(qemu_mutex_iothread_locked());
5361     arm_cpu_update_virq(cpu);
5362     arm_cpu_update_vfiq(cpu);
5363 }
5364 
5365 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5366 {
5367     do_hcr_write(env, value, 0);
5368 }
5369 
5370 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5371                           uint64_t value)
5372 {
5373     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5374     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5375     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5376 }
5377 
5378 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5379                          uint64_t value)
5380 {
5381     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5382     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5383     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5384 }
5385 
5386 /*
5387  * Return the effective value of HCR_EL2.
5388  * Bits that are not included here:
5389  * RW       (read from SCR_EL3.RW as needed)
5390  */
5391 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5392 {
5393     uint64_t ret = env->cp15.hcr_el2;
5394 
5395     if (!arm_is_el2_enabled(env)) {
5396         /*
5397          * "This register has no effect if EL2 is not enabled in the
5398          * current Security state".  This is ARMv8.4-SecEL2 speak for
5399          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5400          *
5401          * Prior to that, the language was "In an implementation that
5402          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5403          * as if this field is 0 for all purposes other than a direct
5404          * read or write access of HCR_EL2".  With lots of enumeration
5405          * on a per-field basis.  In current QEMU, this is condition
5406          * is arm_is_secure_below_el3.
5407          *
5408          * Since the v8.4 language applies to the entire register, and
5409          * appears to be backward compatible, use that.
5410          */
5411         return 0;
5412     }
5413 
5414     /*
5415      * For a cpu that supports both aarch64 and aarch32, we can set bits
5416      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5417      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5418      */
5419     if (!arm_el_is_aa64(env, 2)) {
5420         uint64_t aa32_valid;
5421 
5422         /*
5423          * These bits are up-to-date as of ARMv8.6.
5424          * For HCR, it's easiest to list just the 2 bits that are invalid.
5425          * For HCR2, list those that are valid.
5426          */
5427         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5428         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5429                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5430         ret &= aa32_valid;
5431     }
5432 
5433     if (ret & HCR_TGE) {
5434         /* These bits are up-to-date as of ARMv8.6.  */
5435         if (ret & HCR_E2H) {
5436             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5437                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5438                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5439                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5440                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5441                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5442         } else {
5443             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5444         }
5445         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5446                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5447                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5448                  HCR_TLOR);
5449     }
5450 
5451     return ret;
5452 }
5453 
5454 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5455                            uint64_t value)
5456 {
5457     /*
5458      * For A-profile AArch32 EL3, if NSACR.CP10
5459      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5460      */
5461     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5462         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5463         value &= ~(0x3 << 10);
5464         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5465     }
5466     env->cp15.cptr_el[2] = value;
5467 }
5468 
5469 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5470 {
5471     /*
5472      * For A-profile AArch32 EL3, if NSACR.CP10
5473      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5474      */
5475     uint64_t value = env->cp15.cptr_el[2];
5476 
5477     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5478         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5479         value |= 0x3 << 10;
5480     }
5481     return value;
5482 }
5483 
5484 static const ARMCPRegInfo el2_cp_reginfo[] = {
5485     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5486       .type = ARM_CP_IO,
5487       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5488       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5489       .writefn = hcr_write },
5490     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5491       .type = ARM_CP_ALIAS | ARM_CP_IO,
5492       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5493       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5494       .writefn = hcr_writelow },
5495     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5496       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5497       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5498     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5499       .type = ARM_CP_ALIAS,
5500       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5501       .access = PL2_RW,
5502       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5503     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5504       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5505       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5506     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5507       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5508       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5509     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5510       .type = ARM_CP_ALIAS,
5511       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5512       .access = PL2_RW,
5513       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5514     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5515       .type = ARM_CP_ALIAS,
5516       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5517       .access = PL2_RW,
5518       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5519     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5520       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5521       .access = PL2_RW, .writefn = vbar_write,
5522       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5523       .resetvalue = 0 },
5524     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5525       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5526       .access = PL3_RW, .type = ARM_CP_ALIAS,
5527       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5528     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5529       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5530       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5531       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5532       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5533     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5534       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5535       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5536       .resetvalue = 0 },
5537     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5538       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5539       .access = PL2_RW, .type = ARM_CP_ALIAS,
5540       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5541     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5542       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5543       .access = PL2_RW, .type = ARM_CP_CONST,
5544       .resetvalue = 0 },
5545     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5546     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5547       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5548       .access = PL2_RW, .type = ARM_CP_CONST,
5549       .resetvalue = 0 },
5550     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5551       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5552       .access = PL2_RW, .type = ARM_CP_CONST,
5553       .resetvalue = 0 },
5554     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5555       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5556       .access = PL2_RW, .type = ARM_CP_CONST,
5557       .resetvalue = 0 },
5558     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5559       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5560       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5561       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5562       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5563     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5564       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5565       .type = ARM_CP_ALIAS,
5566       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5567       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5568     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5569       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5570       .access = PL2_RW,
5571       /* no .writefn needed as this can't cause an ASID change;
5572        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5573        */
5574       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5575     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5576       .cp = 15, .opc1 = 6, .crm = 2,
5577       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5578       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5579       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5580       .writefn = vttbr_write },
5581     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5582       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5583       .access = PL2_RW, .writefn = vttbr_write,
5584       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5585     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5586       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5587       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5588       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5589     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5590       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5591       .access = PL2_RW, .resetvalue = 0,
5592       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5593     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5594       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5595       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5596       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5597     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5598       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5599       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5600     { .name = "TLBIALLNSNH",
5601       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5602       .type = ARM_CP_NO_RAW, .access = PL2_W,
5603       .writefn = tlbiall_nsnh_write },
5604     { .name = "TLBIALLNSNHIS",
5605       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5606       .type = ARM_CP_NO_RAW, .access = PL2_W,
5607       .writefn = tlbiall_nsnh_is_write },
5608     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5609       .type = ARM_CP_NO_RAW, .access = PL2_W,
5610       .writefn = tlbiall_hyp_write },
5611     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5612       .type = ARM_CP_NO_RAW, .access = PL2_W,
5613       .writefn = tlbiall_hyp_is_write },
5614     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5615       .type = ARM_CP_NO_RAW, .access = PL2_W,
5616       .writefn = tlbimva_hyp_write },
5617     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5618       .type = ARM_CP_NO_RAW, .access = PL2_W,
5619       .writefn = tlbimva_hyp_is_write },
5620     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5621       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5622       .type = ARM_CP_NO_RAW, .access = PL2_W,
5623       .writefn = tlbi_aa64_alle2_write },
5624     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5625       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5626       .type = ARM_CP_NO_RAW, .access = PL2_W,
5627       .writefn = tlbi_aa64_vae2_write },
5628     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5629       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5630       .access = PL2_W, .type = ARM_CP_NO_RAW,
5631       .writefn = tlbi_aa64_vae2_write },
5632     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5633       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5634       .access = PL2_W, .type = ARM_CP_NO_RAW,
5635       .writefn = tlbi_aa64_alle2is_write },
5636     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5637       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5638       .type = ARM_CP_NO_RAW, .access = PL2_W,
5639       .writefn = tlbi_aa64_vae2is_write },
5640     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5641       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5642       .access = PL2_W, .type = ARM_CP_NO_RAW,
5643       .writefn = tlbi_aa64_vae2is_write },
5644 #ifndef CONFIG_USER_ONLY
5645     /* Unlike the other EL2-related AT operations, these must
5646      * UNDEF from EL3 if EL2 is not implemented, which is why we
5647      * define them here rather than with the rest of the AT ops.
5648      */
5649     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5650       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5651       .access = PL2_W, .accessfn = at_s1e2_access,
5652       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5653     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5654       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5655       .access = PL2_W, .accessfn = at_s1e2_access,
5656       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5657     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5658      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5659      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5660      * to behave as if SCR.NS was 1.
5661      */
5662     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5663       .access = PL2_W,
5664       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5665     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5666       .access = PL2_W,
5667       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5668     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5669       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5670       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5671        * reset values as IMPDEF. We choose to reset to 3 to comply with
5672        * both ARMv7 and ARMv8.
5673        */
5674       .access = PL2_RW, .resetvalue = 3,
5675       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5676     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5677       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5678       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5679       .writefn = gt_cntvoff_write,
5680       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5681     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5682       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5683       .writefn = gt_cntvoff_write,
5684       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5685     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5686       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5687       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5688       .type = ARM_CP_IO, .access = PL2_RW,
5689       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5690     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5691       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5692       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5693       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5694     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5695       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5696       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5697       .resetfn = gt_hyp_timer_reset,
5698       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5699     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5700       .type = ARM_CP_IO,
5701       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5702       .access = PL2_RW,
5703       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5704       .resetvalue = 0,
5705       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5706 #endif
5707     /* The only field of MDCR_EL2 that has a defined architectural reset value
5708      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N; but we
5709      * don't implement any PMU event counters, so using zero as a reset
5710      * value for MDCR_EL2 is okay
5711      */
5712     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5713       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5714       .access = PL2_RW, .resetvalue = 0,
5715       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5716     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5717       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5718       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5719       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5720     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5721       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5722       .access = PL2_RW,
5723       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5724     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5725       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5726       .access = PL2_RW,
5727       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5728     REGINFO_SENTINEL
5729 };
5730 
5731 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5732     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5733       .type = ARM_CP_ALIAS | ARM_CP_IO,
5734       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5735       .access = PL2_RW,
5736       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5737       .writefn = hcr_writehigh },
5738     REGINFO_SENTINEL
5739 };
5740 
5741 static CPAccessResult sel2_access(CPUARMState *env, const ARMCPRegInfo *ri,
5742                                   bool isread)
5743 {
5744     if (arm_current_el(env) == 3 || arm_is_secure_below_el3(env)) {
5745         return CP_ACCESS_OK;
5746     }
5747     return CP_ACCESS_TRAP_UNCATEGORIZED;
5748 }
5749 
5750 static const ARMCPRegInfo el2_sec_cp_reginfo[] = {
5751     { .name = "VSTTBR_EL2", .state = ARM_CP_STATE_AA64,
5752       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 0,
5753       .access = PL2_RW, .accessfn = sel2_access,
5754       .fieldoffset = offsetof(CPUARMState, cp15.vsttbr_el2) },
5755     { .name = "VSTCR_EL2", .state = ARM_CP_STATE_AA64,
5756       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 2,
5757       .access = PL2_RW, .accessfn = sel2_access,
5758       .fieldoffset = offsetof(CPUARMState, cp15.vstcr_el2) },
5759     REGINFO_SENTINEL
5760 };
5761 
5762 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5763                                    bool isread)
5764 {
5765     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5766      * At Secure EL1 it traps to EL3 or EL2.
5767      */
5768     if (arm_current_el(env) == 3) {
5769         return CP_ACCESS_OK;
5770     }
5771     if (arm_is_secure_below_el3(env)) {
5772         if (env->cp15.scr_el3 & SCR_EEL2) {
5773             return CP_ACCESS_TRAP_EL2;
5774         }
5775         return CP_ACCESS_TRAP_EL3;
5776     }
5777     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5778     if (isread) {
5779         return CP_ACCESS_OK;
5780     }
5781     return CP_ACCESS_TRAP_UNCATEGORIZED;
5782 }
5783 
5784 static const ARMCPRegInfo el3_cp_reginfo[] = {
5785     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5786       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5787       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5788       .resetvalue = 0, .writefn = scr_write },
5789     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5790       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5791       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5792       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5793       .writefn = scr_write },
5794     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5795       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5796       .access = PL3_RW, .resetvalue = 0,
5797       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5798     { .name = "SDER",
5799       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5800       .access = PL3_RW, .resetvalue = 0,
5801       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5802     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5803       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5804       .writefn = vbar_write, .resetvalue = 0,
5805       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5806     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5807       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5808       .access = PL3_RW, .resetvalue = 0,
5809       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5810     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5811       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5812       .access = PL3_RW,
5813       /* no .writefn needed as this can't cause an ASID change;
5814        * we must provide a .raw_writefn and .resetfn because we handle
5815        * reset and migration for the AArch32 TTBCR(S), which might be
5816        * using mask and base_mask.
5817        */
5818       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5819       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5820     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5821       .type = ARM_CP_ALIAS,
5822       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5823       .access = PL3_RW,
5824       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5825     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5826       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5827       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5828     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5829       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5830       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5831     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5832       .type = ARM_CP_ALIAS,
5833       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5834       .access = PL3_RW,
5835       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5836     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5837       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5838       .access = PL3_RW, .writefn = vbar_write,
5839       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5840       .resetvalue = 0 },
5841     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5842       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5843       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5844       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5845     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5846       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5847       .access = PL3_RW, .resetvalue = 0,
5848       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5849     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5850       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5851       .access = PL3_RW, .type = ARM_CP_CONST,
5852       .resetvalue = 0 },
5853     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5854       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5855       .access = PL3_RW, .type = ARM_CP_CONST,
5856       .resetvalue = 0 },
5857     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5858       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5859       .access = PL3_RW, .type = ARM_CP_CONST,
5860       .resetvalue = 0 },
5861     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5862       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5863       .access = PL3_W, .type = ARM_CP_NO_RAW,
5864       .writefn = tlbi_aa64_alle3is_write },
5865     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5866       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5867       .access = PL3_W, .type = ARM_CP_NO_RAW,
5868       .writefn = tlbi_aa64_vae3is_write },
5869     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5870       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5871       .access = PL3_W, .type = ARM_CP_NO_RAW,
5872       .writefn = tlbi_aa64_vae3is_write },
5873     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5874       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5875       .access = PL3_W, .type = ARM_CP_NO_RAW,
5876       .writefn = tlbi_aa64_alle3_write },
5877     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5878       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5879       .access = PL3_W, .type = ARM_CP_NO_RAW,
5880       .writefn = tlbi_aa64_vae3_write },
5881     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5882       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5883       .access = PL3_W, .type = ARM_CP_NO_RAW,
5884       .writefn = tlbi_aa64_vae3_write },
5885     REGINFO_SENTINEL
5886 };
5887 
5888 #ifndef CONFIG_USER_ONLY
5889 /* Test if system register redirection is to occur in the current state.  */
5890 static bool redirect_for_e2h(CPUARMState *env)
5891 {
5892     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5893 }
5894 
5895 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5896 {
5897     CPReadFn *readfn;
5898 
5899     if (redirect_for_e2h(env)) {
5900         /* Switch to the saved EL2 version of the register.  */
5901         ri = ri->opaque;
5902         readfn = ri->readfn;
5903     } else {
5904         readfn = ri->orig_readfn;
5905     }
5906     if (readfn == NULL) {
5907         readfn = raw_read;
5908     }
5909     return readfn(env, ri);
5910 }
5911 
5912 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5913                           uint64_t value)
5914 {
5915     CPWriteFn *writefn;
5916 
5917     if (redirect_for_e2h(env)) {
5918         /* Switch to the saved EL2 version of the register.  */
5919         ri = ri->opaque;
5920         writefn = ri->writefn;
5921     } else {
5922         writefn = ri->orig_writefn;
5923     }
5924     if (writefn == NULL) {
5925         writefn = raw_write;
5926     }
5927     writefn(env, ri, value);
5928 }
5929 
5930 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5931 {
5932     struct E2HAlias {
5933         uint32_t src_key, dst_key, new_key;
5934         const char *src_name, *dst_name, *new_name;
5935         bool (*feature)(const ARMISARegisters *id);
5936     };
5937 
5938 #define K(op0, op1, crn, crm, op2) \
5939     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5940 
5941     static const struct E2HAlias aliases[] = {
5942         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5943           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5944         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5945           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5946         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5947           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5948         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5949           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5950         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5951           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5952         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5953           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5954         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5955           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5956         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5957           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5958         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
5959           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
5960         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
5961           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
5962         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
5963           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
5964         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
5965           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
5966         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
5967           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
5968         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
5969           "VBAR", "VBAR_EL2", "VBAR_EL12" },
5970         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
5971           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
5972         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
5973           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
5974 
5975         /*
5976          * Note that redirection of ZCR is mentioned in the description
5977          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
5978          * not in the summary table.
5979          */
5980         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
5981           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
5982 
5983         { K(3, 0,  5, 6, 0), K(3, 4,  5, 6, 0), K(3, 5, 5, 6, 0),
5984           "TFSR_EL1", "TFSR_EL2", "TFSR_EL12", isar_feature_aa64_mte },
5985 
5986         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
5987         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
5988     };
5989 #undef K
5990 
5991     size_t i;
5992 
5993     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
5994         const struct E2HAlias *a = &aliases[i];
5995         ARMCPRegInfo *src_reg, *dst_reg;
5996 
5997         if (a->feature && !a->feature(&cpu->isar)) {
5998             continue;
5999         }
6000 
6001         src_reg = g_hash_table_lookup(cpu->cp_regs, &a->src_key);
6002         dst_reg = g_hash_table_lookup(cpu->cp_regs, &a->dst_key);
6003         g_assert(src_reg != NULL);
6004         g_assert(dst_reg != NULL);
6005 
6006         /* Cross-compare names to detect typos in the keys.  */
6007         g_assert(strcmp(src_reg->name, a->src_name) == 0);
6008         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
6009 
6010         /* None of the core system registers use opaque; we will.  */
6011         g_assert(src_reg->opaque == NULL);
6012 
6013         /* Create alias before redirection so we dup the right data. */
6014         if (a->new_key) {
6015             ARMCPRegInfo *new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
6016             uint32_t *new_key = g_memdup(&a->new_key, sizeof(uint32_t));
6017             bool ok;
6018 
6019             new_reg->name = a->new_name;
6020             new_reg->type |= ARM_CP_ALIAS;
6021             /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
6022             new_reg->access &= PL2_RW | PL3_RW;
6023 
6024             ok = g_hash_table_insert(cpu->cp_regs, new_key, new_reg);
6025             g_assert(ok);
6026         }
6027 
6028         src_reg->opaque = dst_reg;
6029         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
6030         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
6031         if (!src_reg->raw_readfn) {
6032             src_reg->raw_readfn = raw_read;
6033         }
6034         if (!src_reg->raw_writefn) {
6035             src_reg->raw_writefn = raw_write;
6036         }
6037         src_reg->readfn = el2_e2h_read;
6038         src_reg->writefn = el2_e2h_write;
6039     }
6040 }
6041 #endif
6042 
6043 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
6044                                      bool isread)
6045 {
6046     int cur_el = arm_current_el(env);
6047 
6048     if (cur_el < 2) {
6049         uint64_t hcr = arm_hcr_el2_eff(env);
6050 
6051         if (cur_el == 0) {
6052             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
6053                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
6054                     return CP_ACCESS_TRAP_EL2;
6055                 }
6056             } else {
6057                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
6058                     return CP_ACCESS_TRAP;
6059                 }
6060                 if (hcr & HCR_TID2) {
6061                     return CP_ACCESS_TRAP_EL2;
6062                 }
6063             }
6064         } else if (hcr & HCR_TID2) {
6065             return CP_ACCESS_TRAP_EL2;
6066         }
6067     }
6068 
6069     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
6070         return CP_ACCESS_TRAP_EL2;
6071     }
6072 
6073     return CP_ACCESS_OK;
6074 }
6075 
6076 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
6077                         uint64_t value)
6078 {
6079     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
6080      * read via a bit in OSLSR_EL1.
6081      */
6082     int oslock;
6083 
6084     if (ri->state == ARM_CP_STATE_AA32) {
6085         oslock = (value == 0xC5ACCE55);
6086     } else {
6087         oslock = value & 1;
6088     }
6089 
6090     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
6091 }
6092 
6093 static const ARMCPRegInfo debug_cp_reginfo[] = {
6094     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
6095      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
6096      * unlike DBGDRAR it is never accessible from EL0.
6097      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
6098      * accessor.
6099      */
6100     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
6101       .access = PL0_R, .accessfn = access_tdra,
6102       .type = ARM_CP_CONST, .resetvalue = 0 },
6103     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
6104       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6105       .access = PL1_R, .accessfn = access_tdra,
6106       .type = ARM_CP_CONST, .resetvalue = 0 },
6107     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
6108       .access = PL0_R, .accessfn = access_tdra,
6109       .type = ARM_CP_CONST, .resetvalue = 0 },
6110     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
6111     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
6112       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
6113       .access = PL1_RW, .accessfn = access_tda,
6114       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
6115       .resetvalue = 0 },
6116     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
6117      * We don't implement the configurable EL0 access.
6118      */
6119     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
6120       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6121       .type = ARM_CP_ALIAS,
6122       .access = PL1_R, .accessfn = access_tda,
6123       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
6124     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
6125       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
6126       .access = PL1_W, .type = ARM_CP_NO_RAW,
6127       .accessfn = access_tdosa,
6128       .writefn = oslar_write },
6129     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
6130       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
6131       .access = PL1_R, .resetvalue = 10,
6132       .accessfn = access_tdosa,
6133       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
6134     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
6135     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
6136       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
6137       .access = PL1_RW, .accessfn = access_tdosa,
6138       .type = ARM_CP_NOP },
6139     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
6140      * implement vector catch debug events yet.
6141      */
6142     { .name = "DBGVCR",
6143       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6144       .access = PL1_RW, .accessfn = access_tda,
6145       .type = ARM_CP_NOP },
6146     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
6147      * to save and restore a 32-bit guest's DBGVCR)
6148      */
6149     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
6150       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
6151       .access = PL2_RW, .accessfn = access_tda,
6152       .type = ARM_CP_NOP },
6153     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6154      * Channel but Linux may try to access this register. The 32-bit
6155      * alias is DBGDCCINT.
6156      */
6157     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6158       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6159       .access = PL1_RW, .accessfn = access_tda,
6160       .type = ARM_CP_NOP },
6161     REGINFO_SENTINEL
6162 };
6163 
6164 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6165     /* 64 bit access versions of the (dummy) debug registers */
6166     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6167       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6168     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6169       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6170     REGINFO_SENTINEL
6171 };
6172 
6173 /* Return the exception level to which exceptions should be taken
6174  * via SVEAccessTrap.  If an exception should be routed through
6175  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6176  * take care of raising that exception.
6177  * C.f. the ARM pseudocode function CheckSVEEnabled.
6178  */
6179 int sve_exception_el(CPUARMState *env, int el)
6180 {
6181 #ifndef CONFIG_USER_ONLY
6182     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6183 
6184     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6185         bool disabled = false;
6186 
6187         /* The CPACR.ZEN controls traps to EL1:
6188          * 0, 2 : trap EL0 and EL1 accesses
6189          * 1    : trap only EL0 accesses
6190          * 3    : trap no accesses
6191          */
6192         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
6193             disabled = true;
6194         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
6195             disabled = el == 0;
6196         }
6197         if (disabled) {
6198             /* route_to_el2 */
6199             return hcr_el2 & HCR_TGE ? 2 : 1;
6200         }
6201 
6202         /* Check CPACR.FPEN.  */
6203         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
6204             disabled = true;
6205         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
6206             disabled = el == 0;
6207         }
6208         if (disabled) {
6209             return 0;
6210         }
6211     }
6212 
6213     /* CPTR_EL2.  Since TZ and TFP are positive,
6214      * they will be zero when EL2 is not present.
6215      */
6216     if (el <= 2 && arm_is_el2_enabled(env)) {
6217         if (env->cp15.cptr_el[2] & CPTR_TZ) {
6218             return 2;
6219         }
6220         if (env->cp15.cptr_el[2] & CPTR_TFP) {
6221             return 0;
6222         }
6223     }
6224 
6225     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6226     if (arm_feature(env, ARM_FEATURE_EL3)
6227         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6228         return 3;
6229     }
6230 #endif
6231     return 0;
6232 }
6233 
6234 static uint32_t sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6235 {
6236     uint32_t end_len;
6237 
6238     end_len = start_len &= 0xf;
6239     if (!test_bit(start_len, cpu->sve_vq_map)) {
6240         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6241         assert(end_len < start_len);
6242     }
6243     return end_len;
6244 }
6245 
6246 /*
6247  * Given that SVE is enabled, return the vector length for EL.
6248  */
6249 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6250 {
6251     ARMCPU *cpu = env_archcpu(env);
6252     uint32_t zcr_len = cpu->sve_max_vq - 1;
6253 
6254     if (el <= 1) {
6255         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6256     }
6257     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6258         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6259     }
6260     if (arm_feature(env, ARM_FEATURE_EL3)) {
6261         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6262     }
6263 
6264     return sve_zcr_get_valid_len(cpu, zcr_len);
6265 }
6266 
6267 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6268                       uint64_t value)
6269 {
6270     int cur_el = arm_current_el(env);
6271     int old_len = sve_zcr_len_for_el(env, cur_el);
6272     int new_len;
6273 
6274     /* Bits other than [3:0] are RAZ/WI.  */
6275     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6276     raw_write(env, ri, value & 0xf);
6277 
6278     /*
6279      * Because we arrived here, we know both FP and SVE are enabled;
6280      * otherwise we would have trapped access to the ZCR_ELn register.
6281      */
6282     new_len = sve_zcr_len_for_el(env, cur_el);
6283     if (new_len < old_len) {
6284         aarch64_sve_narrow_vq(env, new_len + 1);
6285     }
6286 }
6287 
6288 static const ARMCPRegInfo zcr_el1_reginfo = {
6289     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6290     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6291     .access = PL1_RW, .type = ARM_CP_SVE,
6292     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6293     .writefn = zcr_write, .raw_writefn = raw_write
6294 };
6295 
6296 static const ARMCPRegInfo zcr_el2_reginfo = {
6297     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6298     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6299     .access = PL2_RW, .type = ARM_CP_SVE,
6300     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6301     .writefn = zcr_write, .raw_writefn = raw_write
6302 };
6303 
6304 static const ARMCPRegInfo zcr_no_el2_reginfo = {
6305     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6306     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6307     .access = PL2_RW, .type = ARM_CP_SVE,
6308     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
6309 };
6310 
6311 static const ARMCPRegInfo zcr_el3_reginfo = {
6312     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6313     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6314     .access = PL3_RW, .type = ARM_CP_SVE,
6315     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6316     .writefn = zcr_write, .raw_writefn = raw_write
6317 };
6318 
6319 void hw_watchpoint_update(ARMCPU *cpu, int n)
6320 {
6321     CPUARMState *env = &cpu->env;
6322     vaddr len = 0;
6323     vaddr wvr = env->cp15.dbgwvr[n];
6324     uint64_t wcr = env->cp15.dbgwcr[n];
6325     int mask;
6326     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6327 
6328     if (env->cpu_watchpoint[n]) {
6329         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6330         env->cpu_watchpoint[n] = NULL;
6331     }
6332 
6333     if (!extract64(wcr, 0, 1)) {
6334         /* E bit clear : watchpoint disabled */
6335         return;
6336     }
6337 
6338     switch (extract64(wcr, 3, 2)) {
6339     case 0:
6340         /* LSC 00 is reserved and must behave as if the wp is disabled */
6341         return;
6342     case 1:
6343         flags |= BP_MEM_READ;
6344         break;
6345     case 2:
6346         flags |= BP_MEM_WRITE;
6347         break;
6348     case 3:
6349         flags |= BP_MEM_ACCESS;
6350         break;
6351     }
6352 
6353     /* Attempts to use both MASK and BAS fields simultaneously are
6354      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6355      * thus generating a watchpoint for every byte in the masked region.
6356      */
6357     mask = extract64(wcr, 24, 4);
6358     if (mask == 1 || mask == 2) {
6359         /* Reserved values of MASK; we must act as if the mask value was
6360          * some non-reserved value, or as if the watchpoint were disabled.
6361          * We choose the latter.
6362          */
6363         return;
6364     } else if (mask) {
6365         /* Watchpoint covers an aligned area up to 2GB in size */
6366         len = 1ULL << mask;
6367         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6368          * whether the watchpoint fires when the unmasked bits match; we opt
6369          * to generate the exceptions.
6370          */
6371         wvr &= ~(len - 1);
6372     } else {
6373         /* Watchpoint covers bytes defined by the byte address select bits */
6374         int bas = extract64(wcr, 5, 8);
6375         int basstart;
6376 
6377         if (extract64(wvr, 2, 1)) {
6378             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6379              * ignored, and BAS[3:0] define which bytes to watch.
6380              */
6381             bas &= 0xf;
6382         }
6383 
6384         if (bas == 0) {
6385             /* This must act as if the watchpoint is disabled */
6386             return;
6387         }
6388 
6389         /* The BAS bits are supposed to be programmed to indicate a contiguous
6390          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6391          * we fire for each byte in the word/doubleword addressed by the WVR.
6392          * We choose to ignore any non-zero bits after the first range of 1s.
6393          */
6394         basstart = ctz32(bas);
6395         len = cto32(bas >> basstart);
6396         wvr += basstart;
6397     }
6398 
6399     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6400                           &env->cpu_watchpoint[n]);
6401 }
6402 
6403 void hw_watchpoint_update_all(ARMCPU *cpu)
6404 {
6405     int i;
6406     CPUARMState *env = &cpu->env;
6407 
6408     /* Completely clear out existing QEMU watchpoints and our array, to
6409      * avoid possible stale entries following migration load.
6410      */
6411     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6412     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6413 
6414     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6415         hw_watchpoint_update(cpu, i);
6416     }
6417 }
6418 
6419 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6420                          uint64_t value)
6421 {
6422     ARMCPU *cpu = env_archcpu(env);
6423     int i = ri->crm;
6424 
6425     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
6426      * register reads and behaves as if values written are sign extended.
6427      * Bits [1:0] are RES0.
6428      */
6429     value = sextract64(value, 0, 49) & ~3ULL;
6430 
6431     raw_write(env, ri, value);
6432     hw_watchpoint_update(cpu, i);
6433 }
6434 
6435 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6436                          uint64_t value)
6437 {
6438     ARMCPU *cpu = env_archcpu(env);
6439     int i = ri->crm;
6440 
6441     raw_write(env, ri, value);
6442     hw_watchpoint_update(cpu, i);
6443 }
6444 
6445 void hw_breakpoint_update(ARMCPU *cpu, int n)
6446 {
6447     CPUARMState *env = &cpu->env;
6448     uint64_t bvr = env->cp15.dbgbvr[n];
6449     uint64_t bcr = env->cp15.dbgbcr[n];
6450     vaddr addr;
6451     int bt;
6452     int flags = BP_CPU;
6453 
6454     if (env->cpu_breakpoint[n]) {
6455         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6456         env->cpu_breakpoint[n] = NULL;
6457     }
6458 
6459     if (!extract64(bcr, 0, 1)) {
6460         /* E bit clear : watchpoint disabled */
6461         return;
6462     }
6463 
6464     bt = extract64(bcr, 20, 4);
6465 
6466     switch (bt) {
6467     case 4: /* unlinked address mismatch (reserved if AArch64) */
6468     case 5: /* linked address mismatch (reserved if AArch64) */
6469         qemu_log_mask(LOG_UNIMP,
6470                       "arm: address mismatch breakpoint types not implemented\n");
6471         return;
6472     case 0: /* unlinked address match */
6473     case 1: /* linked address match */
6474     {
6475         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
6476          * we behave as if the register was sign extended. Bits [1:0] are
6477          * RES0. The BAS field is used to allow setting breakpoints on 16
6478          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6479          * a bp will fire if the addresses covered by the bp and the addresses
6480          * covered by the insn overlap but the insn doesn't start at the
6481          * start of the bp address range. We choose to require the insn and
6482          * the bp to have the same address. The constraints on writing to
6483          * BAS enforced in dbgbcr_write mean we have only four cases:
6484          *  0b0000  => no breakpoint
6485          *  0b0011  => breakpoint on addr
6486          *  0b1100  => breakpoint on addr + 2
6487          *  0b1111  => breakpoint on addr
6488          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6489          */
6490         int bas = extract64(bcr, 5, 4);
6491         addr = sextract64(bvr, 0, 49) & ~3ULL;
6492         if (bas == 0) {
6493             return;
6494         }
6495         if (bas == 0xc) {
6496             addr += 2;
6497         }
6498         break;
6499     }
6500     case 2: /* unlinked context ID match */
6501     case 8: /* unlinked VMID match (reserved if no EL2) */
6502     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6503         qemu_log_mask(LOG_UNIMP,
6504                       "arm: unlinked context breakpoint types not implemented\n");
6505         return;
6506     case 9: /* linked VMID match (reserved if no EL2) */
6507     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6508     case 3: /* linked context ID match */
6509     default:
6510         /* We must generate no events for Linked context matches (unless
6511          * they are linked to by some other bp/wp, which is handled in
6512          * updates for the linking bp/wp). We choose to also generate no events
6513          * for reserved values.
6514          */
6515         return;
6516     }
6517 
6518     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6519 }
6520 
6521 void hw_breakpoint_update_all(ARMCPU *cpu)
6522 {
6523     int i;
6524     CPUARMState *env = &cpu->env;
6525 
6526     /* Completely clear out existing QEMU breakpoints and our array, to
6527      * avoid possible stale entries following migration load.
6528      */
6529     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6530     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6531 
6532     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6533         hw_breakpoint_update(cpu, i);
6534     }
6535 }
6536 
6537 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6538                          uint64_t value)
6539 {
6540     ARMCPU *cpu = env_archcpu(env);
6541     int i = ri->crm;
6542 
6543     raw_write(env, ri, value);
6544     hw_breakpoint_update(cpu, i);
6545 }
6546 
6547 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6548                          uint64_t value)
6549 {
6550     ARMCPU *cpu = env_archcpu(env);
6551     int i = ri->crm;
6552 
6553     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6554      * copy of BAS[0].
6555      */
6556     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6557     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6558 
6559     raw_write(env, ri, value);
6560     hw_breakpoint_update(cpu, i);
6561 }
6562 
6563 static void define_debug_regs(ARMCPU *cpu)
6564 {
6565     /* Define v7 and v8 architectural debug registers.
6566      * These are just dummy implementations for now.
6567      */
6568     int i;
6569     int wrps, brps, ctx_cmps;
6570     ARMCPRegInfo dbgdidr = {
6571         .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
6572         .access = PL0_R, .accessfn = access_tda,
6573         .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6574     };
6575 
6576     /* Note that all these register fields hold "number of Xs minus 1". */
6577     brps = arm_num_brps(cpu);
6578     wrps = arm_num_wrps(cpu);
6579     ctx_cmps = arm_num_ctx_cmps(cpu);
6580 
6581     assert(ctx_cmps <= brps);
6582 
6583     define_one_arm_cp_reg(cpu, &dbgdidr);
6584     define_arm_cp_regs(cpu, debug_cp_reginfo);
6585 
6586     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6587         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6588     }
6589 
6590     for (i = 0; i < brps; i++) {
6591         ARMCPRegInfo dbgregs[] = {
6592             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6593               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6594               .access = PL1_RW, .accessfn = access_tda,
6595               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6596               .writefn = dbgbvr_write, .raw_writefn = raw_write
6597             },
6598             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6599               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6600               .access = PL1_RW, .accessfn = access_tda,
6601               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6602               .writefn = dbgbcr_write, .raw_writefn = raw_write
6603             },
6604             REGINFO_SENTINEL
6605         };
6606         define_arm_cp_regs(cpu, dbgregs);
6607     }
6608 
6609     for (i = 0; i < wrps; i++) {
6610         ARMCPRegInfo dbgregs[] = {
6611             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6612               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6613               .access = PL1_RW, .accessfn = access_tda,
6614               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6615               .writefn = dbgwvr_write, .raw_writefn = raw_write
6616             },
6617             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6618               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6619               .access = PL1_RW, .accessfn = access_tda,
6620               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6621               .writefn = dbgwcr_write, .raw_writefn = raw_write
6622             },
6623             REGINFO_SENTINEL
6624         };
6625         define_arm_cp_regs(cpu, dbgregs);
6626     }
6627 }
6628 
6629 static void define_pmu_regs(ARMCPU *cpu)
6630 {
6631     /*
6632      * v7 performance monitor control register: same implementor
6633      * field as main ID register, and we implement four counters in
6634      * addition to the cycle count register.
6635      */
6636     unsigned int i, pmcrn = 4;
6637     ARMCPRegInfo pmcr = {
6638         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6639         .access = PL0_RW,
6640         .type = ARM_CP_IO | ARM_CP_ALIAS,
6641         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6642         .accessfn = pmreg_access, .writefn = pmcr_write,
6643         .raw_writefn = raw_write,
6644     };
6645     ARMCPRegInfo pmcr64 = {
6646         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6647         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6648         .access = PL0_RW, .accessfn = pmreg_access,
6649         .type = ARM_CP_IO,
6650         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6651         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6652                       PMCRLC,
6653         .writefn = pmcr_write, .raw_writefn = raw_write,
6654     };
6655     define_one_arm_cp_reg(cpu, &pmcr);
6656     define_one_arm_cp_reg(cpu, &pmcr64);
6657     for (i = 0; i < pmcrn; i++) {
6658         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6659         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6660         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6661         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6662         ARMCPRegInfo pmev_regs[] = {
6663             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6664               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6665               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6666               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6667               .accessfn = pmreg_access },
6668             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6669               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6670               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6671               .type = ARM_CP_IO,
6672               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6673               .raw_readfn = pmevcntr_rawread,
6674               .raw_writefn = pmevcntr_rawwrite },
6675             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6676               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6677               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6678               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6679               .accessfn = pmreg_access },
6680             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6681               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6682               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6683               .type = ARM_CP_IO,
6684               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6685               .raw_writefn = pmevtyper_rawwrite },
6686             REGINFO_SENTINEL
6687         };
6688         define_arm_cp_regs(cpu, pmev_regs);
6689         g_free(pmevcntr_name);
6690         g_free(pmevcntr_el0_name);
6691         g_free(pmevtyper_name);
6692         g_free(pmevtyper_el0_name);
6693     }
6694     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6695         ARMCPRegInfo v81_pmu_regs[] = {
6696             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6697               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6698               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6699               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6700             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6701               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6702               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6703               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6704             REGINFO_SENTINEL
6705         };
6706         define_arm_cp_regs(cpu, v81_pmu_regs);
6707     }
6708     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6709         static const ARMCPRegInfo v84_pmmir = {
6710             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6711             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6712             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6713             .resetvalue = 0
6714         };
6715         define_one_arm_cp_reg(cpu, &v84_pmmir);
6716     }
6717 }
6718 
6719 /* We don't know until after realize whether there's a GICv3
6720  * attached, and that is what registers the gicv3 sysregs.
6721  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6722  * at runtime.
6723  */
6724 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6725 {
6726     ARMCPU *cpu = env_archcpu(env);
6727     uint64_t pfr1 = cpu->isar.id_pfr1;
6728 
6729     if (env->gicv3state) {
6730         pfr1 |= 1 << 28;
6731     }
6732     return pfr1;
6733 }
6734 
6735 #ifndef CONFIG_USER_ONLY
6736 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6737 {
6738     ARMCPU *cpu = env_archcpu(env);
6739     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6740 
6741     if (env->gicv3state) {
6742         pfr0 |= 1 << 24;
6743     }
6744     return pfr0;
6745 }
6746 #endif
6747 
6748 /* Shared logic between LORID and the rest of the LOR* registers.
6749  * Secure state exclusion has already been dealt with.
6750  */
6751 static CPAccessResult access_lor_ns(CPUARMState *env,
6752                                     const ARMCPRegInfo *ri, bool isread)
6753 {
6754     int el = arm_current_el(env);
6755 
6756     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6757         return CP_ACCESS_TRAP_EL2;
6758     }
6759     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6760         return CP_ACCESS_TRAP_EL3;
6761     }
6762     return CP_ACCESS_OK;
6763 }
6764 
6765 static CPAccessResult access_lor_other(CPUARMState *env,
6766                                        const ARMCPRegInfo *ri, bool isread)
6767 {
6768     if (arm_is_secure_below_el3(env)) {
6769         /* Access denied in secure mode.  */
6770         return CP_ACCESS_TRAP;
6771     }
6772     return access_lor_ns(env, ri, isread);
6773 }
6774 
6775 /*
6776  * A trivial implementation of ARMv8.1-LOR leaves all of these
6777  * registers fixed at 0, which indicates that there are zero
6778  * supported Limited Ordering regions.
6779  */
6780 static const ARMCPRegInfo lor_reginfo[] = {
6781     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6782       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6783       .access = PL1_RW, .accessfn = access_lor_other,
6784       .type = ARM_CP_CONST, .resetvalue = 0 },
6785     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6786       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6787       .access = PL1_RW, .accessfn = access_lor_other,
6788       .type = ARM_CP_CONST, .resetvalue = 0 },
6789     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6790       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6791       .access = PL1_RW, .accessfn = access_lor_other,
6792       .type = ARM_CP_CONST, .resetvalue = 0 },
6793     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6794       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6795       .access = PL1_RW, .accessfn = access_lor_other,
6796       .type = ARM_CP_CONST, .resetvalue = 0 },
6797     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6798       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6799       .access = PL1_R, .accessfn = access_lor_ns,
6800       .type = ARM_CP_CONST, .resetvalue = 0 },
6801     REGINFO_SENTINEL
6802 };
6803 
6804 #ifdef TARGET_AARCH64
6805 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6806                                    bool isread)
6807 {
6808     int el = arm_current_el(env);
6809 
6810     if (el < 2 &&
6811         arm_feature(env, ARM_FEATURE_EL2) &&
6812         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6813         return CP_ACCESS_TRAP_EL2;
6814     }
6815     if (el < 3 &&
6816         arm_feature(env, ARM_FEATURE_EL3) &&
6817         !(env->cp15.scr_el3 & SCR_APK)) {
6818         return CP_ACCESS_TRAP_EL3;
6819     }
6820     return CP_ACCESS_OK;
6821 }
6822 
6823 static const ARMCPRegInfo pauth_reginfo[] = {
6824     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6825       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6826       .access = PL1_RW, .accessfn = access_pauth,
6827       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6828     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6829       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6830       .access = PL1_RW, .accessfn = access_pauth,
6831       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6832     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6833       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6834       .access = PL1_RW, .accessfn = access_pauth,
6835       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6836     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6837       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6838       .access = PL1_RW, .accessfn = access_pauth,
6839       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6840     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6841       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6842       .access = PL1_RW, .accessfn = access_pauth,
6843       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6844     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6845       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6846       .access = PL1_RW, .accessfn = access_pauth,
6847       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6848     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6849       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6850       .access = PL1_RW, .accessfn = access_pauth,
6851       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6852     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6853       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6854       .access = PL1_RW, .accessfn = access_pauth,
6855       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6856     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6857       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6858       .access = PL1_RW, .accessfn = access_pauth,
6859       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6860     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6861       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6862       .access = PL1_RW, .accessfn = access_pauth,
6863       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6864     REGINFO_SENTINEL
6865 };
6866 
6867 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
6868 {
6869     Error *err = NULL;
6870     uint64_t ret;
6871 
6872     /* Success sets NZCV = 0000.  */
6873     env->NF = env->CF = env->VF = 0, env->ZF = 1;
6874 
6875     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
6876         /*
6877          * ??? Failed, for unknown reasons in the crypto subsystem.
6878          * The best we can do is log the reason and return the
6879          * timed-out indication to the guest.  There is no reason
6880          * we know to expect this failure to be transitory, so the
6881          * guest may well hang retrying the operation.
6882          */
6883         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
6884                       ri->name, error_get_pretty(err));
6885         error_free(err);
6886 
6887         env->ZF = 0; /* NZCF = 0100 */
6888         return 0;
6889     }
6890     return ret;
6891 }
6892 
6893 /* We do not support re-seeding, so the two registers operate the same.  */
6894 static const ARMCPRegInfo rndr_reginfo[] = {
6895     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
6896       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6897       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
6898       .access = PL0_R, .readfn = rndr_readfn },
6899     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
6900       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6901       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
6902       .access = PL0_R, .readfn = rndr_readfn },
6903     REGINFO_SENTINEL
6904 };
6905 
6906 #ifndef CONFIG_USER_ONLY
6907 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
6908                           uint64_t value)
6909 {
6910     ARMCPU *cpu = env_archcpu(env);
6911     /* CTR_EL0 System register -> DminLine, bits [19:16] */
6912     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
6913     uint64_t vaddr_in = (uint64_t) value;
6914     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
6915     void *haddr;
6916     int mem_idx = cpu_mmu_index(env, false);
6917 
6918     /* This won't be crossing page boundaries */
6919     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
6920     if (haddr) {
6921 
6922         ram_addr_t offset;
6923         MemoryRegion *mr;
6924 
6925         /* RCU lock is already being held */
6926         mr = memory_region_from_host(haddr, &offset);
6927 
6928         if (mr) {
6929             memory_region_writeback(mr, offset, dline_size);
6930         }
6931     }
6932 }
6933 
6934 static const ARMCPRegInfo dcpop_reg[] = {
6935     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
6936       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
6937       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6938       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6939     REGINFO_SENTINEL
6940 };
6941 
6942 static const ARMCPRegInfo dcpodp_reg[] = {
6943     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
6944       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
6945       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6946       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6947     REGINFO_SENTINEL
6948 };
6949 #endif /*CONFIG_USER_ONLY*/
6950 
6951 static CPAccessResult access_aa64_tid5(CPUARMState *env, const ARMCPRegInfo *ri,
6952                                        bool isread)
6953 {
6954     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID5)) {
6955         return CP_ACCESS_TRAP_EL2;
6956     }
6957 
6958     return CP_ACCESS_OK;
6959 }
6960 
6961 static CPAccessResult access_mte(CPUARMState *env, const ARMCPRegInfo *ri,
6962                                  bool isread)
6963 {
6964     int el = arm_current_el(env);
6965 
6966     if (el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6967         uint64_t hcr = arm_hcr_el2_eff(env);
6968         if (!(hcr & HCR_ATA) && (!(hcr & HCR_E2H) || !(hcr & HCR_TGE))) {
6969             return CP_ACCESS_TRAP_EL2;
6970         }
6971     }
6972     if (el < 3 &&
6973         arm_feature(env, ARM_FEATURE_EL3) &&
6974         !(env->cp15.scr_el3 & SCR_ATA)) {
6975         return CP_ACCESS_TRAP_EL3;
6976     }
6977     return CP_ACCESS_OK;
6978 }
6979 
6980 static uint64_t tco_read(CPUARMState *env, const ARMCPRegInfo *ri)
6981 {
6982     return env->pstate & PSTATE_TCO;
6983 }
6984 
6985 static void tco_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
6986 {
6987     env->pstate = (env->pstate & ~PSTATE_TCO) | (val & PSTATE_TCO);
6988 }
6989 
6990 static const ARMCPRegInfo mte_reginfo[] = {
6991     { .name = "TFSRE0_EL1", .state = ARM_CP_STATE_AA64,
6992       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 1,
6993       .access = PL1_RW, .accessfn = access_mte,
6994       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[0]) },
6995     { .name = "TFSR_EL1", .state = ARM_CP_STATE_AA64,
6996       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 0,
6997       .access = PL1_RW, .accessfn = access_mte,
6998       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[1]) },
6999     { .name = "TFSR_EL2", .state = ARM_CP_STATE_AA64,
7000       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 6, .opc2 = 0,
7001       .access = PL2_RW, .accessfn = access_mte,
7002       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[2]) },
7003     { .name = "TFSR_EL3", .state = ARM_CP_STATE_AA64,
7004       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 6, .opc2 = 0,
7005       .access = PL3_RW,
7006       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[3]) },
7007     { .name = "RGSR_EL1", .state = ARM_CP_STATE_AA64,
7008       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 5,
7009       .access = PL1_RW, .accessfn = access_mte,
7010       .fieldoffset = offsetof(CPUARMState, cp15.rgsr_el1) },
7011     { .name = "GCR_EL1", .state = ARM_CP_STATE_AA64,
7012       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 6,
7013       .access = PL1_RW, .accessfn = access_mte,
7014       .fieldoffset = offsetof(CPUARMState, cp15.gcr_el1) },
7015     { .name = "GMID_EL1", .state = ARM_CP_STATE_AA64,
7016       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 4,
7017       .access = PL1_R, .accessfn = access_aa64_tid5,
7018       .type = ARM_CP_CONST, .resetvalue = GMID_EL1_BS },
7019     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7020       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7021       .type = ARM_CP_NO_RAW,
7022       .access = PL0_RW, .readfn = tco_read, .writefn = tco_write },
7023     { .name = "DC_IGVAC", .state = ARM_CP_STATE_AA64,
7024       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 3,
7025       .type = ARM_CP_NOP, .access = PL1_W,
7026       .accessfn = aa64_cacheop_poc_access },
7027     { .name = "DC_IGSW", .state = ARM_CP_STATE_AA64,
7028       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 4,
7029       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7030     { .name = "DC_IGDVAC", .state = ARM_CP_STATE_AA64,
7031       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 5,
7032       .type = ARM_CP_NOP, .access = PL1_W,
7033       .accessfn = aa64_cacheop_poc_access },
7034     { .name = "DC_IGDSW", .state = ARM_CP_STATE_AA64,
7035       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 6,
7036       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7037     { .name = "DC_CGSW", .state = ARM_CP_STATE_AA64,
7038       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 4,
7039       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7040     { .name = "DC_CGDSW", .state = ARM_CP_STATE_AA64,
7041       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 6,
7042       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7043     { .name = "DC_CIGSW", .state = ARM_CP_STATE_AA64,
7044       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 4,
7045       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7046     { .name = "DC_CIGDSW", .state = ARM_CP_STATE_AA64,
7047       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 6,
7048       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7049     REGINFO_SENTINEL
7050 };
7051 
7052 static const ARMCPRegInfo mte_tco_ro_reginfo[] = {
7053     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7054       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7055       .type = ARM_CP_CONST, .access = PL0_RW, },
7056     REGINFO_SENTINEL
7057 };
7058 
7059 static const ARMCPRegInfo mte_el0_cacheop_reginfo[] = {
7060     { .name = "DC_CGVAC", .state = ARM_CP_STATE_AA64,
7061       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 3,
7062       .type = ARM_CP_NOP, .access = PL0_W,
7063       .accessfn = aa64_cacheop_poc_access },
7064     { .name = "DC_CGDVAC", .state = ARM_CP_STATE_AA64,
7065       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 5,
7066       .type = ARM_CP_NOP, .access = PL0_W,
7067       .accessfn = aa64_cacheop_poc_access },
7068     { .name = "DC_CGVAP", .state = ARM_CP_STATE_AA64,
7069       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 3,
7070       .type = ARM_CP_NOP, .access = PL0_W,
7071       .accessfn = aa64_cacheop_poc_access },
7072     { .name = "DC_CGDVAP", .state = ARM_CP_STATE_AA64,
7073       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 5,
7074       .type = ARM_CP_NOP, .access = PL0_W,
7075       .accessfn = aa64_cacheop_poc_access },
7076     { .name = "DC_CGVADP", .state = ARM_CP_STATE_AA64,
7077       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 3,
7078       .type = ARM_CP_NOP, .access = PL0_W,
7079       .accessfn = aa64_cacheop_poc_access },
7080     { .name = "DC_CGDVADP", .state = ARM_CP_STATE_AA64,
7081       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 5,
7082       .type = ARM_CP_NOP, .access = PL0_W,
7083       .accessfn = aa64_cacheop_poc_access },
7084     { .name = "DC_CIGVAC", .state = ARM_CP_STATE_AA64,
7085       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 3,
7086       .type = ARM_CP_NOP, .access = PL0_W,
7087       .accessfn = aa64_cacheop_poc_access },
7088     { .name = "DC_CIGDVAC", .state = ARM_CP_STATE_AA64,
7089       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 5,
7090       .type = ARM_CP_NOP, .access = PL0_W,
7091       .accessfn = aa64_cacheop_poc_access },
7092     { .name = "DC_GVA", .state = ARM_CP_STATE_AA64,
7093       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 3,
7094       .access = PL0_W, .type = ARM_CP_DC_GVA,
7095 #ifndef CONFIG_USER_ONLY
7096       /* Avoid overhead of an access check that always passes in user-mode */
7097       .accessfn = aa64_zva_access,
7098 #endif
7099     },
7100     { .name = "DC_GZVA", .state = ARM_CP_STATE_AA64,
7101       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 4,
7102       .access = PL0_W, .type = ARM_CP_DC_GZVA,
7103 #ifndef CONFIG_USER_ONLY
7104       /* Avoid overhead of an access check that always passes in user-mode */
7105       .accessfn = aa64_zva_access,
7106 #endif
7107     },
7108     REGINFO_SENTINEL
7109 };
7110 
7111 #endif
7112 
7113 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
7114                                      bool isread)
7115 {
7116     int el = arm_current_el(env);
7117 
7118     if (el == 0) {
7119         uint64_t sctlr = arm_sctlr(env, el);
7120         if (!(sctlr & SCTLR_EnRCTX)) {
7121             return CP_ACCESS_TRAP;
7122         }
7123     } else if (el == 1) {
7124         uint64_t hcr = arm_hcr_el2_eff(env);
7125         if (hcr & HCR_NV) {
7126             return CP_ACCESS_TRAP_EL2;
7127         }
7128     }
7129     return CP_ACCESS_OK;
7130 }
7131 
7132 static const ARMCPRegInfo predinv_reginfo[] = {
7133     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
7134       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
7135       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7136     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
7137       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
7138       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7139     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
7140       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
7141       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7142     /*
7143      * Note the AArch32 opcodes have a different OPC1.
7144      */
7145     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
7146       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
7147       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7148     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
7149       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
7150       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7151     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
7152       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
7153       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7154     REGINFO_SENTINEL
7155 };
7156 
7157 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
7158 {
7159     /* Read the high 32 bits of the current CCSIDR */
7160     return extract64(ccsidr_read(env, ri), 32, 32);
7161 }
7162 
7163 static const ARMCPRegInfo ccsidr2_reginfo[] = {
7164     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
7165       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
7166       .access = PL1_R,
7167       .accessfn = access_aa64_tid2,
7168       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7169     REGINFO_SENTINEL
7170 };
7171 
7172 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7173                                        bool isread)
7174 {
7175     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7176         return CP_ACCESS_TRAP_EL2;
7177     }
7178 
7179     return CP_ACCESS_OK;
7180 }
7181 
7182 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7183                                        bool isread)
7184 {
7185     if (arm_feature(env, ARM_FEATURE_V8)) {
7186         return access_aa64_tid3(env, ri, isread);
7187     }
7188 
7189     return CP_ACCESS_OK;
7190 }
7191 
7192 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7193                                      bool isread)
7194 {
7195     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7196         return CP_ACCESS_TRAP_EL2;
7197     }
7198 
7199     return CP_ACCESS_OK;
7200 }
7201 
7202 static const ARMCPRegInfo jazelle_regs[] = {
7203     { .name = "JIDR",
7204       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7205       .access = PL1_R, .accessfn = access_jazelle,
7206       .type = ARM_CP_CONST, .resetvalue = 0 },
7207     { .name = "JOSCR",
7208       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7209       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7210     { .name = "JMCR",
7211       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7212       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7213     REGINFO_SENTINEL
7214 };
7215 
7216 static const ARMCPRegInfo vhe_reginfo[] = {
7217     { .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7218       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7219       .access = PL2_RW,
7220       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2]) },
7221     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7222       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7223       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7224       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7225 #ifndef CONFIG_USER_ONLY
7226     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7227       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7228       .fieldoffset =
7229         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7230       .type = ARM_CP_IO, .access = PL2_RW,
7231       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7232     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7233       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7234       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7235       .resetfn = gt_hv_timer_reset,
7236       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7237     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7238       .type = ARM_CP_IO,
7239       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7240       .access = PL2_RW,
7241       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7242       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7243     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7244       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7245       .type = ARM_CP_IO | ARM_CP_ALIAS,
7246       .access = PL2_RW, .accessfn = e2h_access,
7247       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7248       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7249     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7250       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7251       .type = ARM_CP_IO | ARM_CP_ALIAS,
7252       .access = PL2_RW, .accessfn = e2h_access,
7253       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7254       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7255     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7256       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7257       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7258       .access = PL2_RW, .accessfn = e2h_access,
7259       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7260     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7261       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7262       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7263       .access = PL2_RW, .accessfn = e2h_access,
7264       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7265     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7266       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7267       .type = ARM_CP_IO | ARM_CP_ALIAS,
7268       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7269       .access = PL2_RW, .accessfn = e2h_access,
7270       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7271     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7272       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7273       .type = ARM_CP_IO | ARM_CP_ALIAS,
7274       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7275       .access = PL2_RW, .accessfn = e2h_access,
7276       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7277 #endif
7278     REGINFO_SENTINEL
7279 };
7280 
7281 #ifndef CONFIG_USER_ONLY
7282 static const ARMCPRegInfo ats1e1_reginfo[] = {
7283     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7284       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7285       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7286       .writefn = ats_write64 },
7287     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7288       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7289       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7290       .writefn = ats_write64 },
7291     REGINFO_SENTINEL
7292 };
7293 
7294 static const ARMCPRegInfo ats1cp_reginfo[] = {
7295     { .name = "ATS1CPRP",
7296       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7297       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7298       .writefn = ats_write },
7299     { .name = "ATS1CPWP",
7300       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7301       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7302       .writefn = ats_write },
7303     REGINFO_SENTINEL
7304 };
7305 #endif
7306 
7307 /*
7308  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7309  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7310  * is non-zero, which is never for ARMv7, optionally in ARMv8
7311  * and mandatorily for ARMv8.2 and up.
7312  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7313  * implementation is RAZ/WI we can ignore this detail, as we
7314  * do for ACTLR.
7315  */
7316 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7317     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7318       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7319       .access = PL1_RW, .accessfn = access_tacr,
7320       .type = ARM_CP_CONST, .resetvalue = 0 },
7321     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7322       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7323       .access = PL2_RW, .type = ARM_CP_CONST,
7324       .resetvalue = 0 },
7325     REGINFO_SENTINEL
7326 };
7327 
7328 void register_cp_regs_for_features(ARMCPU *cpu)
7329 {
7330     /* Register all the coprocessor registers based on feature bits */
7331     CPUARMState *env = &cpu->env;
7332     if (arm_feature(env, ARM_FEATURE_M)) {
7333         /* M profile has no coprocessor registers */
7334         return;
7335     }
7336 
7337     define_arm_cp_regs(cpu, cp_reginfo);
7338     if (!arm_feature(env, ARM_FEATURE_V8)) {
7339         /* Must go early as it is full of wildcards that may be
7340          * overridden by later definitions.
7341          */
7342         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7343     }
7344 
7345     if (arm_feature(env, ARM_FEATURE_V6)) {
7346         /* The ID registers all have impdef reset values */
7347         ARMCPRegInfo v6_idregs[] = {
7348             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7349               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7350               .access = PL1_R, .type = ARM_CP_CONST,
7351               .accessfn = access_aa32_tid3,
7352               .resetvalue = cpu->isar.id_pfr0 },
7353             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7354              * the value of the GIC field until after we define these regs.
7355              */
7356             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7357               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7358               .access = PL1_R, .type = ARM_CP_NO_RAW,
7359               .accessfn = access_aa32_tid3,
7360               .readfn = id_pfr1_read,
7361               .writefn = arm_cp_write_ignore },
7362             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7363               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7364               .access = PL1_R, .type = ARM_CP_CONST,
7365               .accessfn = access_aa32_tid3,
7366               .resetvalue = cpu->isar.id_dfr0 },
7367             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7368               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7369               .access = PL1_R, .type = ARM_CP_CONST,
7370               .accessfn = access_aa32_tid3,
7371               .resetvalue = cpu->id_afr0 },
7372             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7373               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7374               .access = PL1_R, .type = ARM_CP_CONST,
7375               .accessfn = access_aa32_tid3,
7376               .resetvalue = cpu->isar.id_mmfr0 },
7377             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7378               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7379               .access = PL1_R, .type = ARM_CP_CONST,
7380               .accessfn = access_aa32_tid3,
7381               .resetvalue = cpu->isar.id_mmfr1 },
7382             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7383               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7384               .access = PL1_R, .type = ARM_CP_CONST,
7385               .accessfn = access_aa32_tid3,
7386               .resetvalue = cpu->isar.id_mmfr2 },
7387             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7388               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7389               .access = PL1_R, .type = ARM_CP_CONST,
7390               .accessfn = access_aa32_tid3,
7391               .resetvalue = cpu->isar.id_mmfr3 },
7392             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7393               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7394               .access = PL1_R, .type = ARM_CP_CONST,
7395               .accessfn = access_aa32_tid3,
7396               .resetvalue = cpu->isar.id_isar0 },
7397             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7398               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7399               .access = PL1_R, .type = ARM_CP_CONST,
7400               .accessfn = access_aa32_tid3,
7401               .resetvalue = cpu->isar.id_isar1 },
7402             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7403               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7404               .access = PL1_R, .type = ARM_CP_CONST,
7405               .accessfn = access_aa32_tid3,
7406               .resetvalue = cpu->isar.id_isar2 },
7407             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7408               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7409               .access = PL1_R, .type = ARM_CP_CONST,
7410               .accessfn = access_aa32_tid3,
7411               .resetvalue = cpu->isar.id_isar3 },
7412             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7413               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7414               .access = PL1_R, .type = ARM_CP_CONST,
7415               .accessfn = access_aa32_tid3,
7416               .resetvalue = cpu->isar.id_isar4 },
7417             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7418               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7419               .access = PL1_R, .type = ARM_CP_CONST,
7420               .accessfn = access_aa32_tid3,
7421               .resetvalue = cpu->isar.id_isar5 },
7422             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7423               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7424               .access = PL1_R, .type = ARM_CP_CONST,
7425               .accessfn = access_aa32_tid3,
7426               .resetvalue = cpu->isar.id_mmfr4 },
7427             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7428               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7429               .access = PL1_R, .type = ARM_CP_CONST,
7430               .accessfn = access_aa32_tid3,
7431               .resetvalue = cpu->isar.id_isar6 },
7432             REGINFO_SENTINEL
7433         };
7434         define_arm_cp_regs(cpu, v6_idregs);
7435         define_arm_cp_regs(cpu, v6_cp_reginfo);
7436     } else {
7437         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7438     }
7439     if (arm_feature(env, ARM_FEATURE_V6K)) {
7440         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7441     }
7442     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7443         !arm_feature(env, ARM_FEATURE_PMSA)) {
7444         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7445     }
7446     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7447         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7448     }
7449     if (arm_feature(env, ARM_FEATURE_V7)) {
7450         ARMCPRegInfo clidr = {
7451             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7452             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7453             .access = PL1_R, .type = ARM_CP_CONST,
7454             .accessfn = access_aa64_tid2,
7455             .resetvalue = cpu->clidr
7456         };
7457         define_one_arm_cp_reg(cpu, &clidr);
7458         define_arm_cp_regs(cpu, v7_cp_reginfo);
7459         define_debug_regs(cpu);
7460         define_pmu_regs(cpu);
7461     } else {
7462         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7463     }
7464     if (arm_feature(env, ARM_FEATURE_V8)) {
7465         /* AArch64 ID registers, which all have impdef reset values.
7466          * Note that within the ID register ranges the unused slots
7467          * must all RAZ, not UNDEF; future architecture versions may
7468          * define new registers here.
7469          */
7470         ARMCPRegInfo v8_idregs[] = {
7471             /*
7472              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7473              * emulation because we don't know the right value for the
7474              * GIC field until after we define these regs.
7475              */
7476             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7477               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7478               .access = PL1_R,
7479 #ifdef CONFIG_USER_ONLY
7480               .type = ARM_CP_CONST,
7481               .resetvalue = cpu->isar.id_aa64pfr0
7482 #else
7483               .type = ARM_CP_NO_RAW,
7484               .accessfn = access_aa64_tid3,
7485               .readfn = id_aa64pfr0_read,
7486               .writefn = arm_cp_write_ignore
7487 #endif
7488             },
7489             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7490               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7491               .access = PL1_R, .type = ARM_CP_CONST,
7492               .accessfn = access_aa64_tid3,
7493               .resetvalue = cpu->isar.id_aa64pfr1},
7494             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7495               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7496               .access = PL1_R, .type = ARM_CP_CONST,
7497               .accessfn = access_aa64_tid3,
7498               .resetvalue = 0 },
7499             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7500               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7501               .access = PL1_R, .type = ARM_CP_CONST,
7502               .accessfn = access_aa64_tid3,
7503               .resetvalue = 0 },
7504             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7505               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7506               .access = PL1_R, .type = ARM_CP_CONST,
7507               .accessfn = access_aa64_tid3,
7508               /* At present, only SVEver == 0 is defined anyway.  */
7509               .resetvalue = 0 },
7510             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7511               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7512               .access = PL1_R, .type = ARM_CP_CONST,
7513               .accessfn = access_aa64_tid3,
7514               .resetvalue = 0 },
7515             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7516               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7517               .access = PL1_R, .type = ARM_CP_CONST,
7518               .accessfn = access_aa64_tid3,
7519               .resetvalue = 0 },
7520             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7521               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7522               .access = PL1_R, .type = ARM_CP_CONST,
7523               .accessfn = access_aa64_tid3,
7524               .resetvalue = 0 },
7525             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7526               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7527               .access = PL1_R, .type = ARM_CP_CONST,
7528               .accessfn = access_aa64_tid3,
7529               .resetvalue = cpu->isar.id_aa64dfr0 },
7530             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7531               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7532               .access = PL1_R, .type = ARM_CP_CONST,
7533               .accessfn = access_aa64_tid3,
7534               .resetvalue = cpu->isar.id_aa64dfr1 },
7535             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7536               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7537               .access = PL1_R, .type = ARM_CP_CONST,
7538               .accessfn = access_aa64_tid3,
7539               .resetvalue = 0 },
7540             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7541               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7542               .access = PL1_R, .type = ARM_CP_CONST,
7543               .accessfn = access_aa64_tid3,
7544               .resetvalue = 0 },
7545             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7546               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7547               .access = PL1_R, .type = ARM_CP_CONST,
7548               .accessfn = access_aa64_tid3,
7549               .resetvalue = cpu->id_aa64afr0 },
7550             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7551               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7552               .access = PL1_R, .type = ARM_CP_CONST,
7553               .accessfn = access_aa64_tid3,
7554               .resetvalue = cpu->id_aa64afr1 },
7555             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7556               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7557               .access = PL1_R, .type = ARM_CP_CONST,
7558               .accessfn = access_aa64_tid3,
7559               .resetvalue = 0 },
7560             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7561               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7562               .access = PL1_R, .type = ARM_CP_CONST,
7563               .accessfn = access_aa64_tid3,
7564               .resetvalue = 0 },
7565             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7566               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7567               .access = PL1_R, .type = ARM_CP_CONST,
7568               .accessfn = access_aa64_tid3,
7569               .resetvalue = cpu->isar.id_aa64isar0 },
7570             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7571               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7572               .access = PL1_R, .type = ARM_CP_CONST,
7573               .accessfn = access_aa64_tid3,
7574               .resetvalue = cpu->isar.id_aa64isar1 },
7575             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7576               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7577               .access = PL1_R, .type = ARM_CP_CONST,
7578               .accessfn = access_aa64_tid3,
7579               .resetvalue = 0 },
7580             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7581               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7582               .access = PL1_R, .type = ARM_CP_CONST,
7583               .accessfn = access_aa64_tid3,
7584               .resetvalue = 0 },
7585             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7586               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7587               .access = PL1_R, .type = ARM_CP_CONST,
7588               .accessfn = access_aa64_tid3,
7589               .resetvalue = 0 },
7590             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7591               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7592               .access = PL1_R, .type = ARM_CP_CONST,
7593               .accessfn = access_aa64_tid3,
7594               .resetvalue = 0 },
7595             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7596               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7597               .access = PL1_R, .type = ARM_CP_CONST,
7598               .accessfn = access_aa64_tid3,
7599               .resetvalue = 0 },
7600             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7601               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7602               .access = PL1_R, .type = ARM_CP_CONST,
7603               .accessfn = access_aa64_tid3,
7604               .resetvalue = 0 },
7605             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7606               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7607               .access = PL1_R, .type = ARM_CP_CONST,
7608               .accessfn = access_aa64_tid3,
7609               .resetvalue = cpu->isar.id_aa64mmfr0 },
7610             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7611               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7612               .access = PL1_R, .type = ARM_CP_CONST,
7613               .accessfn = access_aa64_tid3,
7614               .resetvalue = cpu->isar.id_aa64mmfr1 },
7615             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7616               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7617               .access = PL1_R, .type = ARM_CP_CONST,
7618               .accessfn = access_aa64_tid3,
7619               .resetvalue = cpu->isar.id_aa64mmfr2 },
7620             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7621               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7622               .access = PL1_R, .type = ARM_CP_CONST,
7623               .accessfn = access_aa64_tid3,
7624               .resetvalue = 0 },
7625             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7626               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7627               .access = PL1_R, .type = ARM_CP_CONST,
7628               .accessfn = access_aa64_tid3,
7629               .resetvalue = 0 },
7630             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7631               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7632               .access = PL1_R, .type = ARM_CP_CONST,
7633               .accessfn = access_aa64_tid3,
7634               .resetvalue = 0 },
7635             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7636               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7637               .access = PL1_R, .type = ARM_CP_CONST,
7638               .accessfn = access_aa64_tid3,
7639               .resetvalue = 0 },
7640             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7641               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7642               .access = PL1_R, .type = ARM_CP_CONST,
7643               .accessfn = access_aa64_tid3,
7644               .resetvalue = 0 },
7645             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7646               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7647               .access = PL1_R, .type = ARM_CP_CONST,
7648               .accessfn = access_aa64_tid3,
7649               .resetvalue = cpu->isar.mvfr0 },
7650             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7651               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7652               .access = PL1_R, .type = ARM_CP_CONST,
7653               .accessfn = access_aa64_tid3,
7654               .resetvalue = cpu->isar.mvfr1 },
7655             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7656               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7657               .access = PL1_R, .type = ARM_CP_CONST,
7658               .accessfn = access_aa64_tid3,
7659               .resetvalue = cpu->isar.mvfr2 },
7660             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7661               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7662               .access = PL1_R, .type = ARM_CP_CONST,
7663               .accessfn = access_aa64_tid3,
7664               .resetvalue = 0 },
7665             { .name = "MVFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7666               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7667               .access = PL1_R, .type = ARM_CP_CONST,
7668               .accessfn = access_aa64_tid3,
7669               .resetvalue = 0 },
7670             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7671               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7672               .access = PL1_R, .type = ARM_CP_CONST,
7673               .accessfn = access_aa64_tid3,
7674               .resetvalue = 0 },
7675             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7676               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7677               .access = PL1_R, .type = ARM_CP_CONST,
7678               .accessfn = access_aa64_tid3,
7679               .resetvalue = 0 },
7680             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7681               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7682               .access = PL1_R, .type = ARM_CP_CONST,
7683               .accessfn = access_aa64_tid3,
7684               .resetvalue = 0 },
7685             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7686               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7687               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7688               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7689             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7690               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7691               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7692               .resetvalue = cpu->pmceid0 },
7693             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7694               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7695               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7696               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7697             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7698               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7699               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7700               .resetvalue = cpu->pmceid1 },
7701             REGINFO_SENTINEL
7702         };
7703 #ifdef CONFIG_USER_ONLY
7704         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7705             { .name = "ID_AA64PFR0_EL1",
7706               .exported_bits = 0x000f000f00ff0000,
7707               .fixed_bits    = 0x0000000000000011 },
7708             { .name = "ID_AA64PFR1_EL1",
7709               .exported_bits = 0x00000000000000f0 },
7710             { .name = "ID_AA64PFR*_EL1_RESERVED",
7711               .is_glob = true                     },
7712             { .name = "ID_AA64ZFR0_EL1"           },
7713             { .name = "ID_AA64MMFR0_EL1",
7714               .fixed_bits    = 0x00000000ff000000 },
7715             { .name = "ID_AA64MMFR1_EL1"          },
7716             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7717               .is_glob = true                     },
7718             { .name = "ID_AA64DFR0_EL1",
7719               .fixed_bits    = 0x0000000000000006 },
7720             { .name = "ID_AA64DFR1_EL1"           },
7721             { .name = "ID_AA64DFR*_EL1_RESERVED",
7722               .is_glob = true                     },
7723             { .name = "ID_AA64AFR*",
7724               .is_glob = true                     },
7725             { .name = "ID_AA64ISAR0_EL1",
7726               .exported_bits = 0x00fffffff0fffff0 },
7727             { .name = "ID_AA64ISAR1_EL1",
7728               .exported_bits = 0x000000f0ffffffff },
7729             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7730               .is_glob = true                     },
7731             REGUSERINFO_SENTINEL
7732         };
7733         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7734 #endif
7735         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7736         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7737             !arm_feature(env, ARM_FEATURE_EL2)) {
7738             ARMCPRegInfo rvbar = {
7739                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7740                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7741                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
7742             };
7743             define_one_arm_cp_reg(cpu, &rvbar);
7744         }
7745         define_arm_cp_regs(cpu, v8_idregs);
7746         define_arm_cp_regs(cpu, v8_cp_reginfo);
7747     }
7748     if (arm_feature(env, ARM_FEATURE_EL2)) {
7749         uint64_t vmpidr_def = mpidr_read_val(env);
7750         ARMCPRegInfo vpidr_regs[] = {
7751             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7752               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7753               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7754               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
7755               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7756             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7757               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7758               .access = PL2_RW, .resetvalue = cpu->midr,
7759               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7760             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7761               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7762               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7763               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
7764               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7765             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7766               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7767               .access = PL2_RW,
7768               .resetvalue = vmpidr_def,
7769               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7770             REGINFO_SENTINEL
7771         };
7772         define_arm_cp_regs(cpu, vpidr_regs);
7773         define_arm_cp_regs(cpu, el2_cp_reginfo);
7774         if (arm_feature(env, ARM_FEATURE_V8)) {
7775             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
7776         }
7777         if (cpu_isar_feature(aa64_sel2, cpu)) {
7778             define_arm_cp_regs(cpu, el2_sec_cp_reginfo);
7779         }
7780         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
7781         if (!arm_feature(env, ARM_FEATURE_EL3)) {
7782             ARMCPRegInfo rvbar = {
7783                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
7784                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
7785                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
7786             };
7787             define_one_arm_cp_reg(cpu, &rvbar);
7788         }
7789     } else {
7790         /* If EL2 is missing but higher ELs are enabled, we need to
7791          * register the no_el2 reginfos.
7792          */
7793         if (arm_feature(env, ARM_FEATURE_EL3)) {
7794             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
7795              * of MIDR_EL1 and MPIDR_EL1.
7796              */
7797             ARMCPRegInfo vpidr_regs[] = {
7798                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7799                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7800                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
7801                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
7802                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7803                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7804                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7805                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
7806                   .type = ARM_CP_NO_RAW,
7807                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
7808                 REGINFO_SENTINEL
7809             };
7810             define_arm_cp_regs(cpu, vpidr_regs);
7811             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
7812             if (arm_feature(env, ARM_FEATURE_V8)) {
7813                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
7814             }
7815         }
7816     }
7817     if (arm_feature(env, ARM_FEATURE_EL3)) {
7818         define_arm_cp_regs(cpu, el3_cp_reginfo);
7819         ARMCPRegInfo el3_regs[] = {
7820             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
7821               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
7822               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
7823             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
7824               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
7825               .access = PL3_RW,
7826               .raw_writefn = raw_write, .writefn = sctlr_write,
7827               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
7828               .resetvalue = cpu->reset_sctlr },
7829             REGINFO_SENTINEL
7830         };
7831 
7832         define_arm_cp_regs(cpu, el3_regs);
7833     }
7834     /* The behaviour of NSACR is sufficiently various that we don't
7835      * try to describe it in a single reginfo:
7836      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
7837      *     reads as constant 0xc00 from NS EL1 and NS EL2
7838      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
7839      *  if v7 without EL3, register doesn't exist
7840      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
7841      */
7842     if (arm_feature(env, ARM_FEATURE_EL3)) {
7843         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7844             ARMCPRegInfo nsacr = {
7845                 .name = "NSACR", .type = ARM_CP_CONST,
7846                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7847                 .access = PL1_RW, .accessfn = nsacr_access,
7848                 .resetvalue = 0xc00
7849             };
7850             define_one_arm_cp_reg(cpu, &nsacr);
7851         } else {
7852             ARMCPRegInfo nsacr = {
7853                 .name = "NSACR",
7854                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7855                 .access = PL3_RW | PL1_R,
7856                 .resetvalue = 0,
7857                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
7858             };
7859             define_one_arm_cp_reg(cpu, &nsacr);
7860         }
7861     } else {
7862         if (arm_feature(env, ARM_FEATURE_V8)) {
7863             ARMCPRegInfo nsacr = {
7864                 .name = "NSACR", .type = ARM_CP_CONST,
7865                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7866                 .access = PL1_R,
7867                 .resetvalue = 0xc00
7868             };
7869             define_one_arm_cp_reg(cpu, &nsacr);
7870         }
7871     }
7872 
7873     if (arm_feature(env, ARM_FEATURE_PMSA)) {
7874         if (arm_feature(env, ARM_FEATURE_V6)) {
7875             /* PMSAv6 not implemented */
7876             assert(arm_feature(env, ARM_FEATURE_V7));
7877             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7878             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
7879         } else {
7880             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
7881         }
7882     } else {
7883         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7884         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
7885         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
7886         if (cpu_isar_feature(aa32_hpd, cpu)) {
7887             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
7888         }
7889     }
7890     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
7891         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
7892     }
7893     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
7894         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
7895     }
7896     if (arm_feature(env, ARM_FEATURE_VAPA)) {
7897         define_arm_cp_regs(cpu, vapa_cp_reginfo);
7898     }
7899     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
7900         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
7901     }
7902     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
7903         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
7904     }
7905     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
7906         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
7907     }
7908     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
7909         define_arm_cp_regs(cpu, omap_cp_reginfo);
7910     }
7911     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
7912         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
7913     }
7914     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
7915         define_arm_cp_regs(cpu, xscale_cp_reginfo);
7916     }
7917     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
7918         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
7919     }
7920     if (arm_feature(env, ARM_FEATURE_LPAE)) {
7921         define_arm_cp_regs(cpu, lpae_cp_reginfo);
7922     }
7923     if (cpu_isar_feature(aa32_jazelle, cpu)) {
7924         define_arm_cp_regs(cpu, jazelle_regs);
7925     }
7926     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
7927      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
7928      * be read-only (ie write causes UNDEF exception).
7929      */
7930     {
7931         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
7932             /* Pre-v8 MIDR space.
7933              * Note that the MIDR isn't a simple constant register because
7934              * of the TI925 behaviour where writes to another register can
7935              * cause the MIDR value to change.
7936              *
7937              * Unimplemented registers in the c15 0 0 0 space default to
7938              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
7939              * and friends override accordingly.
7940              */
7941             { .name = "MIDR",
7942               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
7943               .access = PL1_R, .resetvalue = cpu->midr,
7944               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
7945               .readfn = midr_read,
7946               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7947               .type = ARM_CP_OVERRIDE },
7948             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
7949             { .name = "DUMMY",
7950               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
7951               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7952             { .name = "DUMMY",
7953               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
7954               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7955             { .name = "DUMMY",
7956               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
7957               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7958             { .name = "DUMMY",
7959               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
7960               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7961             { .name = "DUMMY",
7962               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
7963               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
7964             REGINFO_SENTINEL
7965         };
7966         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
7967             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
7968               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
7969               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
7970               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
7971               .readfn = midr_read },
7972             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
7973             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
7974               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
7975               .access = PL1_R, .resetvalue = cpu->midr },
7976             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
7977               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
7978               .access = PL1_R, .resetvalue = cpu->midr },
7979             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
7980               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
7981               .access = PL1_R,
7982               .accessfn = access_aa64_tid1,
7983               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
7984             REGINFO_SENTINEL
7985         };
7986         ARMCPRegInfo id_cp_reginfo[] = {
7987             /* These are common to v8 and pre-v8 */
7988             { .name = "CTR",
7989               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
7990               .access = PL1_R, .accessfn = ctr_el0_access,
7991               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
7992             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
7993               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
7994               .access = PL0_R, .accessfn = ctr_el0_access,
7995               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
7996             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
7997             { .name = "TCMTR",
7998               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
7999               .access = PL1_R,
8000               .accessfn = access_aa32_tid1,
8001               .type = ARM_CP_CONST, .resetvalue = 0 },
8002             REGINFO_SENTINEL
8003         };
8004         /* TLBTR is specific to VMSA */
8005         ARMCPRegInfo id_tlbtr_reginfo = {
8006               .name = "TLBTR",
8007               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
8008               .access = PL1_R,
8009               .accessfn = access_aa32_tid1,
8010               .type = ARM_CP_CONST, .resetvalue = 0,
8011         };
8012         /* MPUIR is specific to PMSA V6+ */
8013         ARMCPRegInfo id_mpuir_reginfo = {
8014               .name = "MPUIR",
8015               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8016               .access = PL1_R, .type = ARM_CP_CONST,
8017               .resetvalue = cpu->pmsav7_dregion << 8
8018         };
8019         ARMCPRegInfo crn0_wi_reginfo = {
8020             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
8021             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
8022             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
8023         };
8024 #ifdef CONFIG_USER_ONLY
8025         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
8026             { .name = "MIDR_EL1",
8027               .exported_bits = 0x00000000ffffffff },
8028             { .name = "REVIDR_EL1"                },
8029             REGUSERINFO_SENTINEL
8030         };
8031         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
8032 #endif
8033         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
8034             arm_feature(env, ARM_FEATURE_STRONGARM)) {
8035             ARMCPRegInfo *r;
8036             /* Register the blanket "writes ignored" value first to cover the
8037              * whole space. Then update the specific ID registers to allow write
8038              * access, so that they ignore writes rather than causing them to
8039              * UNDEF.
8040              */
8041             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
8042             for (r = id_pre_v8_midr_cp_reginfo;
8043                  r->type != ARM_CP_SENTINEL; r++) {
8044                 r->access = PL1_RW;
8045             }
8046             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
8047                 r->access = PL1_RW;
8048             }
8049             id_mpuir_reginfo.access = PL1_RW;
8050             id_tlbtr_reginfo.access = PL1_RW;
8051         }
8052         if (arm_feature(env, ARM_FEATURE_V8)) {
8053             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
8054         } else {
8055             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
8056         }
8057         define_arm_cp_regs(cpu, id_cp_reginfo);
8058         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
8059             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
8060         } else if (arm_feature(env, ARM_FEATURE_V7)) {
8061             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
8062         }
8063     }
8064 
8065     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
8066         ARMCPRegInfo mpidr_cp_reginfo[] = {
8067             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
8068               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
8069               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
8070             REGINFO_SENTINEL
8071         };
8072 #ifdef CONFIG_USER_ONLY
8073         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
8074             { .name = "MPIDR_EL1",
8075               .fixed_bits = 0x0000000080000000 },
8076             REGUSERINFO_SENTINEL
8077         };
8078         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
8079 #endif
8080         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
8081     }
8082 
8083     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
8084         ARMCPRegInfo auxcr_reginfo[] = {
8085             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
8086               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
8087               .access = PL1_RW, .accessfn = access_tacr,
8088               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
8089             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
8090               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
8091               .access = PL2_RW, .type = ARM_CP_CONST,
8092               .resetvalue = 0 },
8093             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
8094               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
8095               .access = PL3_RW, .type = ARM_CP_CONST,
8096               .resetvalue = 0 },
8097             REGINFO_SENTINEL
8098         };
8099         define_arm_cp_regs(cpu, auxcr_reginfo);
8100         if (cpu_isar_feature(aa32_ac2, cpu)) {
8101             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
8102         }
8103     }
8104 
8105     if (arm_feature(env, ARM_FEATURE_CBAR)) {
8106         /*
8107          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
8108          * There are two flavours:
8109          *  (1) older 32-bit only cores have a simple 32-bit CBAR
8110          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
8111          *      32-bit register visible to AArch32 at a different encoding
8112          *      to the "flavour 1" register and with the bits rearranged to
8113          *      be able to squash a 64-bit address into the 32-bit view.
8114          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
8115          * in future if we support AArch32-only configs of some of the
8116          * AArch64 cores we might need to add a specific feature flag
8117          * to indicate cores with "flavour 2" CBAR.
8118          */
8119         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8120             /* 32 bit view is [31:18] 0...0 [43:32]. */
8121             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
8122                 | extract64(cpu->reset_cbar, 32, 12);
8123             ARMCPRegInfo cbar_reginfo[] = {
8124                 { .name = "CBAR",
8125                   .type = ARM_CP_CONST,
8126                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
8127                   .access = PL1_R, .resetvalue = cbar32 },
8128                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
8129                   .type = ARM_CP_CONST,
8130                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
8131                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
8132                 REGINFO_SENTINEL
8133             };
8134             /* We don't implement a r/w 64 bit CBAR currently */
8135             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
8136             define_arm_cp_regs(cpu, cbar_reginfo);
8137         } else {
8138             ARMCPRegInfo cbar = {
8139                 .name = "CBAR",
8140                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
8141                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
8142                 .fieldoffset = offsetof(CPUARMState,
8143                                         cp15.c15_config_base_address)
8144             };
8145             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
8146                 cbar.access = PL1_R;
8147                 cbar.fieldoffset = 0;
8148                 cbar.type = ARM_CP_CONST;
8149             }
8150             define_one_arm_cp_reg(cpu, &cbar);
8151         }
8152     }
8153 
8154     if (arm_feature(env, ARM_FEATURE_VBAR)) {
8155         ARMCPRegInfo vbar_cp_reginfo[] = {
8156             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
8157               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
8158               .access = PL1_RW, .writefn = vbar_write,
8159               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
8160                                      offsetof(CPUARMState, cp15.vbar_ns) },
8161               .resetvalue = 0 },
8162             REGINFO_SENTINEL
8163         };
8164         define_arm_cp_regs(cpu, vbar_cp_reginfo);
8165     }
8166 
8167     /* Generic registers whose values depend on the implementation */
8168     {
8169         ARMCPRegInfo sctlr = {
8170             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8171             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8172             .access = PL1_RW, .accessfn = access_tvm_trvm,
8173             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8174                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8175             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8176             .raw_writefn = raw_write,
8177         };
8178         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8179             /* Normally we would always end the TB on an SCTLR write, but Linux
8180              * arch/arm/mach-pxa/sleep.S expects two instructions following
8181              * an MMU enable to execute from cache.  Imitate this behaviour.
8182              */
8183             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8184         }
8185         define_one_arm_cp_reg(cpu, &sctlr);
8186     }
8187 
8188     if (cpu_isar_feature(aa64_lor, cpu)) {
8189         define_arm_cp_regs(cpu, lor_reginfo);
8190     }
8191     if (cpu_isar_feature(aa64_pan, cpu)) {
8192         define_one_arm_cp_reg(cpu, &pan_reginfo);
8193     }
8194 #ifndef CONFIG_USER_ONLY
8195     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8196         define_arm_cp_regs(cpu, ats1e1_reginfo);
8197     }
8198     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8199         define_arm_cp_regs(cpu, ats1cp_reginfo);
8200     }
8201 #endif
8202     if (cpu_isar_feature(aa64_uao, cpu)) {
8203         define_one_arm_cp_reg(cpu, &uao_reginfo);
8204     }
8205 
8206     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8207         define_arm_cp_regs(cpu, vhe_reginfo);
8208     }
8209 
8210     if (cpu_isar_feature(aa64_sve, cpu)) {
8211         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
8212         if (arm_feature(env, ARM_FEATURE_EL2)) {
8213             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
8214         } else {
8215             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
8216         }
8217         if (arm_feature(env, ARM_FEATURE_EL3)) {
8218             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
8219         }
8220     }
8221 
8222 #ifdef TARGET_AARCH64
8223     if (cpu_isar_feature(aa64_pauth, cpu)) {
8224         define_arm_cp_regs(cpu, pauth_reginfo);
8225     }
8226     if (cpu_isar_feature(aa64_rndr, cpu)) {
8227         define_arm_cp_regs(cpu, rndr_reginfo);
8228     }
8229 #ifndef CONFIG_USER_ONLY
8230     /* Data Cache clean instructions up to PoP */
8231     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8232         define_one_arm_cp_reg(cpu, dcpop_reg);
8233 
8234         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8235             define_one_arm_cp_reg(cpu, dcpodp_reg);
8236         }
8237     }
8238 #endif /*CONFIG_USER_ONLY*/
8239 
8240     /*
8241      * If full MTE is enabled, add all of the system registers.
8242      * If only "instructions available at EL0" are enabled,
8243      * then define only a RAZ/WI version of PSTATE.TCO.
8244      */
8245     if (cpu_isar_feature(aa64_mte, cpu)) {
8246         define_arm_cp_regs(cpu, mte_reginfo);
8247         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8248     } else if (cpu_isar_feature(aa64_mte_insn_reg, cpu)) {
8249         define_arm_cp_regs(cpu, mte_tco_ro_reginfo);
8250         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8251     }
8252 #endif
8253 
8254     if (cpu_isar_feature(any_predinv, cpu)) {
8255         define_arm_cp_regs(cpu, predinv_reginfo);
8256     }
8257 
8258     if (cpu_isar_feature(any_ccidx, cpu)) {
8259         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8260     }
8261 
8262 #ifndef CONFIG_USER_ONLY
8263     /*
8264      * Register redirections and aliases must be done last,
8265      * after the registers from the other extensions have been defined.
8266      */
8267     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8268         define_arm_vh_e2h_redirects_aliases(cpu);
8269     }
8270 #endif
8271 }
8272 
8273 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
8274 {
8275     CPUState *cs = CPU(cpu);
8276     CPUARMState *env = &cpu->env;
8277 
8278     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8279         /*
8280          * The lower part of each SVE register aliases to the FPU
8281          * registers so we don't need to include both.
8282          */
8283 #ifdef TARGET_AARCH64
8284         if (isar_feature_aa64_sve(&cpu->isar)) {
8285             gdb_register_coprocessor(cs, arm_gdb_get_svereg, arm_gdb_set_svereg,
8286                                      arm_gen_dynamic_svereg_xml(cs, cs->gdb_num_regs),
8287                                      "sve-registers.xml", 0);
8288         } else
8289 #endif
8290         {
8291             gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
8292                                      aarch64_fpu_gdb_set_reg,
8293                                      34, "aarch64-fpu.xml", 0);
8294         }
8295     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
8296         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8297                                  51, "arm-neon.xml", 0);
8298     } else if (cpu_isar_feature(aa32_simd_r32, cpu)) {
8299         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8300                                  35, "arm-vfp3.xml", 0);
8301     } else if (cpu_isar_feature(aa32_vfp_simd, cpu)) {
8302         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8303                                  19, "arm-vfp.xml", 0);
8304     }
8305     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
8306                              arm_gen_dynamic_sysreg_xml(cs, cs->gdb_num_regs),
8307                              "system-registers.xml", 0);
8308 
8309 }
8310 
8311 /* Sort alphabetically by type name, except for "any". */
8312 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8313 {
8314     ObjectClass *class_a = (ObjectClass *)a;
8315     ObjectClass *class_b = (ObjectClass *)b;
8316     const char *name_a, *name_b;
8317 
8318     name_a = object_class_get_name(class_a);
8319     name_b = object_class_get_name(class_b);
8320     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8321         return 1;
8322     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8323         return -1;
8324     } else {
8325         return strcmp(name_a, name_b);
8326     }
8327 }
8328 
8329 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8330 {
8331     ObjectClass *oc = data;
8332     const char *typename;
8333     char *name;
8334 
8335     typename = object_class_get_name(oc);
8336     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8337     qemu_printf("  %s\n", name);
8338     g_free(name);
8339 }
8340 
8341 void arm_cpu_list(void)
8342 {
8343     GSList *list;
8344 
8345     list = object_class_get_list(TYPE_ARM_CPU, false);
8346     list = g_slist_sort(list, arm_cpu_list_compare);
8347     qemu_printf("Available CPUs:\n");
8348     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8349     g_slist_free(list);
8350 }
8351 
8352 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8353 {
8354     ObjectClass *oc = data;
8355     CpuDefinitionInfoList **cpu_list = user_data;
8356     CpuDefinitionInfo *info;
8357     const char *typename;
8358 
8359     typename = object_class_get_name(oc);
8360     info = g_malloc0(sizeof(*info));
8361     info->name = g_strndup(typename,
8362                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8363     info->q_typename = g_strdup(typename);
8364 
8365     QAPI_LIST_PREPEND(*cpu_list, info);
8366 }
8367 
8368 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8369 {
8370     CpuDefinitionInfoList *cpu_list = NULL;
8371     GSList *list;
8372 
8373     list = object_class_get_list(TYPE_ARM_CPU, false);
8374     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8375     g_slist_free(list);
8376 
8377     return cpu_list;
8378 }
8379 
8380 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8381                                    void *opaque, int state, int secstate,
8382                                    int crm, int opc1, int opc2,
8383                                    const char *name)
8384 {
8385     /* Private utility function for define_one_arm_cp_reg_with_opaque():
8386      * add a single reginfo struct to the hash table.
8387      */
8388     uint32_t *key = g_new(uint32_t, 1);
8389     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
8390     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
8391     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
8392 
8393     r2->name = g_strdup(name);
8394     /* Reset the secure state to the specific incoming state.  This is
8395      * necessary as the register may have been defined with both states.
8396      */
8397     r2->secure = secstate;
8398 
8399     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8400         /* Register is banked (using both entries in array).
8401          * Overwriting fieldoffset as the array is only used to define
8402          * banked registers but later only fieldoffset is used.
8403          */
8404         r2->fieldoffset = r->bank_fieldoffsets[ns];
8405     }
8406 
8407     if (state == ARM_CP_STATE_AA32) {
8408         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8409             /* If the register is banked then we don't need to migrate or
8410              * reset the 32-bit instance in certain cases:
8411              *
8412              * 1) If the register has both 32-bit and 64-bit instances then we
8413              *    can count on the 64-bit instance taking care of the
8414              *    non-secure bank.
8415              * 2) If ARMv8 is enabled then we can count on a 64-bit version
8416              *    taking care of the secure bank.  This requires that separate
8417              *    32 and 64-bit definitions are provided.
8418              */
8419             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8420                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
8421                 r2->type |= ARM_CP_ALIAS;
8422             }
8423         } else if ((secstate != r->secure) && !ns) {
8424             /* The register is not banked so we only want to allow migration of
8425              * the non-secure instance.
8426              */
8427             r2->type |= ARM_CP_ALIAS;
8428         }
8429 
8430         if (r->state == ARM_CP_STATE_BOTH) {
8431             /* We assume it is a cp15 register if the .cp field is left unset.
8432              */
8433             if (r2->cp == 0) {
8434                 r2->cp = 15;
8435             }
8436 
8437 #ifdef HOST_WORDS_BIGENDIAN
8438             if (r2->fieldoffset) {
8439                 r2->fieldoffset += sizeof(uint32_t);
8440             }
8441 #endif
8442         }
8443     }
8444     if (state == ARM_CP_STATE_AA64) {
8445         /* To allow abbreviation of ARMCPRegInfo
8446          * definitions, we treat cp == 0 as equivalent to
8447          * the value for "standard guest-visible sysreg".
8448          * STATE_BOTH definitions are also always "standard
8449          * sysreg" in their AArch64 view (the .cp value may
8450          * be non-zero for the benefit of the AArch32 view).
8451          */
8452         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8453             r2->cp = CP_REG_ARM64_SYSREG_CP;
8454         }
8455         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
8456                                   r2->opc0, opc1, opc2);
8457     } else {
8458         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
8459     }
8460     if (opaque) {
8461         r2->opaque = opaque;
8462     }
8463     /* reginfo passed to helpers is correct for the actual access,
8464      * and is never ARM_CP_STATE_BOTH:
8465      */
8466     r2->state = state;
8467     /* Make sure reginfo passed to helpers for wildcarded regs
8468      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
8469      */
8470     r2->crm = crm;
8471     r2->opc1 = opc1;
8472     r2->opc2 = opc2;
8473     /* By convention, for wildcarded registers only the first
8474      * entry is used for migration; the others are marked as
8475      * ALIAS so we don't try to transfer the register
8476      * multiple times. Special registers (ie NOP/WFI) are
8477      * never migratable and not even raw-accessible.
8478      */
8479     if ((r->type & ARM_CP_SPECIAL)) {
8480         r2->type |= ARM_CP_NO_RAW;
8481     }
8482     if (((r->crm == CP_ANY) && crm != 0) ||
8483         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8484         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8485         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8486     }
8487 
8488     /* Check that raw accesses are either forbidden or handled. Note that
8489      * we can't assert this earlier because the setup of fieldoffset for
8490      * banked registers has to be done first.
8491      */
8492     if (!(r2->type & ARM_CP_NO_RAW)) {
8493         assert(!raw_accessors_invalid(r2));
8494     }
8495 
8496     /* Overriding of an existing definition must be explicitly
8497      * requested.
8498      */
8499     if (!(r->type & ARM_CP_OVERRIDE)) {
8500         ARMCPRegInfo *oldreg;
8501         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
8502         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
8503             fprintf(stderr, "Register redefined: cp=%d %d bit "
8504                     "crn=%d crm=%d opc1=%d opc2=%d, "
8505                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
8506                     r2->crn, r2->crm, r2->opc1, r2->opc2,
8507                     oldreg->name, r2->name);
8508             g_assert_not_reached();
8509         }
8510     }
8511     g_hash_table_insert(cpu->cp_regs, key, r2);
8512 }
8513 
8514 
8515 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8516                                        const ARMCPRegInfo *r, void *opaque)
8517 {
8518     /* Define implementations of coprocessor registers.
8519      * We store these in a hashtable because typically
8520      * there are less than 150 registers in a space which
8521      * is 16*16*16*8*8 = 262144 in size.
8522      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8523      * If a register is defined twice then the second definition is
8524      * used, so this can be used to define some generic registers and
8525      * then override them with implementation specific variations.
8526      * At least one of the original and the second definition should
8527      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8528      * against accidental use.
8529      *
8530      * The state field defines whether the register is to be
8531      * visible in the AArch32 or AArch64 execution state. If the
8532      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8533      * reginfo structure for the AArch32 view, which sees the lower
8534      * 32 bits of the 64 bit register.
8535      *
8536      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8537      * be wildcarded. AArch64 registers are always considered to be 64
8538      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8539      * the register, if any.
8540      */
8541     int crm, opc1, opc2, state;
8542     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8543     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8544     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8545     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8546     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8547     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8548     /* 64 bit registers have only CRm and Opc1 fields */
8549     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8550     /* op0 only exists in the AArch64 encodings */
8551     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8552     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8553     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8554     /*
8555      * This API is only for Arm's system coprocessors (14 and 15) or
8556      * (M-profile or v7A-and-earlier only) for implementation defined
8557      * coprocessors in the range 0..7.  Our decode assumes this, since
8558      * 8..13 can be used for other insns including VFP and Neon. See
8559      * valid_cp() in translate.c.  Assert here that we haven't tried
8560      * to use an invalid coprocessor number.
8561      */
8562     switch (r->state) {
8563     case ARM_CP_STATE_BOTH:
8564         /* 0 has a special meaning, but otherwise the same rules as AA32. */
8565         if (r->cp == 0) {
8566             break;
8567         }
8568         /* fall through */
8569     case ARM_CP_STATE_AA32:
8570         if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
8571             !arm_feature(&cpu->env, ARM_FEATURE_M)) {
8572             assert(r->cp >= 14 && r->cp <= 15);
8573         } else {
8574             assert(r->cp < 8 || (r->cp >= 14 && r->cp <= 15));
8575         }
8576         break;
8577     case ARM_CP_STATE_AA64:
8578         assert(r->cp == 0 || r->cp == CP_REG_ARM64_SYSREG_CP);
8579         break;
8580     default:
8581         g_assert_not_reached();
8582     }
8583     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8584      * encodes a minimum access level for the register. We roll this
8585      * runtime check into our general permission check code, so check
8586      * here that the reginfo's specified permissions are strict enough
8587      * to encompass the generic architectural permission check.
8588      */
8589     if (r->state != ARM_CP_STATE_AA32) {
8590         int mask = 0;
8591         switch (r->opc1) {
8592         case 0:
8593             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8594             mask = PL0U_R | PL1_RW;
8595             break;
8596         case 1: case 2:
8597             /* min_EL EL1 */
8598             mask = PL1_RW;
8599             break;
8600         case 3:
8601             /* min_EL EL0 */
8602             mask = PL0_RW;
8603             break;
8604         case 4:
8605         case 5:
8606             /* min_EL EL2 */
8607             mask = PL2_RW;
8608             break;
8609         case 6:
8610             /* min_EL EL3 */
8611             mask = PL3_RW;
8612             break;
8613         case 7:
8614             /* min_EL EL1, secure mode only (we don't check the latter) */
8615             mask = PL1_RW;
8616             break;
8617         default:
8618             /* broken reginfo with out-of-range opc1 */
8619             assert(false);
8620             break;
8621         }
8622         /* assert our permissions are not too lax (stricter is fine) */
8623         assert((r->access & ~mask) == 0);
8624     }
8625 
8626     /* Check that the register definition has enough info to handle
8627      * reads and writes if they are permitted.
8628      */
8629     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
8630         if (r->access & PL3_R) {
8631             assert((r->fieldoffset ||
8632                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8633                    r->readfn);
8634         }
8635         if (r->access & PL3_W) {
8636             assert((r->fieldoffset ||
8637                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8638                    r->writefn);
8639         }
8640     }
8641     /* Bad type field probably means missing sentinel at end of reg list */
8642     assert(cptype_valid(r->type));
8643     for (crm = crmmin; crm <= crmmax; crm++) {
8644         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8645             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8646                 for (state = ARM_CP_STATE_AA32;
8647                      state <= ARM_CP_STATE_AA64; state++) {
8648                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8649                         continue;
8650                     }
8651                     if (state == ARM_CP_STATE_AA32) {
8652                         /* Under AArch32 CP registers can be common
8653                          * (same for secure and non-secure world) or banked.
8654                          */
8655                         char *name;
8656 
8657                         switch (r->secure) {
8658                         case ARM_CP_SECSTATE_S:
8659                         case ARM_CP_SECSTATE_NS:
8660                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8661                                                    r->secure, crm, opc1, opc2,
8662                                                    r->name);
8663                             break;
8664                         default:
8665                             name = g_strdup_printf("%s_S", r->name);
8666                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8667                                                    ARM_CP_SECSTATE_S,
8668                                                    crm, opc1, opc2, name);
8669                             g_free(name);
8670                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8671                                                    ARM_CP_SECSTATE_NS,
8672                                                    crm, opc1, opc2, r->name);
8673                             break;
8674                         }
8675                     } else {
8676                         /* AArch64 registers get mapped to non-secure instance
8677                          * of AArch32 */
8678                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8679                                                ARM_CP_SECSTATE_NS,
8680                                                crm, opc1, opc2, r->name);
8681                     }
8682                 }
8683             }
8684         }
8685     }
8686 }
8687 
8688 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
8689                                     const ARMCPRegInfo *regs, void *opaque)
8690 {
8691     /* Define a whole list of registers */
8692     const ARMCPRegInfo *r;
8693     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8694         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
8695     }
8696 }
8697 
8698 /*
8699  * Modify ARMCPRegInfo for access from userspace.
8700  *
8701  * This is a data driven modification directed by
8702  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8703  * user-space cannot alter any values and dynamic values pertaining to
8704  * execution state are hidden from user space view anyway.
8705  */
8706 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
8707 {
8708     const ARMCPRegUserSpaceInfo *m;
8709     ARMCPRegInfo *r;
8710 
8711     for (m = mods; m->name; m++) {
8712         GPatternSpec *pat = NULL;
8713         if (m->is_glob) {
8714             pat = g_pattern_spec_new(m->name);
8715         }
8716         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8717             if (pat && g_pattern_match_string(pat, r->name)) {
8718                 r->type = ARM_CP_CONST;
8719                 r->access = PL0U_R;
8720                 r->resetvalue = 0;
8721                 /* continue */
8722             } else if (strcmp(r->name, m->name) == 0) {
8723                 r->type = ARM_CP_CONST;
8724                 r->access = PL0U_R;
8725                 r->resetvalue &= m->exported_bits;
8726                 r->resetvalue |= m->fixed_bits;
8727                 break;
8728             }
8729         }
8730         if (pat) {
8731             g_pattern_spec_free(pat);
8732         }
8733     }
8734 }
8735 
8736 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8737 {
8738     return g_hash_table_lookup(cpregs, &encoded_cp);
8739 }
8740 
8741 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8742                          uint64_t value)
8743 {
8744     /* Helper coprocessor write function for write-ignore registers */
8745 }
8746 
8747 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8748 {
8749     /* Helper coprocessor write function for read-as-zero registers */
8750     return 0;
8751 }
8752 
8753 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8754 {
8755     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8756 }
8757 
8758 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8759 {
8760     /* Return true if it is not valid for us to switch to
8761      * this CPU mode (ie all the UNPREDICTABLE cases in
8762      * the ARM ARM CPSRWriteByInstr pseudocode).
8763      */
8764 
8765     /* Changes to or from Hyp via MSR and CPS are illegal. */
8766     if (write_type == CPSRWriteByInstr &&
8767         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8768          mode == ARM_CPU_MODE_HYP)) {
8769         return 1;
8770     }
8771 
8772     switch (mode) {
8773     case ARM_CPU_MODE_USR:
8774         return 0;
8775     case ARM_CPU_MODE_SYS:
8776     case ARM_CPU_MODE_SVC:
8777     case ARM_CPU_MODE_ABT:
8778     case ARM_CPU_MODE_UND:
8779     case ARM_CPU_MODE_IRQ:
8780     case ARM_CPU_MODE_FIQ:
8781         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
8782          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
8783          */
8784         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
8785          * and CPS are treated as illegal mode changes.
8786          */
8787         if (write_type == CPSRWriteByInstr &&
8788             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
8789             (arm_hcr_el2_eff(env) & HCR_TGE)) {
8790             return 1;
8791         }
8792         return 0;
8793     case ARM_CPU_MODE_HYP:
8794         return !arm_is_el2_enabled(env) || arm_current_el(env) < 2;
8795     case ARM_CPU_MODE_MON:
8796         return arm_current_el(env) < 3;
8797     default:
8798         return 1;
8799     }
8800 }
8801 
8802 uint32_t cpsr_read(CPUARMState *env)
8803 {
8804     int ZF;
8805     ZF = (env->ZF == 0);
8806     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
8807         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
8808         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
8809         | ((env->condexec_bits & 0xfc) << 8)
8810         | (env->GE << 16) | (env->daif & CPSR_AIF);
8811 }
8812 
8813 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
8814                 CPSRWriteType write_type)
8815 {
8816     uint32_t changed_daif;
8817 
8818     if (mask & CPSR_NZCV) {
8819         env->ZF = (~val) & CPSR_Z;
8820         env->NF = val;
8821         env->CF = (val >> 29) & 1;
8822         env->VF = (val << 3) & 0x80000000;
8823     }
8824     if (mask & CPSR_Q)
8825         env->QF = ((val & CPSR_Q) != 0);
8826     if (mask & CPSR_T)
8827         env->thumb = ((val & CPSR_T) != 0);
8828     if (mask & CPSR_IT_0_1) {
8829         env->condexec_bits &= ~3;
8830         env->condexec_bits |= (val >> 25) & 3;
8831     }
8832     if (mask & CPSR_IT_2_7) {
8833         env->condexec_bits &= 3;
8834         env->condexec_bits |= (val >> 8) & 0xfc;
8835     }
8836     if (mask & CPSR_GE) {
8837         env->GE = (val >> 16) & 0xf;
8838     }
8839 
8840     /* In a V7 implementation that includes the security extensions but does
8841      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
8842      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
8843      * bits respectively.
8844      *
8845      * In a V8 implementation, it is permitted for privileged software to
8846      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
8847      */
8848     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
8849         arm_feature(env, ARM_FEATURE_EL3) &&
8850         !arm_feature(env, ARM_FEATURE_EL2) &&
8851         !arm_is_secure(env)) {
8852 
8853         changed_daif = (env->daif ^ val) & mask;
8854 
8855         if (changed_daif & CPSR_A) {
8856             /* Check to see if we are allowed to change the masking of async
8857              * abort exceptions from a non-secure state.
8858              */
8859             if (!(env->cp15.scr_el3 & SCR_AW)) {
8860                 qemu_log_mask(LOG_GUEST_ERROR,
8861                               "Ignoring attempt to switch CPSR_A flag from "
8862                               "non-secure world with SCR.AW bit clear\n");
8863                 mask &= ~CPSR_A;
8864             }
8865         }
8866 
8867         if (changed_daif & CPSR_F) {
8868             /* Check to see if we are allowed to change the masking of FIQ
8869              * exceptions from a non-secure state.
8870              */
8871             if (!(env->cp15.scr_el3 & SCR_FW)) {
8872                 qemu_log_mask(LOG_GUEST_ERROR,
8873                               "Ignoring attempt to switch CPSR_F flag from "
8874                               "non-secure world with SCR.FW bit clear\n");
8875                 mask &= ~CPSR_F;
8876             }
8877 
8878             /* Check whether non-maskable FIQ (NMFI) support is enabled.
8879              * If this bit is set software is not allowed to mask
8880              * FIQs, but is allowed to set CPSR_F to 0.
8881              */
8882             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
8883                 (val & CPSR_F)) {
8884                 qemu_log_mask(LOG_GUEST_ERROR,
8885                               "Ignoring attempt to enable CPSR_F flag "
8886                               "(non-maskable FIQ [NMFI] support enabled)\n");
8887                 mask &= ~CPSR_F;
8888             }
8889         }
8890     }
8891 
8892     env->daif &= ~(CPSR_AIF & mask);
8893     env->daif |= val & CPSR_AIF & mask;
8894 
8895     if (write_type != CPSRWriteRaw &&
8896         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
8897         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
8898             /* Note that we can only get here in USR mode if this is a
8899              * gdb stub write; for this case we follow the architectural
8900              * behaviour for guest writes in USR mode of ignoring an attempt
8901              * to switch mode. (Those are caught by translate.c for writes
8902              * triggered by guest instructions.)
8903              */
8904             mask &= ~CPSR_M;
8905         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
8906             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
8907              * v7, and has defined behaviour in v8:
8908              *  + leave CPSR.M untouched
8909              *  + allow changes to the other CPSR fields
8910              *  + set PSTATE.IL
8911              * For user changes via the GDB stub, we don't set PSTATE.IL,
8912              * as this would be unnecessarily harsh for a user error.
8913              */
8914             mask &= ~CPSR_M;
8915             if (write_type != CPSRWriteByGDBStub &&
8916                 arm_feature(env, ARM_FEATURE_V8)) {
8917                 mask |= CPSR_IL;
8918                 val |= CPSR_IL;
8919             }
8920             qemu_log_mask(LOG_GUEST_ERROR,
8921                           "Illegal AArch32 mode switch attempt from %s to %s\n",
8922                           aarch32_mode_name(env->uncached_cpsr),
8923                           aarch32_mode_name(val));
8924         } else {
8925             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
8926                           write_type == CPSRWriteExceptionReturn ?
8927                           "Exception return from AArch32" :
8928                           "AArch32 mode switch from",
8929                           aarch32_mode_name(env->uncached_cpsr),
8930                           aarch32_mode_name(val), env->regs[15]);
8931             switch_mode(env, val & CPSR_M);
8932         }
8933     }
8934     mask &= ~CACHED_CPSR_BITS;
8935     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
8936 }
8937 
8938 /* Sign/zero extend */
8939 uint32_t HELPER(sxtb16)(uint32_t x)
8940 {
8941     uint32_t res;
8942     res = (uint16_t)(int8_t)x;
8943     res |= (uint32_t)(int8_t)(x >> 16) << 16;
8944     return res;
8945 }
8946 
8947 uint32_t HELPER(uxtb16)(uint32_t x)
8948 {
8949     uint32_t res;
8950     res = (uint16_t)(uint8_t)x;
8951     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
8952     return res;
8953 }
8954 
8955 int32_t HELPER(sdiv)(int32_t num, int32_t den)
8956 {
8957     if (den == 0)
8958       return 0;
8959     if (num == INT_MIN && den == -1)
8960       return INT_MIN;
8961     return num / den;
8962 }
8963 
8964 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
8965 {
8966     if (den == 0)
8967       return 0;
8968     return num / den;
8969 }
8970 
8971 uint32_t HELPER(rbit)(uint32_t x)
8972 {
8973     return revbit32(x);
8974 }
8975 
8976 #ifdef CONFIG_USER_ONLY
8977 
8978 static void switch_mode(CPUARMState *env, int mode)
8979 {
8980     ARMCPU *cpu = env_archcpu(env);
8981 
8982     if (mode != ARM_CPU_MODE_USR) {
8983         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
8984     }
8985 }
8986 
8987 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
8988                                  uint32_t cur_el, bool secure)
8989 {
8990     return 1;
8991 }
8992 
8993 void aarch64_sync_64_to_32(CPUARMState *env)
8994 {
8995     g_assert_not_reached();
8996 }
8997 
8998 #else
8999 
9000 static void switch_mode(CPUARMState *env, int mode)
9001 {
9002     int old_mode;
9003     int i;
9004 
9005     old_mode = env->uncached_cpsr & CPSR_M;
9006     if (mode == old_mode)
9007         return;
9008 
9009     if (old_mode == ARM_CPU_MODE_FIQ) {
9010         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
9011         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
9012     } else if (mode == ARM_CPU_MODE_FIQ) {
9013         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
9014         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
9015     }
9016 
9017     i = bank_number(old_mode);
9018     env->banked_r13[i] = env->regs[13];
9019     env->banked_spsr[i] = env->spsr;
9020 
9021     i = bank_number(mode);
9022     env->regs[13] = env->banked_r13[i];
9023     env->spsr = env->banked_spsr[i];
9024 
9025     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
9026     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
9027 }
9028 
9029 /* Physical Interrupt Target EL Lookup Table
9030  *
9031  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
9032  *
9033  * The below multi-dimensional table is used for looking up the target
9034  * exception level given numerous condition criteria.  Specifically, the
9035  * target EL is based on SCR and HCR routing controls as well as the
9036  * currently executing EL and secure state.
9037  *
9038  *    Dimensions:
9039  *    target_el_table[2][2][2][2][2][4]
9040  *                    |  |  |  |  |  +--- Current EL
9041  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
9042  *                    |  |  |  +--------- HCR mask override
9043  *                    |  |  +------------ SCR exec state control
9044  *                    |  +--------------- SCR mask override
9045  *                    +------------------ 32-bit(0)/64-bit(1) EL3
9046  *
9047  *    The table values are as such:
9048  *    0-3 = EL0-EL3
9049  *     -1 = Cannot occur
9050  *
9051  * The ARM ARM target EL table includes entries indicating that an "exception
9052  * is not taken".  The two cases where this is applicable are:
9053  *    1) An exception is taken from EL3 but the SCR does not have the exception
9054  *    routed to EL3.
9055  *    2) An exception is taken from EL2 but the HCR does not have the exception
9056  *    routed to EL2.
9057  * In these two cases, the below table contain a target of EL1.  This value is
9058  * returned as it is expected that the consumer of the table data will check
9059  * for "target EL >= current EL" to ensure the exception is not taken.
9060  *
9061  *            SCR     HCR
9062  *         64  EA     AMO                 From
9063  *        BIT IRQ     IMO      Non-secure         Secure
9064  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
9065  */
9066 static const int8_t target_el_table[2][2][2][2][2][4] = {
9067     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9068        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
9069       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9070        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
9071      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9072        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
9073       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9074        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
9075     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
9076        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 2,  2, -1,  1 },},},
9077       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1,  1,  1 },},
9078        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 2,  2,  2,  1 },},},},
9079      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
9080        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
9081       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},
9082        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},},},},
9083 };
9084 
9085 /*
9086  * Determine the target EL for physical exceptions
9087  */
9088 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9089                                  uint32_t cur_el, bool secure)
9090 {
9091     CPUARMState *env = cs->env_ptr;
9092     bool rw;
9093     bool scr;
9094     bool hcr;
9095     int target_el;
9096     /* Is the highest EL AArch64? */
9097     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
9098     uint64_t hcr_el2;
9099 
9100     if (arm_feature(env, ARM_FEATURE_EL3)) {
9101         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
9102     } else {
9103         /* Either EL2 is the highest EL (and so the EL2 register width
9104          * is given by is64); or there is no EL2 or EL3, in which case
9105          * the value of 'rw' does not affect the table lookup anyway.
9106          */
9107         rw = is64;
9108     }
9109 
9110     hcr_el2 = arm_hcr_el2_eff(env);
9111     switch (excp_idx) {
9112     case EXCP_IRQ:
9113         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
9114         hcr = hcr_el2 & HCR_IMO;
9115         break;
9116     case EXCP_FIQ:
9117         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
9118         hcr = hcr_el2 & HCR_FMO;
9119         break;
9120     default:
9121         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
9122         hcr = hcr_el2 & HCR_AMO;
9123         break;
9124     };
9125 
9126     /*
9127      * For these purposes, TGE and AMO/IMO/FMO both force the
9128      * interrupt to EL2.  Fold TGE into the bit extracted above.
9129      */
9130     hcr |= (hcr_el2 & HCR_TGE) != 0;
9131 
9132     /* Perform a table-lookup for the target EL given the current state */
9133     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
9134 
9135     assert(target_el > 0);
9136 
9137     return target_el;
9138 }
9139 
9140 void arm_log_exception(int idx)
9141 {
9142     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9143         const char *exc = NULL;
9144         static const char * const excnames[] = {
9145             [EXCP_UDEF] = "Undefined Instruction",
9146             [EXCP_SWI] = "SVC",
9147             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9148             [EXCP_DATA_ABORT] = "Data Abort",
9149             [EXCP_IRQ] = "IRQ",
9150             [EXCP_FIQ] = "FIQ",
9151             [EXCP_BKPT] = "Breakpoint",
9152             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9153             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9154             [EXCP_HVC] = "Hypervisor Call",
9155             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9156             [EXCP_SMC] = "Secure Monitor Call",
9157             [EXCP_VIRQ] = "Virtual IRQ",
9158             [EXCP_VFIQ] = "Virtual FIQ",
9159             [EXCP_SEMIHOST] = "Semihosting call",
9160             [EXCP_NOCP] = "v7M NOCP UsageFault",
9161             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9162             [EXCP_STKOF] = "v8M STKOF UsageFault",
9163             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9164             [EXCP_LSERR] = "v8M LSERR UsageFault",
9165             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9166         };
9167 
9168         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9169             exc = excnames[idx];
9170         }
9171         if (!exc) {
9172             exc = "unknown";
9173         }
9174         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
9175     }
9176 }
9177 
9178 /*
9179  * Function used to synchronize QEMU's AArch64 register set with AArch32
9180  * register set.  This is necessary when switching between AArch32 and AArch64
9181  * execution state.
9182  */
9183 void aarch64_sync_32_to_64(CPUARMState *env)
9184 {
9185     int i;
9186     uint32_t mode = env->uncached_cpsr & CPSR_M;
9187 
9188     /* We can blanket copy R[0:7] to X[0:7] */
9189     for (i = 0; i < 8; i++) {
9190         env->xregs[i] = env->regs[i];
9191     }
9192 
9193     /*
9194      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9195      * Otherwise, they come from the banked user regs.
9196      */
9197     if (mode == ARM_CPU_MODE_FIQ) {
9198         for (i = 8; i < 13; i++) {
9199             env->xregs[i] = env->usr_regs[i - 8];
9200         }
9201     } else {
9202         for (i = 8; i < 13; i++) {
9203             env->xregs[i] = env->regs[i];
9204         }
9205     }
9206 
9207     /*
9208      * Registers x13-x23 are the various mode SP and FP registers. Registers
9209      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9210      * from the mode banked register.
9211      */
9212     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9213         env->xregs[13] = env->regs[13];
9214         env->xregs[14] = env->regs[14];
9215     } else {
9216         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9217         /* HYP is an exception in that it is copied from r14 */
9218         if (mode == ARM_CPU_MODE_HYP) {
9219             env->xregs[14] = env->regs[14];
9220         } else {
9221             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9222         }
9223     }
9224 
9225     if (mode == ARM_CPU_MODE_HYP) {
9226         env->xregs[15] = env->regs[13];
9227     } else {
9228         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9229     }
9230 
9231     if (mode == ARM_CPU_MODE_IRQ) {
9232         env->xregs[16] = env->regs[14];
9233         env->xregs[17] = env->regs[13];
9234     } else {
9235         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9236         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9237     }
9238 
9239     if (mode == ARM_CPU_MODE_SVC) {
9240         env->xregs[18] = env->regs[14];
9241         env->xregs[19] = env->regs[13];
9242     } else {
9243         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9244         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9245     }
9246 
9247     if (mode == ARM_CPU_MODE_ABT) {
9248         env->xregs[20] = env->regs[14];
9249         env->xregs[21] = env->regs[13];
9250     } else {
9251         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9252         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9253     }
9254 
9255     if (mode == ARM_CPU_MODE_UND) {
9256         env->xregs[22] = env->regs[14];
9257         env->xregs[23] = env->regs[13];
9258     } else {
9259         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9260         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9261     }
9262 
9263     /*
9264      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9265      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9266      * FIQ bank for r8-r14.
9267      */
9268     if (mode == ARM_CPU_MODE_FIQ) {
9269         for (i = 24; i < 31; i++) {
9270             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9271         }
9272     } else {
9273         for (i = 24; i < 29; i++) {
9274             env->xregs[i] = env->fiq_regs[i - 24];
9275         }
9276         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9277         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9278     }
9279 
9280     env->pc = env->regs[15];
9281 }
9282 
9283 /*
9284  * Function used to synchronize QEMU's AArch32 register set with AArch64
9285  * register set.  This is necessary when switching between AArch32 and AArch64
9286  * execution state.
9287  */
9288 void aarch64_sync_64_to_32(CPUARMState *env)
9289 {
9290     int i;
9291     uint32_t mode = env->uncached_cpsr & CPSR_M;
9292 
9293     /* We can blanket copy X[0:7] to R[0:7] */
9294     for (i = 0; i < 8; i++) {
9295         env->regs[i] = env->xregs[i];
9296     }
9297 
9298     /*
9299      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9300      * Otherwise, we copy x8-x12 into the banked user regs.
9301      */
9302     if (mode == ARM_CPU_MODE_FIQ) {
9303         for (i = 8; i < 13; i++) {
9304             env->usr_regs[i - 8] = env->xregs[i];
9305         }
9306     } else {
9307         for (i = 8; i < 13; i++) {
9308             env->regs[i] = env->xregs[i];
9309         }
9310     }
9311 
9312     /*
9313      * Registers r13 & r14 depend on the current mode.
9314      * If we are in a given mode, we copy the corresponding x registers to r13
9315      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9316      * for the mode.
9317      */
9318     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9319         env->regs[13] = env->xregs[13];
9320         env->regs[14] = env->xregs[14];
9321     } else {
9322         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9323 
9324         /*
9325          * HYP is an exception in that it does not have its own banked r14 but
9326          * shares the USR r14
9327          */
9328         if (mode == ARM_CPU_MODE_HYP) {
9329             env->regs[14] = env->xregs[14];
9330         } else {
9331             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9332         }
9333     }
9334 
9335     if (mode == ARM_CPU_MODE_HYP) {
9336         env->regs[13] = env->xregs[15];
9337     } else {
9338         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9339     }
9340 
9341     if (mode == ARM_CPU_MODE_IRQ) {
9342         env->regs[14] = env->xregs[16];
9343         env->regs[13] = env->xregs[17];
9344     } else {
9345         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9346         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9347     }
9348 
9349     if (mode == ARM_CPU_MODE_SVC) {
9350         env->regs[14] = env->xregs[18];
9351         env->regs[13] = env->xregs[19];
9352     } else {
9353         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9354         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9355     }
9356 
9357     if (mode == ARM_CPU_MODE_ABT) {
9358         env->regs[14] = env->xregs[20];
9359         env->regs[13] = env->xregs[21];
9360     } else {
9361         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9362         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9363     }
9364 
9365     if (mode == ARM_CPU_MODE_UND) {
9366         env->regs[14] = env->xregs[22];
9367         env->regs[13] = env->xregs[23];
9368     } else {
9369         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9370         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9371     }
9372 
9373     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9374      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9375      * FIQ bank for r8-r14.
9376      */
9377     if (mode == ARM_CPU_MODE_FIQ) {
9378         for (i = 24; i < 31; i++) {
9379             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9380         }
9381     } else {
9382         for (i = 24; i < 29; i++) {
9383             env->fiq_regs[i - 24] = env->xregs[i];
9384         }
9385         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9386         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9387     }
9388 
9389     env->regs[15] = env->pc;
9390 }
9391 
9392 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9393                                    uint32_t mask, uint32_t offset,
9394                                    uint32_t newpc)
9395 {
9396     int new_el;
9397 
9398     /* Change the CPU state so as to actually take the exception. */
9399     switch_mode(env, new_mode);
9400 
9401     /*
9402      * For exceptions taken to AArch32 we must clear the SS bit in both
9403      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9404      */
9405     env->uncached_cpsr &= ~PSTATE_SS;
9406     env->spsr = cpsr_read(env);
9407     /* Clear IT bits.  */
9408     env->condexec_bits = 0;
9409     /* Switch to the new mode, and to the correct instruction set.  */
9410     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9411 
9412     /* This must be after mode switching. */
9413     new_el = arm_current_el(env);
9414 
9415     /* Set new mode endianness */
9416     env->uncached_cpsr &= ~CPSR_E;
9417     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9418         env->uncached_cpsr |= CPSR_E;
9419     }
9420     /* J and IL must always be cleared for exception entry */
9421     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9422     env->daif |= mask;
9423 
9424     if (new_mode == ARM_CPU_MODE_HYP) {
9425         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9426         env->elr_el[2] = env->regs[15];
9427     } else {
9428         /* CPSR.PAN is normally preserved preserved unless...  */
9429         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9430             switch (new_el) {
9431             case 3:
9432                 if (!arm_is_secure_below_el3(env)) {
9433                     /* ... the target is EL3, from non-secure state.  */
9434                     env->uncached_cpsr &= ~CPSR_PAN;
9435                     break;
9436                 }
9437                 /* ... the target is EL3, from secure state ... */
9438                 /* fall through */
9439             case 1:
9440                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9441                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9442                     env->uncached_cpsr |= CPSR_PAN;
9443                 }
9444                 break;
9445             }
9446         }
9447         /*
9448          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9449          * and we should just guard the thumb mode on V4
9450          */
9451         if (arm_feature(env, ARM_FEATURE_V4T)) {
9452             env->thumb =
9453                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9454         }
9455         env->regs[14] = env->regs[15] + offset;
9456     }
9457     env->regs[15] = newpc;
9458     arm_rebuild_hflags(env);
9459 }
9460 
9461 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9462 {
9463     /*
9464      * Handle exception entry to Hyp mode; this is sufficiently
9465      * different to entry to other AArch32 modes that we handle it
9466      * separately here.
9467      *
9468      * The vector table entry used is always the 0x14 Hyp mode entry point,
9469      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
9470      * The offset applied to the preferred return address is always zero
9471      * (see DDI0487C.a section G1.12.3).
9472      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9473      */
9474     uint32_t addr, mask;
9475     ARMCPU *cpu = ARM_CPU(cs);
9476     CPUARMState *env = &cpu->env;
9477 
9478     switch (cs->exception_index) {
9479     case EXCP_UDEF:
9480         addr = 0x04;
9481         break;
9482     case EXCP_SWI:
9483         addr = 0x14;
9484         break;
9485     case EXCP_BKPT:
9486         /* Fall through to prefetch abort.  */
9487     case EXCP_PREFETCH_ABORT:
9488         env->cp15.ifar_s = env->exception.vaddress;
9489         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9490                       (uint32_t)env->exception.vaddress);
9491         addr = 0x0c;
9492         break;
9493     case EXCP_DATA_ABORT:
9494         env->cp15.dfar_s = env->exception.vaddress;
9495         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9496                       (uint32_t)env->exception.vaddress);
9497         addr = 0x10;
9498         break;
9499     case EXCP_IRQ:
9500         addr = 0x18;
9501         break;
9502     case EXCP_FIQ:
9503         addr = 0x1c;
9504         break;
9505     case EXCP_HVC:
9506         addr = 0x08;
9507         break;
9508     case EXCP_HYP_TRAP:
9509         addr = 0x14;
9510         break;
9511     default:
9512         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9513     }
9514 
9515     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9516         if (!arm_feature(env, ARM_FEATURE_V8)) {
9517             /*
9518              * QEMU syndrome values are v8-style. v7 has the IL bit
9519              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9520              * If this is a v7 CPU, squash the IL bit in those cases.
9521              */
9522             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9523                 (cs->exception_index == EXCP_DATA_ABORT &&
9524                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9525                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9526                 env->exception.syndrome &= ~ARM_EL_IL;
9527             }
9528         }
9529         env->cp15.esr_el[2] = env->exception.syndrome;
9530     }
9531 
9532     if (arm_current_el(env) != 2 && addr < 0x14) {
9533         addr = 0x14;
9534     }
9535 
9536     mask = 0;
9537     if (!(env->cp15.scr_el3 & SCR_EA)) {
9538         mask |= CPSR_A;
9539     }
9540     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9541         mask |= CPSR_I;
9542     }
9543     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9544         mask |= CPSR_F;
9545     }
9546 
9547     addr += env->cp15.hvbar;
9548 
9549     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9550 }
9551 
9552 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9553 {
9554     ARMCPU *cpu = ARM_CPU(cs);
9555     CPUARMState *env = &cpu->env;
9556     uint32_t addr;
9557     uint32_t mask;
9558     int new_mode;
9559     uint32_t offset;
9560     uint32_t moe;
9561 
9562     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9563     switch (syn_get_ec(env->exception.syndrome)) {
9564     case EC_BREAKPOINT:
9565     case EC_BREAKPOINT_SAME_EL:
9566         moe = 1;
9567         break;
9568     case EC_WATCHPOINT:
9569     case EC_WATCHPOINT_SAME_EL:
9570         moe = 10;
9571         break;
9572     case EC_AA32_BKPT:
9573         moe = 3;
9574         break;
9575     case EC_VECTORCATCH:
9576         moe = 5;
9577         break;
9578     default:
9579         moe = 0;
9580         break;
9581     }
9582 
9583     if (moe) {
9584         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9585     }
9586 
9587     if (env->exception.target_el == 2) {
9588         arm_cpu_do_interrupt_aarch32_hyp(cs);
9589         return;
9590     }
9591 
9592     switch (cs->exception_index) {
9593     case EXCP_UDEF:
9594         new_mode = ARM_CPU_MODE_UND;
9595         addr = 0x04;
9596         mask = CPSR_I;
9597         if (env->thumb)
9598             offset = 2;
9599         else
9600             offset = 4;
9601         break;
9602     case EXCP_SWI:
9603         new_mode = ARM_CPU_MODE_SVC;
9604         addr = 0x08;
9605         mask = CPSR_I;
9606         /* The PC already points to the next instruction.  */
9607         offset = 0;
9608         break;
9609     case EXCP_BKPT:
9610         /* Fall through to prefetch abort.  */
9611     case EXCP_PREFETCH_ABORT:
9612         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9613         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9614         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9615                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9616         new_mode = ARM_CPU_MODE_ABT;
9617         addr = 0x0c;
9618         mask = CPSR_A | CPSR_I;
9619         offset = 4;
9620         break;
9621     case EXCP_DATA_ABORT:
9622         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9623         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9624         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9625                       env->exception.fsr,
9626                       (uint32_t)env->exception.vaddress);
9627         new_mode = ARM_CPU_MODE_ABT;
9628         addr = 0x10;
9629         mask = CPSR_A | CPSR_I;
9630         offset = 8;
9631         break;
9632     case EXCP_IRQ:
9633         new_mode = ARM_CPU_MODE_IRQ;
9634         addr = 0x18;
9635         /* Disable IRQ and imprecise data aborts.  */
9636         mask = CPSR_A | CPSR_I;
9637         offset = 4;
9638         if (env->cp15.scr_el3 & SCR_IRQ) {
9639             /* IRQ routed to monitor mode */
9640             new_mode = ARM_CPU_MODE_MON;
9641             mask |= CPSR_F;
9642         }
9643         break;
9644     case EXCP_FIQ:
9645         new_mode = ARM_CPU_MODE_FIQ;
9646         addr = 0x1c;
9647         /* Disable FIQ, IRQ and imprecise data aborts.  */
9648         mask = CPSR_A | CPSR_I | CPSR_F;
9649         if (env->cp15.scr_el3 & SCR_FIQ) {
9650             /* FIQ routed to monitor mode */
9651             new_mode = ARM_CPU_MODE_MON;
9652         }
9653         offset = 4;
9654         break;
9655     case EXCP_VIRQ:
9656         new_mode = ARM_CPU_MODE_IRQ;
9657         addr = 0x18;
9658         /* Disable IRQ and imprecise data aborts.  */
9659         mask = CPSR_A | CPSR_I;
9660         offset = 4;
9661         break;
9662     case EXCP_VFIQ:
9663         new_mode = ARM_CPU_MODE_FIQ;
9664         addr = 0x1c;
9665         /* Disable FIQ, IRQ and imprecise data aborts.  */
9666         mask = CPSR_A | CPSR_I | CPSR_F;
9667         offset = 4;
9668         break;
9669     case EXCP_SMC:
9670         new_mode = ARM_CPU_MODE_MON;
9671         addr = 0x08;
9672         mask = CPSR_A | CPSR_I | CPSR_F;
9673         offset = 0;
9674         break;
9675     default:
9676         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9677         return; /* Never happens.  Keep compiler happy.  */
9678     }
9679 
9680     if (new_mode == ARM_CPU_MODE_MON) {
9681         addr += env->cp15.mvbar;
9682     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9683         /* High vectors. When enabled, base address cannot be remapped. */
9684         addr += 0xffff0000;
9685     } else {
9686         /* ARM v7 architectures provide a vector base address register to remap
9687          * the interrupt vector table.
9688          * This register is only followed in non-monitor mode, and is banked.
9689          * Note: only bits 31:5 are valid.
9690          */
9691         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9692     }
9693 
9694     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9695         env->cp15.scr_el3 &= ~SCR_NS;
9696     }
9697 
9698     take_aarch32_exception(env, new_mode, mask, offset, addr);
9699 }
9700 
9701 static int aarch64_regnum(CPUARMState *env, int aarch32_reg)
9702 {
9703     /*
9704      * Return the register number of the AArch64 view of the AArch32
9705      * register @aarch32_reg. The CPUARMState CPSR is assumed to still
9706      * be that of the AArch32 mode the exception came from.
9707      */
9708     int mode = env->uncached_cpsr & CPSR_M;
9709 
9710     switch (aarch32_reg) {
9711     case 0 ... 7:
9712         return aarch32_reg;
9713     case 8 ... 12:
9714         return mode == ARM_CPU_MODE_FIQ ? aarch32_reg + 16 : aarch32_reg;
9715     case 13:
9716         switch (mode) {
9717         case ARM_CPU_MODE_USR:
9718         case ARM_CPU_MODE_SYS:
9719             return 13;
9720         case ARM_CPU_MODE_HYP:
9721             return 15;
9722         case ARM_CPU_MODE_IRQ:
9723             return 17;
9724         case ARM_CPU_MODE_SVC:
9725             return 19;
9726         case ARM_CPU_MODE_ABT:
9727             return 21;
9728         case ARM_CPU_MODE_UND:
9729             return 23;
9730         case ARM_CPU_MODE_FIQ:
9731             return 29;
9732         default:
9733             g_assert_not_reached();
9734         }
9735     case 14:
9736         switch (mode) {
9737         case ARM_CPU_MODE_USR:
9738         case ARM_CPU_MODE_SYS:
9739         case ARM_CPU_MODE_HYP:
9740             return 14;
9741         case ARM_CPU_MODE_IRQ:
9742             return 16;
9743         case ARM_CPU_MODE_SVC:
9744             return 18;
9745         case ARM_CPU_MODE_ABT:
9746             return 20;
9747         case ARM_CPU_MODE_UND:
9748             return 22;
9749         case ARM_CPU_MODE_FIQ:
9750             return 30;
9751         default:
9752             g_assert_not_reached();
9753         }
9754     case 15:
9755         return 31;
9756     default:
9757         g_assert_not_reached();
9758     }
9759 }
9760 
9761 /* Handle exception entry to a target EL which is using AArch64 */
9762 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
9763 {
9764     ARMCPU *cpu = ARM_CPU(cs);
9765     CPUARMState *env = &cpu->env;
9766     unsigned int new_el = env->exception.target_el;
9767     target_ulong addr = env->cp15.vbar_el[new_el];
9768     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
9769     unsigned int old_mode;
9770     unsigned int cur_el = arm_current_el(env);
9771     int rt;
9772 
9773     /*
9774      * Note that new_el can never be 0.  If cur_el is 0, then
9775      * el0_a64 is is_a64(), else el0_a64 is ignored.
9776      */
9777     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
9778 
9779     if (cur_el < new_el) {
9780         /* Entry vector offset depends on whether the implemented EL
9781          * immediately lower than the target level is using AArch32 or AArch64
9782          */
9783         bool is_aa64;
9784         uint64_t hcr;
9785 
9786         switch (new_el) {
9787         case 3:
9788             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
9789             break;
9790         case 2:
9791             hcr = arm_hcr_el2_eff(env);
9792             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
9793                 is_aa64 = (hcr & HCR_RW) != 0;
9794                 break;
9795             }
9796             /* fall through */
9797         case 1:
9798             is_aa64 = is_a64(env);
9799             break;
9800         default:
9801             g_assert_not_reached();
9802         }
9803 
9804         if (is_aa64) {
9805             addr += 0x400;
9806         } else {
9807             addr += 0x600;
9808         }
9809     } else if (pstate_read(env) & PSTATE_SP) {
9810         addr += 0x200;
9811     }
9812 
9813     switch (cs->exception_index) {
9814     case EXCP_PREFETCH_ABORT:
9815     case EXCP_DATA_ABORT:
9816         env->cp15.far_el[new_el] = env->exception.vaddress;
9817         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
9818                       env->cp15.far_el[new_el]);
9819         /* fall through */
9820     case EXCP_BKPT:
9821     case EXCP_UDEF:
9822     case EXCP_SWI:
9823     case EXCP_HVC:
9824     case EXCP_HYP_TRAP:
9825     case EXCP_SMC:
9826         switch (syn_get_ec(env->exception.syndrome)) {
9827         case EC_ADVSIMDFPACCESSTRAP:
9828             /*
9829              * QEMU internal FP/SIMD syndromes from AArch32 include the
9830              * TA and coproc fields which are only exposed if the exception
9831              * is taken to AArch32 Hyp mode. Mask them out to get a valid
9832              * AArch64 format syndrome.
9833              */
9834             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
9835             break;
9836         case EC_CP14RTTRAP:
9837         case EC_CP15RTTRAP:
9838         case EC_CP14DTTRAP:
9839             /*
9840              * For a trap on AArch32 MRC/MCR/LDC/STC the Rt field is currently
9841              * the raw register field from the insn; when taking this to
9842              * AArch64 we must convert it to the AArch64 view of the register
9843              * number. Notice that we read a 4-bit AArch32 register number and
9844              * write back a 5-bit AArch64 one.
9845              */
9846             rt = extract32(env->exception.syndrome, 5, 4);
9847             rt = aarch64_regnum(env, rt);
9848             env->exception.syndrome = deposit32(env->exception.syndrome,
9849                                                 5, 5, rt);
9850             break;
9851         case EC_CP15RRTTRAP:
9852         case EC_CP14RRTTRAP:
9853             /* Similarly for MRRC/MCRR traps for Rt and Rt2 fields */
9854             rt = extract32(env->exception.syndrome, 5, 4);
9855             rt = aarch64_regnum(env, rt);
9856             env->exception.syndrome = deposit32(env->exception.syndrome,
9857                                                 5, 5, rt);
9858             rt = extract32(env->exception.syndrome, 10, 4);
9859             rt = aarch64_regnum(env, rt);
9860             env->exception.syndrome = deposit32(env->exception.syndrome,
9861                                                 10, 5, rt);
9862             break;
9863         }
9864         env->cp15.esr_el[new_el] = env->exception.syndrome;
9865         break;
9866     case EXCP_IRQ:
9867     case EXCP_VIRQ:
9868         addr += 0x80;
9869         break;
9870     case EXCP_FIQ:
9871     case EXCP_VFIQ:
9872         addr += 0x100;
9873         break;
9874     default:
9875         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9876     }
9877 
9878     if (is_a64(env)) {
9879         old_mode = pstate_read(env);
9880         aarch64_save_sp(env, arm_current_el(env));
9881         env->elr_el[new_el] = env->pc;
9882     } else {
9883         old_mode = cpsr_read(env);
9884         env->elr_el[new_el] = env->regs[15];
9885 
9886         aarch64_sync_32_to_64(env);
9887 
9888         env->condexec_bits = 0;
9889     }
9890     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
9891 
9892     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
9893                   env->elr_el[new_el]);
9894 
9895     if (cpu_isar_feature(aa64_pan, cpu)) {
9896         /* The value of PSTATE.PAN is normally preserved, except when ... */
9897         new_mode |= old_mode & PSTATE_PAN;
9898         switch (new_el) {
9899         case 2:
9900             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
9901             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
9902                 != (HCR_E2H | HCR_TGE)) {
9903                 break;
9904             }
9905             /* fall through */
9906         case 1:
9907             /* ... the target is EL1 ... */
9908             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
9909             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
9910                 new_mode |= PSTATE_PAN;
9911             }
9912             break;
9913         }
9914     }
9915     if (cpu_isar_feature(aa64_mte, cpu)) {
9916         new_mode |= PSTATE_TCO;
9917     }
9918 
9919     pstate_write(env, PSTATE_DAIF | new_mode);
9920     env->aarch64 = 1;
9921     aarch64_restore_sp(env, new_el);
9922     helper_rebuild_hflags_a64(env, new_el);
9923 
9924     env->pc = addr;
9925 
9926     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
9927                   new_el, env->pc, pstate_read(env));
9928 }
9929 
9930 /*
9931  * Do semihosting call and set the appropriate return value. All the
9932  * permission and validity checks have been done at translate time.
9933  *
9934  * We only see semihosting exceptions in TCG only as they are not
9935  * trapped to the hypervisor in KVM.
9936  */
9937 #ifdef CONFIG_TCG
9938 static void handle_semihosting(CPUState *cs)
9939 {
9940     ARMCPU *cpu = ARM_CPU(cs);
9941     CPUARMState *env = &cpu->env;
9942 
9943     if (is_a64(env)) {
9944         qemu_log_mask(CPU_LOG_INT,
9945                       "...handling as semihosting call 0x%" PRIx64 "\n",
9946                       env->xregs[0]);
9947         env->xregs[0] = do_common_semihosting(cs);
9948         env->pc += 4;
9949     } else {
9950         qemu_log_mask(CPU_LOG_INT,
9951                       "...handling as semihosting call 0x%x\n",
9952                       env->regs[0]);
9953         env->regs[0] = do_common_semihosting(cs);
9954         env->regs[15] += env->thumb ? 2 : 4;
9955     }
9956 }
9957 #endif
9958 
9959 /* Handle a CPU exception for A and R profile CPUs.
9960  * Do any appropriate logging, handle PSCI calls, and then hand off
9961  * to the AArch64-entry or AArch32-entry function depending on the
9962  * target exception level's register width.
9963  */
9964 void arm_cpu_do_interrupt(CPUState *cs)
9965 {
9966     ARMCPU *cpu = ARM_CPU(cs);
9967     CPUARMState *env = &cpu->env;
9968     unsigned int new_el = env->exception.target_el;
9969 
9970     assert(!arm_feature(env, ARM_FEATURE_M));
9971 
9972     arm_log_exception(cs->exception_index);
9973     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
9974                   new_el);
9975     if (qemu_loglevel_mask(CPU_LOG_INT)
9976         && !excp_is_internal(cs->exception_index)) {
9977         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
9978                       syn_get_ec(env->exception.syndrome),
9979                       env->exception.syndrome);
9980     }
9981 
9982     if (arm_is_psci_call(cpu, cs->exception_index)) {
9983         arm_handle_psci_call(cpu);
9984         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
9985         return;
9986     }
9987 
9988     /*
9989      * Semihosting semantics depend on the register width of the code
9990      * that caused the exception, not the target exception level, so
9991      * must be handled here.
9992      */
9993 #ifdef CONFIG_TCG
9994     if (cs->exception_index == EXCP_SEMIHOST) {
9995         handle_semihosting(cs);
9996         return;
9997     }
9998 #endif
9999 
10000     /* Hooks may change global state so BQL should be held, also the
10001      * BQL needs to be held for any modification of
10002      * cs->interrupt_request.
10003      */
10004     g_assert(qemu_mutex_iothread_locked());
10005 
10006     arm_call_pre_el_change_hook(cpu);
10007 
10008     assert(!excp_is_internal(cs->exception_index));
10009     if (arm_el_is_aa64(env, new_el)) {
10010         arm_cpu_do_interrupt_aarch64(cs);
10011     } else {
10012         arm_cpu_do_interrupt_aarch32(cs);
10013     }
10014 
10015     arm_call_el_change_hook(cpu);
10016 
10017     if (!kvm_enabled()) {
10018         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10019     }
10020 }
10021 #endif /* !CONFIG_USER_ONLY */
10022 
10023 uint64_t arm_sctlr(CPUARMState *env, int el)
10024 {
10025     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
10026     if (el == 0) {
10027         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
10028         el = (mmu_idx == ARMMMUIdx_E20_0 || mmu_idx == ARMMMUIdx_SE20_0)
10029              ? 2 : 1;
10030     }
10031     return env->cp15.sctlr_el[el];
10032 }
10033 
10034 /* Return the SCTLR value which controls this address translation regime */
10035 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10036 {
10037     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10038 }
10039 
10040 #ifndef CONFIG_USER_ONLY
10041 
10042 /* Return true if the specified stage of address translation is disabled */
10043 static inline bool regime_translation_disabled(CPUARMState *env,
10044                                                ARMMMUIdx mmu_idx)
10045 {
10046     uint64_t hcr_el2;
10047 
10048     if (arm_feature(env, ARM_FEATURE_M)) {
10049         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10050                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10051         case R_V7M_MPU_CTRL_ENABLE_MASK:
10052             /* Enabled, but not for HardFault and NMI */
10053             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10054         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10055             /* Enabled for all cases */
10056             return false;
10057         case 0:
10058         default:
10059             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10060              * we warned about that in armv7m_nvic.c when the guest set it.
10061              */
10062             return true;
10063         }
10064     }
10065 
10066     hcr_el2 = arm_hcr_el2_eff(env);
10067 
10068     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10069         /* HCR.DC means HCR.VM behaves as 1 */
10070         return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10071     }
10072 
10073     if (hcr_el2 & HCR_TGE) {
10074         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10075         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10076             return true;
10077         }
10078     }
10079 
10080     if ((hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
10081         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10082         return true;
10083     }
10084 
10085     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10086 }
10087 
10088 static inline bool regime_translation_big_endian(CPUARMState *env,
10089                                                  ARMMMUIdx mmu_idx)
10090 {
10091     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10092 }
10093 
10094 /* Return the TTBR associated with this translation regime */
10095 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10096                                    int ttbrn)
10097 {
10098     if (mmu_idx == ARMMMUIdx_Stage2) {
10099         return env->cp15.vttbr_el2;
10100     }
10101     if (mmu_idx == ARMMMUIdx_Stage2_S) {
10102         return env->cp15.vsttbr_el2;
10103     }
10104     if (ttbrn == 0) {
10105         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10106     } else {
10107         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10108     }
10109 }
10110 
10111 #endif /* !CONFIG_USER_ONLY */
10112 
10113 /* Convert a possible stage1+2 MMU index into the appropriate
10114  * stage 1 MMU index
10115  */
10116 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10117 {
10118     switch (mmu_idx) {
10119     case ARMMMUIdx_SE10_0:
10120         return ARMMMUIdx_Stage1_SE0;
10121     case ARMMMUIdx_SE10_1:
10122         return ARMMMUIdx_Stage1_SE1;
10123     case ARMMMUIdx_SE10_1_PAN:
10124         return ARMMMUIdx_Stage1_SE1_PAN;
10125     case ARMMMUIdx_E10_0:
10126         return ARMMMUIdx_Stage1_E0;
10127     case ARMMMUIdx_E10_1:
10128         return ARMMMUIdx_Stage1_E1;
10129     case ARMMMUIdx_E10_1_PAN:
10130         return ARMMMUIdx_Stage1_E1_PAN;
10131     default:
10132         return mmu_idx;
10133     }
10134 }
10135 
10136 /* Return true if the translation regime is using LPAE format page tables */
10137 static inline bool regime_using_lpae_format(CPUARMState *env,
10138                                             ARMMMUIdx mmu_idx)
10139 {
10140     int el = regime_el(env, mmu_idx);
10141     if (el == 2 || arm_el_is_aa64(env, el)) {
10142         return true;
10143     }
10144     if (arm_feature(env, ARM_FEATURE_LPAE)
10145         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10146         return true;
10147     }
10148     return false;
10149 }
10150 
10151 /* Returns true if the stage 1 translation regime is using LPAE format page
10152  * tables. Used when raising alignment exceptions, whose FSR changes depending
10153  * on whether the long or short descriptor format is in use. */
10154 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10155 {
10156     mmu_idx = stage_1_mmu_idx(mmu_idx);
10157 
10158     return regime_using_lpae_format(env, mmu_idx);
10159 }
10160 
10161 #ifndef CONFIG_USER_ONLY
10162 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10163 {
10164     switch (mmu_idx) {
10165     case ARMMMUIdx_SE10_0:
10166     case ARMMMUIdx_E20_0:
10167     case ARMMMUIdx_SE20_0:
10168     case ARMMMUIdx_Stage1_E0:
10169     case ARMMMUIdx_Stage1_SE0:
10170     case ARMMMUIdx_MUser:
10171     case ARMMMUIdx_MSUser:
10172     case ARMMMUIdx_MUserNegPri:
10173     case ARMMMUIdx_MSUserNegPri:
10174         return true;
10175     default:
10176         return false;
10177     case ARMMMUIdx_E10_0:
10178     case ARMMMUIdx_E10_1:
10179     case ARMMMUIdx_E10_1_PAN:
10180         g_assert_not_reached();
10181     }
10182 }
10183 
10184 /* Translate section/page access permissions to page
10185  * R/W protection flags
10186  *
10187  * @env:         CPUARMState
10188  * @mmu_idx:     MMU index indicating required translation regime
10189  * @ap:          The 3-bit access permissions (AP[2:0])
10190  * @domain_prot: The 2-bit domain access permissions
10191  */
10192 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10193                                 int ap, int domain_prot)
10194 {
10195     bool is_user = regime_is_user(env, mmu_idx);
10196 
10197     if (domain_prot == 3) {
10198         return PAGE_READ | PAGE_WRITE;
10199     }
10200 
10201     switch (ap) {
10202     case 0:
10203         if (arm_feature(env, ARM_FEATURE_V7)) {
10204             return 0;
10205         }
10206         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10207         case SCTLR_S:
10208             return is_user ? 0 : PAGE_READ;
10209         case SCTLR_R:
10210             return PAGE_READ;
10211         default:
10212             return 0;
10213         }
10214     case 1:
10215         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10216     case 2:
10217         if (is_user) {
10218             return PAGE_READ;
10219         } else {
10220             return PAGE_READ | PAGE_WRITE;
10221         }
10222     case 3:
10223         return PAGE_READ | PAGE_WRITE;
10224     case 4: /* Reserved.  */
10225         return 0;
10226     case 5:
10227         return is_user ? 0 : PAGE_READ;
10228     case 6:
10229         return PAGE_READ;
10230     case 7:
10231         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10232             return 0;
10233         }
10234         return PAGE_READ;
10235     default:
10236         g_assert_not_reached();
10237     }
10238 }
10239 
10240 /* Translate section/page access permissions to page
10241  * R/W protection flags.
10242  *
10243  * @ap:      The 2-bit simple AP (AP[2:1])
10244  * @is_user: TRUE if accessing from PL0
10245  */
10246 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10247 {
10248     switch (ap) {
10249     case 0:
10250         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10251     case 1:
10252         return PAGE_READ | PAGE_WRITE;
10253     case 2:
10254         return is_user ? 0 : PAGE_READ;
10255     case 3:
10256         return PAGE_READ;
10257     default:
10258         g_assert_not_reached();
10259     }
10260 }
10261 
10262 static inline int
10263 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10264 {
10265     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10266 }
10267 
10268 /* Translate S2 section/page access permissions to protection flags
10269  *
10270  * @env:     CPUARMState
10271  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10272  * @xn:      XN (execute-never) bits
10273  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
10274  */
10275 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
10276 {
10277     int prot = 0;
10278 
10279     if (s2ap & 1) {
10280         prot |= PAGE_READ;
10281     }
10282     if (s2ap & 2) {
10283         prot |= PAGE_WRITE;
10284     }
10285 
10286     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
10287         switch (xn) {
10288         case 0:
10289             prot |= PAGE_EXEC;
10290             break;
10291         case 1:
10292             if (s1_is_el0) {
10293                 prot |= PAGE_EXEC;
10294             }
10295             break;
10296         case 2:
10297             break;
10298         case 3:
10299             if (!s1_is_el0) {
10300                 prot |= PAGE_EXEC;
10301             }
10302             break;
10303         default:
10304             g_assert_not_reached();
10305         }
10306     } else {
10307         if (!extract32(xn, 1, 1)) {
10308             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10309                 prot |= PAGE_EXEC;
10310             }
10311         }
10312     }
10313     return prot;
10314 }
10315 
10316 /* Translate section/page access permissions to protection flags
10317  *
10318  * @env:     CPUARMState
10319  * @mmu_idx: MMU index indicating required translation regime
10320  * @is_aa64: TRUE if AArch64
10321  * @ap:      The 2-bit simple AP (AP[2:1])
10322  * @ns:      NS (non-secure) bit
10323  * @xn:      XN (execute-never) bit
10324  * @pxn:     PXN (privileged execute-never) bit
10325  */
10326 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10327                       int ap, int ns, int xn, int pxn)
10328 {
10329     bool is_user = regime_is_user(env, mmu_idx);
10330     int prot_rw, user_rw;
10331     bool have_wxn;
10332     int wxn = 0;
10333 
10334     assert(mmu_idx != ARMMMUIdx_Stage2);
10335     assert(mmu_idx != ARMMMUIdx_Stage2_S);
10336 
10337     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10338     if (is_user) {
10339         prot_rw = user_rw;
10340     } else {
10341         if (user_rw && regime_is_pan(env, mmu_idx)) {
10342             /* PAN forbids data accesses but doesn't affect insn fetch */
10343             prot_rw = 0;
10344         } else {
10345             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10346         }
10347     }
10348 
10349     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10350         return prot_rw;
10351     }
10352 
10353     /* TODO have_wxn should be replaced with
10354      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10355      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10356      * compatible processors have EL2, which is required for [U]WXN.
10357      */
10358     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10359 
10360     if (have_wxn) {
10361         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10362     }
10363 
10364     if (is_aa64) {
10365         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10366             xn = pxn || (user_rw & PAGE_WRITE);
10367         }
10368     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10369         switch (regime_el(env, mmu_idx)) {
10370         case 1:
10371         case 3:
10372             if (is_user) {
10373                 xn = xn || !(user_rw & PAGE_READ);
10374             } else {
10375                 int uwxn = 0;
10376                 if (have_wxn) {
10377                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10378                 }
10379                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10380                      (uwxn && (user_rw & PAGE_WRITE));
10381             }
10382             break;
10383         case 2:
10384             break;
10385         }
10386     } else {
10387         xn = wxn = 0;
10388     }
10389 
10390     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10391         return prot_rw;
10392     }
10393     return prot_rw | PAGE_EXEC;
10394 }
10395 
10396 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10397                                      uint32_t *table, uint32_t address)
10398 {
10399     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10400     TCR *tcr = regime_tcr(env, mmu_idx);
10401 
10402     if (address & tcr->mask) {
10403         if (tcr->raw_tcr & TTBCR_PD1) {
10404             /* Translation table walk disabled for TTBR1 */
10405             return false;
10406         }
10407         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10408     } else {
10409         if (tcr->raw_tcr & TTBCR_PD0) {
10410             /* Translation table walk disabled for TTBR0 */
10411             return false;
10412         }
10413         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10414     }
10415     *table |= (address >> 18) & 0x3ffc;
10416     return true;
10417 }
10418 
10419 /* Translate a S1 pagetable walk through S2 if needed.  */
10420 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10421                                hwaddr addr, bool *is_secure,
10422                                ARMMMUFaultInfo *fi)
10423 {
10424     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10425         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10426         target_ulong s2size;
10427         hwaddr s2pa;
10428         int s2prot;
10429         int ret;
10430         ARMMMUIdx s2_mmu_idx = *is_secure ? ARMMMUIdx_Stage2_S
10431                                           : ARMMMUIdx_Stage2;
10432         ARMCacheAttrs cacheattrs = {};
10433         MemTxAttrs txattrs = {};
10434 
10435         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, s2_mmu_idx, false,
10436                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10437                                  &cacheattrs);
10438         if (ret) {
10439             assert(fi->type != ARMFault_None);
10440             fi->s2addr = addr;
10441             fi->stage2 = true;
10442             fi->s1ptw = true;
10443             fi->s1ns = !*is_secure;
10444             return ~0;
10445         }
10446         if ((arm_hcr_el2_eff(env) & HCR_PTW) &&
10447             (cacheattrs.attrs & 0xf0) == 0) {
10448             /*
10449              * PTW set and S1 walk touched S2 Device memory:
10450              * generate Permission fault.
10451              */
10452             fi->type = ARMFault_Permission;
10453             fi->s2addr = addr;
10454             fi->stage2 = true;
10455             fi->s1ptw = true;
10456             fi->s1ns = !*is_secure;
10457             return ~0;
10458         }
10459 
10460         if (arm_is_secure_below_el3(env)) {
10461             /* Check if page table walk is to secure or non-secure PA space. */
10462             if (*is_secure) {
10463                 *is_secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
10464             } else {
10465                 *is_secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
10466             }
10467         } else {
10468             assert(!*is_secure);
10469         }
10470 
10471         addr = s2pa;
10472     }
10473     return addr;
10474 }
10475 
10476 /* All loads done in the course of a page table walk go through here. */
10477 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10478                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10479 {
10480     ARMCPU *cpu = ARM_CPU(cs);
10481     CPUARMState *env = &cpu->env;
10482     MemTxAttrs attrs = {};
10483     MemTxResult result = MEMTX_OK;
10484     AddressSpace *as;
10485     uint32_t data;
10486 
10487     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10488     attrs.secure = is_secure;
10489     as = arm_addressspace(cs, attrs);
10490     if (fi->s1ptw) {
10491         return 0;
10492     }
10493     if (regime_translation_big_endian(env, mmu_idx)) {
10494         data = address_space_ldl_be(as, addr, attrs, &result);
10495     } else {
10496         data = address_space_ldl_le(as, addr, attrs, &result);
10497     }
10498     if (result == MEMTX_OK) {
10499         return data;
10500     }
10501     fi->type = ARMFault_SyncExternalOnWalk;
10502     fi->ea = arm_extabort_type(result);
10503     return 0;
10504 }
10505 
10506 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10507                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10508 {
10509     ARMCPU *cpu = ARM_CPU(cs);
10510     CPUARMState *env = &cpu->env;
10511     MemTxAttrs attrs = {};
10512     MemTxResult result = MEMTX_OK;
10513     AddressSpace *as;
10514     uint64_t data;
10515 
10516     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10517     attrs.secure = is_secure;
10518     as = arm_addressspace(cs, attrs);
10519     if (fi->s1ptw) {
10520         return 0;
10521     }
10522     if (regime_translation_big_endian(env, mmu_idx)) {
10523         data = address_space_ldq_be(as, addr, attrs, &result);
10524     } else {
10525         data = address_space_ldq_le(as, addr, attrs, &result);
10526     }
10527     if (result == MEMTX_OK) {
10528         return data;
10529     }
10530     fi->type = ARMFault_SyncExternalOnWalk;
10531     fi->ea = arm_extabort_type(result);
10532     return 0;
10533 }
10534 
10535 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10536                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10537                              hwaddr *phys_ptr, int *prot,
10538                              target_ulong *page_size,
10539                              ARMMMUFaultInfo *fi)
10540 {
10541     CPUState *cs = env_cpu(env);
10542     int level = 1;
10543     uint32_t table;
10544     uint32_t desc;
10545     int type;
10546     int ap;
10547     int domain = 0;
10548     int domain_prot;
10549     hwaddr phys_addr;
10550     uint32_t dacr;
10551 
10552     /* Pagetable walk.  */
10553     /* Lookup l1 descriptor.  */
10554     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10555         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10556         fi->type = ARMFault_Translation;
10557         goto do_fault;
10558     }
10559     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10560                        mmu_idx, fi);
10561     if (fi->type != ARMFault_None) {
10562         goto do_fault;
10563     }
10564     type = (desc & 3);
10565     domain = (desc >> 5) & 0x0f;
10566     if (regime_el(env, mmu_idx) == 1) {
10567         dacr = env->cp15.dacr_ns;
10568     } else {
10569         dacr = env->cp15.dacr_s;
10570     }
10571     domain_prot = (dacr >> (domain * 2)) & 3;
10572     if (type == 0) {
10573         /* Section translation fault.  */
10574         fi->type = ARMFault_Translation;
10575         goto do_fault;
10576     }
10577     if (type != 2) {
10578         level = 2;
10579     }
10580     if (domain_prot == 0 || domain_prot == 2) {
10581         fi->type = ARMFault_Domain;
10582         goto do_fault;
10583     }
10584     if (type == 2) {
10585         /* 1Mb section.  */
10586         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10587         ap = (desc >> 10) & 3;
10588         *page_size = 1024 * 1024;
10589     } else {
10590         /* Lookup l2 entry.  */
10591         if (type == 1) {
10592             /* Coarse pagetable.  */
10593             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10594         } else {
10595             /* Fine pagetable.  */
10596             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10597         }
10598         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10599                            mmu_idx, fi);
10600         if (fi->type != ARMFault_None) {
10601             goto do_fault;
10602         }
10603         switch (desc & 3) {
10604         case 0: /* Page translation fault.  */
10605             fi->type = ARMFault_Translation;
10606             goto do_fault;
10607         case 1: /* 64k page.  */
10608             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10609             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10610             *page_size = 0x10000;
10611             break;
10612         case 2: /* 4k page.  */
10613             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10614             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10615             *page_size = 0x1000;
10616             break;
10617         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10618             if (type == 1) {
10619                 /* ARMv6/XScale extended small page format */
10620                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10621                     || arm_feature(env, ARM_FEATURE_V6)) {
10622                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10623                     *page_size = 0x1000;
10624                 } else {
10625                     /* UNPREDICTABLE in ARMv5; we choose to take a
10626                      * page translation fault.
10627                      */
10628                     fi->type = ARMFault_Translation;
10629                     goto do_fault;
10630                 }
10631             } else {
10632                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10633                 *page_size = 0x400;
10634             }
10635             ap = (desc >> 4) & 3;
10636             break;
10637         default:
10638             /* Never happens, but compiler isn't smart enough to tell.  */
10639             abort();
10640         }
10641     }
10642     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10643     *prot |= *prot ? PAGE_EXEC : 0;
10644     if (!(*prot & (1 << access_type))) {
10645         /* Access permission fault.  */
10646         fi->type = ARMFault_Permission;
10647         goto do_fault;
10648     }
10649     *phys_ptr = phys_addr;
10650     return false;
10651 do_fault:
10652     fi->domain = domain;
10653     fi->level = level;
10654     return true;
10655 }
10656 
10657 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10658                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10659                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10660                              target_ulong *page_size, ARMMMUFaultInfo *fi)
10661 {
10662     CPUState *cs = env_cpu(env);
10663     ARMCPU *cpu = env_archcpu(env);
10664     int level = 1;
10665     uint32_t table;
10666     uint32_t desc;
10667     uint32_t xn;
10668     uint32_t pxn = 0;
10669     int type;
10670     int ap;
10671     int domain = 0;
10672     int domain_prot;
10673     hwaddr phys_addr;
10674     uint32_t dacr;
10675     bool ns;
10676 
10677     /* Pagetable walk.  */
10678     /* Lookup l1 descriptor.  */
10679     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10680         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10681         fi->type = ARMFault_Translation;
10682         goto do_fault;
10683     }
10684     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10685                        mmu_idx, fi);
10686     if (fi->type != ARMFault_None) {
10687         goto do_fault;
10688     }
10689     type = (desc & 3);
10690     if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
10691         /* Section translation fault, or attempt to use the encoding
10692          * which is Reserved on implementations without PXN.
10693          */
10694         fi->type = ARMFault_Translation;
10695         goto do_fault;
10696     }
10697     if ((type == 1) || !(desc & (1 << 18))) {
10698         /* Page or Section.  */
10699         domain = (desc >> 5) & 0x0f;
10700     }
10701     if (regime_el(env, mmu_idx) == 1) {
10702         dacr = env->cp15.dacr_ns;
10703     } else {
10704         dacr = env->cp15.dacr_s;
10705     }
10706     if (type == 1) {
10707         level = 2;
10708     }
10709     domain_prot = (dacr >> (domain * 2)) & 3;
10710     if (domain_prot == 0 || domain_prot == 2) {
10711         /* Section or Page domain fault */
10712         fi->type = ARMFault_Domain;
10713         goto do_fault;
10714     }
10715     if (type != 1) {
10716         if (desc & (1 << 18)) {
10717             /* Supersection.  */
10718             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
10719             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
10720             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
10721             *page_size = 0x1000000;
10722         } else {
10723             /* Section.  */
10724             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10725             *page_size = 0x100000;
10726         }
10727         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
10728         xn = desc & (1 << 4);
10729         pxn = desc & 1;
10730         ns = extract32(desc, 19, 1);
10731     } else {
10732         if (cpu_isar_feature(aa32_pxn, cpu)) {
10733             pxn = (desc >> 2) & 1;
10734         }
10735         ns = extract32(desc, 3, 1);
10736         /* Lookup l2 entry.  */
10737         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10738         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10739                            mmu_idx, fi);
10740         if (fi->type != ARMFault_None) {
10741             goto do_fault;
10742         }
10743         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
10744         switch (desc & 3) {
10745         case 0: /* Page translation fault.  */
10746             fi->type = ARMFault_Translation;
10747             goto do_fault;
10748         case 1: /* 64k page.  */
10749             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10750             xn = desc & (1 << 15);
10751             *page_size = 0x10000;
10752             break;
10753         case 2: case 3: /* 4k page.  */
10754             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10755             xn = desc & 1;
10756             *page_size = 0x1000;
10757             break;
10758         default:
10759             /* Never happens, but compiler isn't smart enough to tell.  */
10760             abort();
10761         }
10762     }
10763     if (domain_prot == 3) {
10764         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10765     } else {
10766         if (pxn && !regime_is_user(env, mmu_idx)) {
10767             xn = 1;
10768         }
10769         if (xn && access_type == MMU_INST_FETCH) {
10770             fi->type = ARMFault_Permission;
10771             goto do_fault;
10772         }
10773 
10774         if (arm_feature(env, ARM_FEATURE_V6K) &&
10775                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
10776             /* The simplified model uses AP[0] as an access control bit.  */
10777             if ((ap & 1) == 0) {
10778                 /* Access flag fault.  */
10779                 fi->type = ARMFault_AccessFlag;
10780                 goto do_fault;
10781             }
10782             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
10783         } else {
10784             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10785         }
10786         if (*prot && !xn) {
10787             *prot |= PAGE_EXEC;
10788         }
10789         if (!(*prot & (1 << access_type))) {
10790             /* Access permission fault.  */
10791             fi->type = ARMFault_Permission;
10792             goto do_fault;
10793         }
10794     }
10795     if (ns) {
10796         /* The NS bit will (as required by the architecture) have no effect if
10797          * the CPU doesn't support TZ or this is a non-secure translation
10798          * regime, because the attribute will already be non-secure.
10799          */
10800         attrs->secure = false;
10801     }
10802     *phys_ptr = phys_addr;
10803     return false;
10804 do_fault:
10805     fi->domain = domain;
10806     fi->level = level;
10807     return true;
10808 }
10809 
10810 /*
10811  * check_s2_mmu_setup
10812  * @cpu:        ARMCPU
10813  * @is_aa64:    True if the translation regime is in AArch64 state
10814  * @startlevel: Suggested starting level
10815  * @inputsize:  Bitsize of IPAs
10816  * @stride:     Page-table stride (See the ARM ARM)
10817  *
10818  * Returns true if the suggested S2 translation parameters are OK and
10819  * false otherwise.
10820  */
10821 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
10822                                int inputsize, int stride)
10823 {
10824     const int grainsize = stride + 3;
10825     int startsizecheck;
10826 
10827     /* Negative levels are never allowed.  */
10828     if (level < 0) {
10829         return false;
10830     }
10831 
10832     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
10833     if (startsizecheck < 1 || startsizecheck > stride + 4) {
10834         return false;
10835     }
10836 
10837     if (is_aa64) {
10838         CPUARMState *env = &cpu->env;
10839         unsigned int pamax = arm_pamax(cpu);
10840 
10841         switch (stride) {
10842         case 13: /* 64KB Pages.  */
10843             if (level == 0 || (level == 1 && pamax <= 42)) {
10844                 return false;
10845             }
10846             break;
10847         case 11: /* 16KB Pages.  */
10848             if (level == 0 || (level == 1 && pamax <= 40)) {
10849                 return false;
10850             }
10851             break;
10852         case 9: /* 4KB Pages.  */
10853             if (level == 0 && pamax <= 42) {
10854                 return false;
10855             }
10856             break;
10857         default:
10858             g_assert_not_reached();
10859         }
10860 
10861         /* Inputsize checks.  */
10862         if (inputsize > pamax &&
10863             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
10864             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
10865             return false;
10866         }
10867     } else {
10868         /* AArch32 only supports 4KB pages. Assert on that.  */
10869         assert(stride == 9);
10870 
10871         if (level == 0) {
10872             return false;
10873         }
10874     }
10875     return true;
10876 }
10877 
10878 /* Translate from the 4-bit stage 2 representation of
10879  * memory attributes (without cache-allocation hints) to
10880  * the 8-bit representation of the stage 1 MAIR registers
10881  * (which includes allocation hints).
10882  *
10883  * ref: shared/translation/attrs/S2AttrDecode()
10884  *      .../S2ConvertAttrsHints()
10885  */
10886 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
10887 {
10888     uint8_t hiattr = extract32(s2attrs, 2, 2);
10889     uint8_t loattr = extract32(s2attrs, 0, 2);
10890     uint8_t hihint = 0, lohint = 0;
10891 
10892     if (hiattr != 0) { /* normal memory */
10893         if (arm_hcr_el2_eff(env) & HCR_CD) { /* cache disabled */
10894             hiattr = loattr = 1; /* non-cacheable */
10895         } else {
10896             if (hiattr != 1) { /* Write-through or write-back */
10897                 hihint = 3; /* RW allocate */
10898             }
10899             if (loattr != 1) { /* Write-through or write-back */
10900                 lohint = 3; /* RW allocate */
10901             }
10902         }
10903     }
10904 
10905     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
10906 }
10907 #endif /* !CONFIG_USER_ONLY */
10908 
10909 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
10910 {
10911     if (regime_has_2_ranges(mmu_idx)) {
10912         return extract64(tcr, 37, 2);
10913     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10914         return 0; /* VTCR_EL2 */
10915     } else {
10916         /* Replicate the single TBI bit so we always have 2 bits.  */
10917         return extract32(tcr, 20, 1) * 3;
10918     }
10919 }
10920 
10921 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
10922 {
10923     if (regime_has_2_ranges(mmu_idx)) {
10924         return extract64(tcr, 51, 2);
10925     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10926         return 0; /* VTCR_EL2 */
10927     } else {
10928         /* Replicate the single TBID bit so we always have 2 bits.  */
10929         return extract32(tcr, 29, 1) * 3;
10930     }
10931 }
10932 
10933 static int aa64_va_parameter_tcma(uint64_t tcr, ARMMMUIdx mmu_idx)
10934 {
10935     if (regime_has_2_ranges(mmu_idx)) {
10936         return extract64(tcr, 57, 2);
10937     } else {
10938         /* Replicate the single TCMA bit so we always have 2 bits.  */
10939         return extract32(tcr, 30, 1) * 3;
10940     }
10941 }
10942 
10943 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
10944                                    ARMMMUIdx mmu_idx, bool data)
10945 {
10946     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
10947     bool epd, hpd, using16k, using64k;
10948     int select, tsz, tbi, max_tsz;
10949 
10950     if (!regime_has_2_ranges(mmu_idx)) {
10951         select = 0;
10952         tsz = extract32(tcr, 0, 6);
10953         using64k = extract32(tcr, 14, 1);
10954         using16k = extract32(tcr, 15, 1);
10955         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10956             /* VTCR_EL2 */
10957             hpd = false;
10958         } else {
10959             hpd = extract32(tcr, 24, 1);
10960         }
10961         epd = false;
10962     } else {
10963         /*
10964          * Bit 55 is always between the two regions, and is canonical for
10965          * determining if address tagging is enabled.
10966          */
10967         select = extract64(va, 55, 1);
10968         if (!select) {
10969             tsz = extract32(tcr, 0, 6);
10970             epd = extract32(tcr, 7, 1);
10971             using64k = extract32(tcr, 14, 1);
10972             using16k = extract32(tcr, 15, 1);
10973             hpd = extract64(tcr, 41, 1);
10974         } else {
10975             int tg = extract32(tcr, 30, 2);
10976             using16k = tg == 1;
10977             using64k = tg == 3;
10978             tsz = extract32(tcr, 16, 6);
10979             epd = extract32(tcr, 23, 1);
10980             hpd = extract64(tcr, 42, 1);
10981         }
10982     }
10983 
10984     if (cpu_isar_feature(aa64_st, env_archcpu(env))) {
10985         max_tsz = 48 - using64k;
10986     } else {
10987         max_tsz = 39;
10988     }
10989 
10990     tsz = MIN(tsz, max_tsz);
10991     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
10992 
10993     /* Present TBI as a composite with TBID.  */
10994     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
10995     if (!data) {
10996         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
10997     }
10998     tbi = (tbi >> select) & 1;
10999 
11000     return (ARMVAParameters) {
11001         .tsz = tsz,
11002         .select = select,
11003         .tbi = tbi,
11004         .epd = epd,
11005         .hpd = hpd,
11006         .using16k = using16k,
11007         .using64k = using64k,
11008     };
11009 }
11010 
11011 #ifndef CONFIG_USER_ONLY
11012 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11013                                           ARMMMUIdx mmu_idx)
11014 {
11015     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11016     uint32_t el = regime_el(env, mmu_idx);
11017     int select, tsz;
11018     bool epd, hpd;
11019 
11020     assert(mmu_idx != ARMMMUIdx_Stage2_S);
11021 
11022     if (mmu_idx == ARMMMUIdx_Stage2) {
11023         /* VTCR */
11024         bool sext = extract32(tcr, 4, 1);
11025         bool sign = extract32(tcr, 3, 1);
11026 
11027         /*
11028          * If the sign-extend bit is not the same as t0sz[3], the result
11029          * is unpredictable. Flag this as a guest error.
11030          */
11031         if (sign != sext) {
11032             qemu_log_mask(LOG_GUEST_ERROR,
11033                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11034         }
11035         tsz = sextract32(tcr, 0, 4) + 8;
11036         select = 0;
11037         hpd = false;
11038         epd = false;
11039     } else if (el == 2) {
11040         /* HTCR */
11041         tsz = extract32(tcr, 0, 3);
11042         select = 0;
11043         hpd = extract64(tcr, 24, 1);
11044         epd = false;
11045     } else {
11046         int t0sz = extract32(tcr, 0, 3);
11047         int t1sz = extract32(tcr, 16, 3);
11048 
11049         if (t1sz == 0) {
11050             select = va > (0xffffffffu >> t0sz);
11051         } else {
11052             /* Note that we will detect errors later.  */
11053             select = va >= ~(0xffffffffu >> t1sz);
11054         }
11055         if (!select) {
11056             tsz = t0sz;
11057             epd = extract32(tcr, 7, 1);
11058             hpd = extract64(tcr, 41, 1);
11059         } else {
11060             tsz = t1sz;
11061             epd = extract32(tcr, 23, 1);
11062             hpd = extract64(tcr, 42, 1);
11063         }
11064         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11065         hpd &= extract32(tcr, 6, 1);
11066     }
11067 
11068     return (ARMVAParameters) {
11069         .tsz = tsz,
11070         .select = select,
11071         .epd = epd,
11072         .hpd = hpd,
11073     };
11074 }
11075 
11076 /**
11077  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
11078  *
11079  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11080  * prot and page_size may not be filled in, and the populated fsr value provides
11081  * information on why the translation aborted, in the format of a long-format
11082  * DFSR/IFSR fault register, with the following caveats:
11083  *  * the WnR bit is never set (the caller must do this).
11084  *
11085  * @env: CPUARMState
11086  * @address: virtual address to get physical address for
11087  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
11088  * @mmu_idx: MMU index indicating required translation regime
11089  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
11090  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
11091  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
11092  * @phys_ptr: set to the physical address corresponding to the virtual address
11093  * @attrs: set to the memory transaction attributes to use
11094  * @prot: set to the permissions for the page containing phys_ptr
11095  * @page_size_ptr: set to the size of the page containing phys_ptr
11096  * @fi: set to fault info if the translation fails
11097  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11098  */
11099 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
11100                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11101                                bool s1_is_el0,
11102                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11103                                target_ulong *page_size_ptr,
11104                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11105 {
11106     ARMCPU *cpu = env_archcpu(env);
11107     CPUState *cs = CPU(cpu);
11108     /* Read an LPAE long-descriptor translation table. */
11109     ARMFaultType fault_type = ARMFault_Translation;
11110     uint32_t level;
11111     ARMVAParameters param;
11112     uint64_t ttbr;
11113     hwaddr descaddr, indexmask, indexmask_grainsize;
11114     uint32_t tableattrs;
11115     target_ulong page_size;
11116     uint32_t attrs;
11117     int32_t stride;
11118     int addrsize, inputsize;
11119     TCR *tcr = regime_tcr(env, mmu_idx);
11120     int ap, ns, xn, pxn;
11121     uint32_t el = regime_el(env, mmu_idx);
11122     uint64_t descaddrmask;
11123     bool aarch64 = arm_el_is_aa64(env, el);
11124     bool guarded = false;
11125 
11126     /* TODO: This code does not support shareability levels. */
11127     if (aarch64) {
11128         param = aa64_va_parameters(env, address, mmu_idx,
11129                                    access_type != MMU_INST_FETCH);
11130         level = 0;
11131         addrsize = 64 - 8 * param.tbi;
11132         inputsize = 64 - param.tsz;
11133     } else {
11134         param = aa32_va_parameters(env, address, mmu_idx);
11135         level = 1;
11136         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
11137         inputsize = addrsize - param.tsz;
11138     }
11139 
11140     /*
11141      * We determined the region when collecting the parameters, but we
11142      * have not yet validated that the address is valid for the region.
11143      * Extract the top bits and verify that they all match select.
11144      *
11145      * For aa32, if inputsize == addrsize, then we have selected the
11146      * region by exclusion in aa32_va_parameters and there is no more
11147      * validation to do here.
11148      */
11149     if (inputsize < addrsize) {
11150         target_ulong top_bits = sextract64(address, inputsize,
11151                                            addrsize - inputsize);
11152         if (-top_bits != param.select) {
11153             /* The gap between the two regions is a Translation fault */
11154             fault_type = ARMFault_Translation;
11155             goto do_fault;
11156         }
11157     }
11158 
11159     if (param.using64k) {
11160         stride = 13;
11161     } else if (param.using16k) {
11162         stride = 11;
11163     } else {
11164         stride = 9;
11165     }
11166 
11167     /* Note that QEMU ignores shareability and cacheability attributes,
11168      * so we don't need to do anything with the SH, ORGN, IRGN fields
11169      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11170      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11171      * implement any ASID-like capability so we can ignore it (instead
11172      * we will always flush the TLB any time the ASID is changed).
11173      */
11174     ttbr = regime_ttbr(env, mmu_idx, param.select);
11175 
11176     /* Here we should have set up all the parameters for the translation:
11177      * inputsize, ttbr, epd, stride, tbi
11178      */
11179 
11180     if (param.epd) {
11181         /* Translation table walk disabled => Translation fault on TLB miss
11182          * Note: This is always 0 on 64-bit EL2 and EL3.
11183          */
11184         goto do_fault;
11185     }
11186 
11187     if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
11188         /* The starting level depends on the virtual address size (which can
11189          * be up to 48 bits) and the translation granule size. It indicates
11190          * the number of strides (stride bits at a time) needed to
11191          * consume the bits of the input address. In the pseudocode this is:
11192          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11193          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11194          * our 'stride + 3' and 'stride' is our 'stride'.
11195          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11196          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11197          * = 4 - (inputsize - 4) / stride;
11198          */
11199         level = 4 - (inputsize - 4) / stride;
11200     } else {
11201         /* For stage 2 translations the starting level is specified by the
11202          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11203          */
11204         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11205         uint32_t startlevel;
11206         bool ok;
11207 
11208         if (!aarch64 || stride == 9) {
11209             /* AArch32 or 4KB pages */
11210             startlevel = 2 - sl0;
11211 
11212             if (cpu_isar_feature(aa64_st, cpu)) {
11213                 startlevel &= 3;
11214             }
11215         } else {
11216             /* 16KB or 64KB pages */
11217             startlevel = 3 - sl0;
11218         }
11219 
11220         /* Check that the starting level is valid. */
11221         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11222                                 inputsize, stride);
11223         if (!ok) {
11224             fault_type = ARMFault_Translation;
11225             goto do_fault;
11226         }
11227         level = startlevel;
11228     }
11229 
11230     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
11231     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
11232 
11233     /* Now we can extract the actual base address from the TTBR */
11234     descaddr = extract64(ttbr, 0, 48);
11235     /*
11236      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
11237      * and also to mask out CnP (bit 0) which could validly be non-zero.
11238      */
11239     descaddr &= ~indexmask;
11240 
11241     /* The address field in the descriptor goes up to bit 39 for ARMv7
11242      * but up to bit 47 for ARMv8, but we use the descaddrmask
11243      * up to bit 39 for AArch32, because we don't need other bits in that case
11244      * to construct next descriptor address (anyway they should be all zeroes).
11245      */
11246     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
11247                    ~indexmask_grainsize;
11248 
11249     /* Secure accesses start with the page table in secure memory and
11250      * can be downgraded to non-secure at any step. Non-secure accesses
11251      * remain non-secure. We implement this by just ORing in the NSTable/NS
11252      * bits at each step.
11253      */
11254     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11255     for (;;) {
11256         uint64_t descriptor;
11257         bool nstable;
11258 
11259         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11260         descaddr &= ~7ULL;
11261         nstable = extract32(tableattrs, 4, 1);
11262         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11263         if (fi->type != ARMFault_None) {
11264             goto do_fault;
11265         }
11266 
11267         if (!(descriptor & 1) ||
11268             (!(descriptor & 2) && (level == 3))) {
11269             /* Invalid, or the Reserved level 3 encoding */
11270             goto do_fault;
11271         }
11272         descaddr = descriptor & descaddrmask;
11273 
11274         if ((descriptor & 2) && (level < 3)) {
11275             /* Table entry. The top five bits are attributes which may
11276              * propagate down through lower levels of the table (and
11277              * which are all arranged so that 0 means "no effect", so
11278              * we can gather them up by ORing in the bits at each level).
11279              */
11280             tableattrs |= extract64(descriptor, 59, 5);
11281             level++;
11282             indexmask = indexmask_grainsize;
11283             continue;
11284         }
11285         /* Block entry at level 1 or 2, or page entry at level 3.
11286          * These are basically the same thing, although the number
11287          * of bits we pull in from the vaddr varies.
11288          */
11289         page_size = (1ULL << ((stride * (4 - level)) + 3));
11290         descaddr |= (address & (page_size - 1));
11291         /* Extract attributes from the descriptor */
11292         attrs = extract64(descriptor, 2, 10)
11293             | (extract64(descriptor, 52, 12) << 10);
11294 
11295         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11296             /* Stage 2 table descriptors do not include any attribute fields */
11297             break;
11298         }
11299         /* Merge in attributes from table descriptors */
11300         attrs |= nstable << 3; /* NS */
11301         guarded = extract64(descriptor, 50, 1);  /* GP */
11302         if (param.hpd) {
11303             /* HPD disables all the table attributes except NSTable.  */
11304             break;
11305         }
11306         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11307         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11308          * means "force PL1 access only", which means forcing AP[1] to 0.
11309          */
11310         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11311         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11312         break;
11313     }
11314     /* Here descaddr is the final physical address, and attributes
11315      * are all in attrs.
11316      */
11317     fault_type = ARMFault_AccessFlag;
11318     if ((attrs & (1 << 8)) == 0) {
11319         /* Access flag */
11320         goto do_fault;
11321     }
11322 
11323     ap = extract32(attrs, 4, 2);
11324 
11325     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11326         ns = mmu_idx == ARMMMUIdx_Stage2;
11327         xn = extract32(attrs, 11, 2);
11328         *prot = get_S2prot(env, ap, xn, s1_is_el0);
11329     } else {
11330         ns = extract32(attrs, 3, 1);
11331         xn = extract32(attrs, 12, 1);
11332         pxn = extract32(attrs, 11, 1);
11333         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11334     }
11335 
11336     fault_type = ARMFault_Permission;
11337     if (!(*prot & (1 << access_type))) {
11338         goto do_fault;
11339     }
11340 
11341     if (ns) {
11342         /* The NS bit will (as required by the architecture) have no effect if
11343          * the CPU doesn't support TZ or this is a non-secure translation
11344          * regime, because the attribute will already be non-secure.
11345          */
11346         txattrs->secure = false;
11347     }
11348     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11349     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11350         arm_tlb_bti_gp(txattrs) = true;
11351     }
11352 
11353     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11354         cacheattrs->attrs = convert_stage2_attrs(env, extract32(attrs, 0, 4));
11355     } else {
11356         /* Index into MAIR registers for cache attributes */
11357         uint8_t attrindx = extract32(attrs, 0, 3);
11358         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11359         assert(attrindx <= 7);
11360         cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11361     }
11362     cacheattrs->shareability = extract32(attrs, 6, 2);
11363 
11364     *phys_ptr = descaddr;
11365     *page_size_ptr = page_size;
11366     return false;
11367 
11368 do_fault:
11369     fi->type = fault_type;
11370     fi->level = level;
11371     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11372     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2 ||
11373                                mmu_idx == ARMMMUIdx_Stage2_S);
11374     fi->s1ns = mmu_idx == ARMMMUIdx_Stage2;
11375     return true;
11376 }
11377 
11378 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11379                                                 ARMMMUIdx mmu_idx,
11380                                                 int32_t address, int *prot)
11381 {
11382     if (!arm_feature(env, ARM_FEATURE_M)) {
11383         *prot = PAGE_READ | PAGE_WRITE;
11384         switch (address) {
11385         case 0xF0000000 ... 0xFFFFFFFF:
11386             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11387                 /* hivecs execing is ok */
11388                 *prot |= PAGE_EXEC;
11389             }
11390             break;
11391         case 0x00000000 ... 0x7FFFFFFF:
11392             *prot |= PAGE_EXEC;
11393             break;
11394         }
11395     } else {
11396         /* Default system address map for M profile cores.
11397          * The architecture specifies which regions are execute-never;
11398          * at the MPU level no other checks are defined.
11399          */
11400         switch (address) {
11401         case 0x00000000 ... 0x1fffffff: /* ROM */
11402         case 0x20000000 ... 0x3fffffff: /* SRAM */
11403         case 0x60000000 ... 0x7fffffff: /* RAM */
11404         case 0x80000000 ... 0x9fffffff: /* RAM */
11405             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11406             break;
11407         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11408         case 0xa0000000 ... 0xbfffffff: /* Device */
11409         case 0xc0000000 ... 0xdfffffff: /* Device */
11410         case 0xe0000000 ... 0xffffffff: /* System */
11411             *prot = PAGE_READ | PAGE_WRITE;
11412             break;
11413         default:
11414             g_assert_not_reached();
11415         }
11416     }
11417 }
11418 
11419 static bool pmsav7_use_background_region(ARMCPU *cpu,
11420                                          ARMMMUIdx mmu_idx, bool is_user)
11421 {
11422     /* Return true if we should use the default memory map as a
11423      * "background" region if there are no hits against any MPU regions.
11424      */
11425     CPUARMState *env = &cpu->env;
11426 
11427     if (is_user) {
11428         return false;
11429     }
11430 
11431     if (arm_feature(env, ARM_FEATURE_M)) {
11432         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11433             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11434     } else {
11435         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11436     }
11437 }
11438 
11439 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11440 {
11441     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11442     return arm_feature(env, ARM_FEATURE_M) &&
11443         extract32(address, 20, 12) == 0xe00;
11444 }
11445 
11446 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11447 {
11448     /* True if address is in the M profile system region
11449      * 0xe0000000 - 0xffffffff
11450      */
11451     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11452 }
11453 
11454 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11455                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11456                                  hwaddr *phys_ptr, int *prot,
11457                                  target_ulong *page_size,
11458                                  ARMMMUFaultInfo *fi)
11459 {
11460     ARMCPU *cpu = env_archcpu(env);
11461     int n;
11462     bool is_user = regime_is_user(env, mmu_idx);
11463 
11464     *phys_ptr = address;
11465     *page_size = TARGET_PAGE_SIZE;
11466     *prot = 0;
11467 
11468     if (regime_translation_disabled(env, mmu_idx) ||
11469         m_is_ppb_region(env, address)) {
11470         /* MPU disabled or M profile PPB access: use default memory map.
11471          * The other case which uses the default memory map in the
11472          * v7M ARM ARM pseudocode is exception vector reads from the vector
11473          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11474          * which always does a direct read using address_space_ldl(), rather
11475          * than going via this function, so we don't need to check that here.
11476          */
11477         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11478     } else { /* MPU enabled */
11479         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11480             /* region search */
11481             uint32_t base = env->pmsav7.drbar[n];
11482             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11483             uint32_t rmask;
11484             bool srdis = false;
11485 
11486             if (!(env->pmsav7.drsr[n] & 0x1)) {
11487                 continue;
11488             }
11489 
11490             if (!rsize) {
11491                 qemu_log_mask(LOG_GUEST_ERROR,
11492                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11493                 continue;
11494             }
11495             rsize++;
11496             rmask = (1ull << rsize) - 1;
11497 
11498             if (base & rmask) {
11499                 qemu_log_mask(LOG_GUEST_ERROR,
11500                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11501                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11502                               n, base, rmask);
11503                 continue;
11504             }
11505 
11506             if (address < base || address > base + rmask) {
11507                 /*
11508                  * Address not in this region. We must check whether the
11509                  * region covers addresses in the same page as our address.
11510                  * In that case we must not report a size that covers the
11511                  * whole page for a subsequent hit against a different MPU
11512                  * region or the background region, because it would result in
11513                  * incorrect TLB hits for subsequent accesses to addresses that
11514                  * are in this MPU region.
11515                  */
11516                 if (ranges_overlap(base, rmask,
11517                                    address & TARGET_PAGE_MASK,
11518                                    TARGET_PAGE_SIZE)) {
11519                     *page_size = 1;
11520                 }
11521                 continue;
11522             }
11523 
11524             /* Region matched */
11525 
11526             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11527                 int i, snd;
11528                 uint32_t srdis_mask;
11529 
11530                 rsize -= 3; /* sub region size (power of 2) */
11531                 snd = ((address - base) >> rsize) & 0x7;
11532                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11533 
11534                 srdis_mask = srdis ? 0x3 : 0x0;
11535                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11536                     /* This will check in groups of 2, 4 and then 8, whether
11537                      * the subregion bits are consistent. rsize is incremented
11538                      * back up to give the region size, considering consistent
11539                      * adjacent subregions as one region. Stop testing if rsize
11540                      * is already big enough for an entire QEMU page.
11541                      */
11542                     int snd_rounded = snd & ~(i - 1);
11543                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11544                                                      snd_rounded + 8, i);
11545                     if (srdis_mask ^ srdis_multi) {
11546                         break;
11547                     }
11548                     srdis_mask = (srdis_mask << i) | srdis_mask;
11549                     rsize++;
11550                 }
11551             }
11552             if (srdis) {
11553                 continue;
11554             }
11555             if (rsize < TARGET_PAGE_BITS) {
11556                 *page_size = 1 << rsize;
11557             }
11558             break;
11559         }
11560 
11561         if (n == -1) { /* no hits */
11562             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11563                 /* background fault */
11564                 fi->type = ARMFault_Background;
11565                 return true;
11566             }
11567             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11568         } else { /* a MPU hit! */
11569             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
11570             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
11571 
11572             if (m_is_system_region(env, address)) {
11573                 /* System space is always execute never */
11574                 xn = 1;
11575             }
11576 
11577             if (is_user) { /* User mode AP bit decoding */
11578                 switch (ap) {
11579                 case 0:
11580                 case 1:
11581                 case 5:
11582                     break; /* no access */
11583                 case 3:
11584                     *prot |= PAGE_WRITE;
11585                     /* fall through */
11586                 case 2:
11587                 case 6:
11588                     *prot |= PAGE_READ | PAGE_EXEC;
11589                     break;
11590                 case 7:
11591                     /* for v7M, same as 6; for R profile a reserved value */
11592                     if (arm_feature(env, ARM_FEATURE_M)) {
11593                         *prot |= PAGE_READ | PAGE_EXEC;
11594                         break;
11595                     }
11596                     /* fall through */
11597                 default:
11598                     qemu_log_mask(LOG_GUEST_ERROR,
11599                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11600                                   PRIx32 "\n", n, ap);
11601                 }
11602             } else { /* Priv. mode AP bits decoding */
11603                 switch (ap) {
11604                 case 0:
11605                     break; /* no access */
11606                 case 1:
11607                 case 2:
11608                 case 3:
11609                     *prot |= PAGE_WRITE;
11610                     /* fall through */
11611                 case 5:
11612                 case 6:
11613                     *prot |= PAGE_READ | PAGE_EXEC;
11614                     break;
11615                 case 7:
11616                     /* for v7M, same as 6; for R profile a reserved value */
11617                     if (arm_feature(env, ARM_FEATURE_M)) {
11618                         *prot |= PAGE_READ | PAGE_EXEC;
11619                         break;
11620                     }
11621                     /* fall through */
11622                 default:
11623                     qemu_log_mask(LOG_GUEST_ERROR,
11624                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11625                                   PRIx32 "\n", n, ap);
11626                 }
11627             }
11628 
11629             /* execute never */
11630             if (xn) {
11631                 *prot &= ~PAGE_EXEC;
11632             }
11633         }
11634     }
11635 
11636     fi->type = ARMFault_Permission;
11637     fi->level = 1;
11638     return !(*prot & (1 << access_type));
11639 }
11640 
11641 static bool v8m_is_sau_exempt(CPUARMState *env,
11642                               uint32_t address, MMUAccessType access_type)
11643 {
11644     /* The architecture specifies that certain address ranges are
11645      * exempt from v8M SAU/IDAU checks.
11646      */
11647     return
11648         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
11649         (address >= 0xe0000000 && address <= 0xe0002fff) ||
11650         (address >= 0xe000e000 && address <= 0xe000efff) ||
11651         (address >= 0xe002e000 && address <= 0xe002efff) ||
11652         (address >= 0xe0040000 && address <= 0xe0041fff) ||
11653         (address >= 0xe00ff000 && address <= 0xe00fffff);
11654 }
11655 
11656 void v8m_security_lookup(CPUARMState *env, uint32_t address,
11657                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
11658                                 V8M_SAttributes *sattrs)
11659 {
11660     /* Look up the security attributes for this address. Compare the
11661      * pseudocode SecurityCheck() function.
11662      * We assume the caller has zero-initialized *sattrs.
11663      */
11664     ARMCPU *cpu = env_archcpu(env);
11665     int r;
11666     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
11667     int idau_region = IREGION_NOTVALID;
11668     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11669     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11670 
11671     if (cpu->idau) {
11672         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
11673         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
11674 
11675         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
11676                    &idau_nsc);
11677     }
11678 
11679     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
11680         /* 0xf0000000..0xffffffff is always S for insn fetches */
11681         return;
11682     }
11683 
11684     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
11685         sattrs->ns = !regime_is_secure(env, mmu_idx);
11686         return;
11687     }
11688 
11689     if (idau_region != IREGION_NOTVALID) {
11690         sattrs->irvalid = true;
11691         sattrs->iregion = idau_region;
11692     }
11693 
11694     switch (env->sau.ctrl & 3) {
11695     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
11696         break;
11697     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
11698         sattrs->ns = true;
11699         break;
11700     default: /* SAU.ENABLE == 1 */
11701         for (r = 0; r < cpu->sau_sregion; r++) {
11702             if (env->sau.rlar[r] & 1) {
11703                 uint32_t base = env->sau.rbar[r] & ~0x1f;
11704                 uint32_t limit = env->sau.rlar[r] | 0x1f;
11705 
11706                 if (base <= address && limit >= address) {
11707                     if (base > addr_page_base || limit < addr_page_limit) {
11708                         sattrs->subpage = true;
11709                     }
11710                     if (sattrs->srvalid) {
11711                         /* If we hit in more than one region then we must report
11712                          * as Secure, not NS-Callable, with no valid region
11713                          * number info.
11714                          */
11715                         sattrs->ns = false;
11716                         sattrs->nsc = false;
11717                         sattrs->sregion = 0;
11718                         sattrs->srvalid = false;
11719                         break;
11720                     } else {
11721                         if (env->sau.rlar[r] & 2) {
11722                             sattrs->nsc = true;
11723                         } else {
11724                             sattrs->ns = true;
11725                         }
11726                         sattrs->srvalid = true;
11727                         sattrs->sregion = r;
11728                     }
11729                 } else {
11730                     /*
11731                      * Address not in this region. We must check whether the
11732                      * region covers addresses in the same page as our address.
11733                      * In that case we must not report a size that covers the
11734                      * whole page for a subsequent hit against a different MPU
11735                      * region or the background region, because it would result
11736                      * in incorrect TLB hits for subsequent accesses to
11737                      * addresses that are in this MPU region.
11738                      */
11739                     if (limit >= base &&
11740                         ranges_overlap(base, limit - base + 1,
11741                                        addr_page_base,
11742                                        TARGET_PAGE_SIZE)) {
11743                         sattrs->subpage = true;
11744                     }
11745                 }
11746             }
11747         }
11748         break;
11749     }
11750 
11751     /*
11752      * The IDAU will override the SAU lookup results if it specifies
11753      * higher security than the SAU does.
11754      */
11755     if (!idau_ns) {
11756         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
11757             sattrs->ns = false;
11758             sattrs->nsc = idau_nsc;
11759         }
11760     }
11761 }
11762 
11763 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
11764                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
11765                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
11766                               int *prot, bool *is_subpage,
11767                               ARMMMUFaultInfo *fi, uint32_t *mregion)
11768 {
11769     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
11770      * that a full phys-to-virt translation does).
11771      * mregion is (if not NULL) set to the region number which matched,
11772      * or -1 if no region number is returned (MPU off, address did not
11773      * hit a region, address hit in multiple regions).
11774      * We set is_subpage to true if the region hit doesn't cover the
11775      * entire TARGET_PAGE the address is within.
11776      */
11777     ARMCPU *cpu = env_archcpu(env);
11778     bool is_user = regime_is_user(env, mmu_idx);
11779     uint32_t secure = regime_is_secure(env, mmu_idx);
11780     int n;
11781     int matchregion = -1;
11782     bool hit = false;
11783     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11784     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11785 
11786     *is_subpage = false;
11787     *phys_ptr = address;
11788     *prot = 0;
11789     if (mregion) {
11790         *mregion = -1;
11791     }
11792 
11793     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
11794      * was an exception vector read from the vector table (which is always
11795      * done using the default system address map), because those accesses
11796      * are done in arm_v7m_load_vector(), which always does a direct
11797      * read using address_space_ldl(), rather than going via this function.
11798      */
11799     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
11800         hit = true;
11801     } else if (m_is_ppb_region(env, address)) {
11802         hit = true;
11803     } else {
11804         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11805             hit = true;
11806         }
11807 
11808         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11809             /* region search */
11810             /* Note that the base address is bits [31:5] from the register
11811              * with bits [4:0] all zeroes, but the limit address is bits
11812              * [31:5] from the register with bits [4:0] all ones.
11813              */
11814             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
11815             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
11816 
11817             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
11818                 /* Region disabled */
11819                 continue;
11820             }
11821 
11822             if (address < base || address > limit) {
11823                 /*
11824                  * Address not in this region. We must check whether the
11825                  * region covers addresses in the same page as our address.
11826                  * In that case we must not report a size that covers the
11827                  * whole page for a subsequent hit against a different MPU
11828                  * region or the background region, because it would result in
11829                  * incorrect TLB hits for subsequent accesses to addresses that
11830                  * are in this MPU region.
11831                  */
11832                 if (limit >= base &&
11833                     ranges_overlap(base, limit - base + 1,
11834                                    addr_page_base,
11835                                    TARGET_PAGE_SIZE)) {
11836                     *is_subpage = true;
11837                 }
11838                 continue;
11839             }
11840 
11841             if (base > addr_page_base || limit < addr_page_limit) {
11842                 *is_subpage = true;
11843             }
11844 
11845             if (matchregion != -1) {
11846                 /* Multiple regions match -- always a failure (unlike
11847                  * PMSAv7 where highest-numbered-region wins)
11848                  */
11849                 fi->type = ARMFault_Permission;
11850                 fi->level = 1;
11851                 return true;
11852             }
11853 
11854             matchregion = n;
11855             hit = true;
11856         }
11857     }
11858 
11859     if (!hit) {
11860         /* background fault */
11861         fi->type = ARMFault_Background;
11862         return true;
11863     }
11864 
11865     if (matchregion == -1) {
11866         /* hit using the background region */
11867         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11868     } else {
11869         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
11870         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
11871         bool pxn = false;
11872 
11873         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
11874             pxn = extract32(env->pmsav8.rlar[secure][matchregion], 4, 1);
11875         }
11876 
11877         if (m_is_system_region(env, address)) {
11878             /* System space is always execute never */
11879             xn = 1;
11880         }
11881 
11882         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
11883         if (*prot && !xn && !(pxn && !is_user)) {
11884             *prot |= PAGE_EXEC;
11885         }
11886         /* We don't need to look the attribute up in the MAIR0/MAIR1
11887          * registers because that only tells us about cacheability.
11888          */
11889         if (mregion) {
11890             *mregion = matchregion;
11891         }
11892     }
11893 
11894     fi->type = ARMFault_Permission;
11895     fi->level = 1;
11896     return !(*prot & (1 << access_type));
11897 }
11898 
11899 
11900 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
11901                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11902                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
11903                                  int *prot, target_ulong *page_size,
11904                                  ARMMMUFaultInfo *fi)
11905 {
11906     uint32_t secure = regime_is_secure(env, mmu_idx);
11907     V8M_SAttributes sattrs = {};
11908     bool ret;
11909     bool mpu_is_subpage;
11910 
11911     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
11912         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
11913         if (access_type == MMU_INST_FETCH) {
11914             /* Instruction fetches always use the MMU bank and the
11915              * transaction attribute determined by the fetch address,
11916              * regardless of CPU state. This is painful for QEMU
11917              * to handle, because it would mean we need to encode
11918              * into the mmu_idx not just the (user, negpri) information
11919              * for the current security state but also that for the
11920              * other security state, which would balloon the number
11921              * of mmu_idx values needed alarmingly.
11922              * Fortunately we can avoid this because it's not actually
11923              * possible to arbitrarily execute code from memory with
11924              * the wrong security attribute: it will always generate
11925              * an exception of some kind or another, apart from the
11926              * special case of an NS CPU executing an SG instruction
11927              * in S&NSC memory. So we always just fail the translation
11928              * here and sort things out in the exception handler
11929              * (including possibly emulating an SG instruction).
11930              */
11931             if (sattrs.ns != !secure) {
11932                 if (sattrs.nsc) {
11933                     fi->type = ARMFault_QEMU_NSCExec;
11934                 } else {
11935                     fi->type = ARMFault_QEMU_SFault;
11936                 }
11937                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
11938                 *phys_ptr = address;
11939                 *prot = 0;
11940                 return true;
11941             }
11942         } else {
11943             /* For data accesses we always use the MMU bank indicated
11944              * by the current CPU state, but the security attributes
11945              * might downgrade a secure access to nonsecure.
11946              */
11947             if (sattrs.ns) {
11948                 txattrs->secure = false;
11949             } else if (!secure) {
11950                 /* NS access to S memory must fault.
11951                  * Architecturally we should first check whether the
11952                  * MPU information for this address indicates that we
11953                  * are doing an unaligned access to Device memory, which
11954                  * should generate a UsageFault instead. QEMU does not
11955                  * currently check for that kind of unaligned access though.
11956                  * If we added it we would need to do so as a special case
11957                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
11958                  */
11959                 fi->type = ARMFault_QEMU_SFault;
11960                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
11961                 *phys_ptr = address;
11962                 *prot = 0;
11963                 return true;
11964             }
11965         }
11966     }
11967 
11968     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
11969                             txattrs, prot, &mpu_is_subpage, fi, NULL);
11970     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
11971     return ret;
11972 }
11973 
11974 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
11975                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11976                                  hwaddr *phys_ptr, int *prot,
11977                                  ARMMMUFaultInfo *fi)
11978 {
11979     int n;
11980     uint32_t mask;
11981     uint32_t base;
11982     bool is_user = regime_is_user(env, mmu_idx);
11983 
11984     if (regime_translation_disabled(env, mmu_idx)) {
11985         /* MPU disabled.  */
11986         *phys_ptr = address;
11987         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11988         return false;
11989     }
11990 
11991     *phys_ptr = address;
11992     for (n = 7; n >= 0; n--) {
11993         base = env->cp15.c6_region[n];
11994         if ((base & 1) == 0) {
11995             continue;
11996         }
11997         mask = 1 << ((base >> 1) & 0x1f);
11998         /* Keep this shift separate from the above to avoid an
11999            (undefined) << 32.  */
12000         mask = (mask << 1) - 1;
12001         if (((base ^ address) & ~mask) == 0) {
12002             break;
12003         }
12004     }
12005     if (n < 0) {
12006         fi->type = ARMFault_Background;
12007         return true;
12008     }
12009 
12010     if (access_type == MMU_INST_FETCH) {
12011         mask = env->cp15.pmsav5_insn_ap;
12012     } else {
12013         mask = env->cp15.pmsav5_data_ap;
12014     }
12015     mask = (mask >> (n * 4)) & 0xf;
12016     switch (mask) {
12017     case 0:
12018         fi->type = ARMFault_Permission;
12019         fi->level = 1;
12020         return true;
12021     case 1:
12022         if (is_user) {
12023             fi->type = ARMFault_Permission;
12024             fi->level = 1;
12025             return true;
12026         }
12027         *prot = PAGE_READ | PAGE_WRITE;
12028         break;
12029     case 2:
12030         *prot = PAGE_READ;
12031         if (!is_user) {
12032             *prot |= PAGE_WRITE;
12033         }
12034         break;
12035     case 3:
12036         *prot = PAGE_READ | PAGE_WRITE;
12037         break;
12038     case 5:
12039         if (is_user) {
12040             fi->type = ARMFault_Permission;
12041             fi->level = 1;
12042             return true;
12043         }
12044         *prot = PAGE_READ;
12045         break;
12046     case 6:
12047         *prot = PAGE_READ;
12048         break;
12049     default:
12050         /* Bad permission.  */
12051         fi->type = ARMFault_Permission;
12052         fi->level = 1;
12053         return true;
12054     }
12055     *prot |= PAGE_EXEC;
12056     return false;
12057 }
12058 
12059 /* Combine either inner or outer cacheability attributes for normal
12060  * memory, according to table D4-42 and pseudocode procedure
12061  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12062  *
12063  * NB: only stage 1 includes allocation hints (RW bits), leading to
12064  * some asymmetry.
12065  */
12066 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12067 {
12068     if (s1 == 4 || s2 == 4) {
12069         /* non-cacheable has precedence */
12070         return 4;
12071     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12072         /* stage 1 write-through takes precedence */
12073         return s1;
12074     } else if (extract32(s2, 2, 2) == 2) {
12075         /* stage 2 write-through takes precedence, but the allocation hint
12076          * is still taken from stage 1
12077          */
12078         return (2 << 2) | extract32(s1, 0, 2);
12079     } else { /* write-back */
12080         return s1;
12081     }
12082 }
12083 
12084 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12085  * and CombineS1S2Desc()
12086  *
12087  * @s1:      Attributes from stage 1 walk
12088  * @s2:      Attributes from stage 2 walk
12089  */
12090 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
12091 {
12092     uint8_t s1lo, s2lo, s1hi, s2hi;
12093     ARMCacheAttrs ret;
12094     bool tagged = false;
12095 
12096     if (s1.attrs == 0xf0) {
12097         tagged = true;
12098         s1.attrs = 0xff;
12099     }
12100 
12101     s1lo = extract32(s1.attrs, 0, 4);
12102     s2lo = extract32(s2.attrs, 0, 4);
12103     s1hi = extract32(s1.attrs, 4, 4);
12104     s2hi = extract32(s2.attrs, 4, 4);
12105 
12106     /* Combine shareability attributes (table D4-43) */
12107     if (s1.shareability == 2 || s2.shareability == 2) {
12108         /* if either are outer-shareable, the result is outer-shareable */
12109         ret.shareability = 2;
12110     } else if (s1.shareability == 3 || s2.shareability == 3) {
12111         /* if either are inner-shareable, the result is inner-shareable */
12112         ret.shareability = 3;
12113     } else {
12114         /* both non-shareable */
12115         ret.shareability = 0;
12116     }
12117 
12118     /* Combine memory type and cacheability attributes */
12119     if (s1hi == 0 || s2hi == 0) {
12120         /* Device has precedence over normal */
12121         if (s1lo == 0 || s2lo == 0) {
12122             /* nGnRnE has precedence over anything */
12123             ret.attrs = 0;
12124         } else if (s1lo == 4 || s2lo == 4) {
12125             /* non-Reordering has precedence over Reordering */
12126             ret.attrs = 4;  /* nGnRE */
12127         } else if (s1lo == 8 || s2lo == 8) {
12128             /* non-Gathering has precedence over Gathering */
12129             ret.attrs = 8;  /* nGRE */
12130         } else {
12131             ret.attrs = 0xc; /* GRE */
12132         }
12133 
12134         /* Any location for which the resultant memory type is any
12135          * type of Device memory is always treated as Outer Shareable.
12136          */
12137         ret.shareability = 2;
12138     } else { /* Normal memory */
12139         /* Outer/inner cacheability combine independently */
12140         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12141                   | combine_cacheattr_nibble(s1lo, s2lo);
12142 
12143         if (ret.attrs == 0x44) {
12144             /* Any location for which the resultant memory type is Normal
12145              * Inner Non-cacheable, Outer Non-cacheable is always treated
12146              * as Outer Shareable.
12147              */
12148             ret.shareability = 2;
12149         }
12150     }
12151 
12152     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
12153     if (tagged && ret.attrs == 0xff) {
12154         ret.attrs = 0xf0;
12155     }
12156 
12157     return ret;
12158 }
12159 
12160 
12161 /* get_phys_addr - get the physical address for this virtual address
12162  *
12163  * Find the physical address corresponding to the given virtual address,
12164  * by doing a translation table walk on MMU based systems or using the
12165  * MPU state on MPU based systems.
12166  *
12167  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12168  * prot and page_size may not be filled in, and the populated fsr value provides
12169  * information on why the translation aborted, in the format of a
12170  * DFSR/IFSR fault register, with the following caveats:
12171  *  * we honour the short vs long DFSR format differences.
12172  *  * the WnR bit is never set (the caller must do this).
12173  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12174  *    value.
12175  *
12176  * @env: CPUARMState
12177  * @address: virtual address to get physical address for
12178  * @access_type: 0 for read, 1 for write, 2 for execute
12179  * @mmu_idx: MMU index indicating required translation regime
12180  * @phys_ptr: set to the physical address corresponding to the virtual address
12181  * @attrs: set to the memory transaction attributes to use
12182  * @prot: set to the permissions for the page containing phys_ptr
12183  * @page_size: set to the size of the page containing phys_ptr
12184  * @fi: set to fault info if the translation fails
12185  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12186  */
12187 bool get_phys_addr(CPUARMState *env, target_ulong address,
12188                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12189                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12190                    target_ulong *page_size,
12191                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12192 {
12193     ARMMMUIdx s1_mmu_idx = stage_1_mmu_idx(mmu_idx);
12194 
12195     if (mmu_idx != s1_mmu_idx) {
12196         /* Call ourselves recursively to do the stage 1 and then stage 2
12197          * translations if mmu_idx is a two-stage regime.
12198          */
12199         if (arm_feature(env, ARM_FEATURE_EL2)) {
12200             hwaddr ipa;
12201             int s2_prot;
12202             int ret;
12203             ARMCacheAttrs cacheattrs2 = {};
12204             ARMMMUIdx s2_mmu_idx;
12205             bool is_el0;
12206 
12207             ret = get_phys_addr(env, address, access_type, s1_mmu_idx, &ipa,
12208                                 attrs, prot, page_size, fi, cacheattrs);
12209 
12210             /* If S1 fails or S2 is disabled, return early.  */
12211             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
12212                 *phys_ptr = ipa;
12213                 return ret;
12214             }
12215 
12216             s2_mmu_idx = attrs->secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
12217             is_el0 = mmu_idx == ARMMMUIdx_E10_0 || mmu_idx == ARMMMUIdx_SE10_0;
12218 
12219             /* S1 is done. Now do S2 translation.  */
12220             ret = get_phys_addr_lpae(env, ipa, access_type, s2_mmu_idx, is_el0,
12221                                      phys_ptr, attrs, &s2_prot,
12222                                      page_size, fi, &cacheattrs2);
12223             fi->s2addr = ipa;
12224             /* Combine the S1 and S2 perms.  */
12225             *prot &= s2_prot;
12226 
12227             /* If S2 fails, return early.  */
12228             if (ret) {
12229                 return ret;
12230             }
12231 
12232             /* Combine the S1 and S2 cache attributes. */
12233             if (arm_hcr_el2_eff(env) & HCR_DC) {
12234                 /*
12235                  * HCR.DC forces the first stage attributes to
12236                  *  Normal Non-Shareable,
12237                  *  Inner Write-Back Read-Allocate Write-Allocate,
12238                  *  Outer Write-Back Read-Allocate Write-Allocate.
12239                  * Do not overwrite Tagged within attrs.
12240                  */
12241                 if (cacheattrs->attrs != 0xf0) {
12242                     cacheattrs->attrs = 0xff;
12243                 }
12244                 cacheattrs->shareability = 0;
12245             }
12246             *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12247 
12248             /* Check if IPA translates to secure or non-secure PA space. */
12249             if (arm_is_secure_below_el3(env)) {
12250                 if (attrs->secure) {
12251                     attrs->secure =
12252                         !(env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW));
12253                 } else {
12254                     attrs->secure =
12255                         !((env->cp15.vtcr_el2.raw_tcr & (VTCR_NSA | VTCR_NSW))
12256                         || (env->cp15.vstcr_el2.raw_tcr & VSTCR_SA));
12257                 }
12258             }
12259             return 0;
12260         } else {
12261             /*
12262              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12263              */
12264             mmu_idx = stage_1_mmu_idx(mmu_idx);
12265         }
12266     }
12267 
12268     /* The page table entries may downgrade secure to non-secure, but
12269      * cannot upgrade an non-secure translation regime's attributes
12270      * to secure.
12271      */
12272     attrs->secure = regime_is_secure(env, mmu_idx);
12273     attrs->user = regime_is_user(env, mmu_idx);
12274 
12275     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12276      * In v7 and earlier it affects all stage 1 translations.
12277      */
12278     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
12279         && !arm_feature(env, ARM_FEATURE_V8)) {
12280         if (regime_el(env, mmu_idx) == 3) {
12281             address += env->cp15.fcseidr_s;
12282         } else {
12283             address += env->cp15.fcseidr_ns;
12284         }
12285     }
12286 
12287     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12288         bool ret;
12289         *page_size = TARGET_PAGE_SIZE;
12290 
12291         if (arm_feature(env, ARM_FEATURE_V8)) {
12292             /* PMSAv8 */
12293             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12294                                        phys_ptr, attrs, prot, page_size, fi);
12295         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12296             /* PMSAv7 */
12297             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12298                                        phys_ptr, prot, page_size, fi);
12299         } else {
12300             /* Pre-v7 MPU */
12301             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12302                                        phys_ptr, prot, fi);
12303         }
12304         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12305                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12306                       access_type == MMU_DATA_LOAD ? "reading" :
12307                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12308                       (uint32_t)address, mmu_idx,
12309                       ret ? "Miss" : "Hit",
12310                       *prot & PAGE_READ ? 'r' : '-',
12311                       *prot & PAGE_WRITE ? 'w' : '-',
12312                       *prot & PAGE_EXEC ? 'x' : '-');
12313 
12314         return ret;
12315     }
12316 
12317     /* Definitely a real MMU, not an MPU */
12318 
12319     if (regime_translation_disabled(env, mmu_idx)) {
12320         uint64_t hcr;
12321         uint8_t memattr;
12322 
12323         /*
12324          * MMU disabled.  S1 addresses within aa64 translation regimes are
12325          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
12326          */
12327         if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
12328             int r_el = regime_el(env, mmu_idx);
12329             if (arm_el_is_aa64(env, r_el)) {
12330                 int pamax = arm_pamax(env_archcpu(env));
12331                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
12332                 int addrtop, tbi;
12333 
12334                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
12335                 if (access_type == MMU_INST_FETCH) {
12336                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
12337                 }
12338                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
12339                 addrtop = (tbi ? 55 : 63);
12340 
12341                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
12342                     fi->type = ARMFault_AddressSize;
12343                     fi->level = 0;
12344                     fi->stage2 = false;
12345                     return 1;
12346                 }
12347 
12348                 /*
12349                  * When TBI is disabled, we've just validated that all of the
12350                  * bits above PAMax are zero, so logically we only need to
12351                  * clear the top byte for TBI.  But it's clearer to follow
12352                  * the pseudocode set of addrdesc.paddress.
12353                  */
12354                 address = extract64(address, 0, 52);
12355             }
12356         }
12357         *phys_ptr = address;
12358         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12359         *page_size = TARGET_PAGE_SIZE;
12360 
12361         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
12362         hcr = arm_hcr_el2_eff(env);
12363         cacheattrs->shareability = 0;
12364         if (hcr & HCR_DC) {
12365             if (hcr & HCR_DCT) {
12366                 memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
12367             } else {
12368                 memattr = 0xff;  /* Normal, WB, RWA */
12369             }
12370         } else if (access_type == MMU_INST_FETCH) {
12371             if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
12372                 memattr = 0xee;  /* Normal, WT, RA, NT */
12373             } else {
12374                 memattr = 0x44;  /* Normal, NC, No */
12375             }
12376             cacheattrs->shareability = 2; /* outer sharable */
12377         } else {
12378             memattr = 0x00;      /* Device, nGnRnE */
12379         }
12380         cacheattrs->attrs = memattr;
12381         return 0;
12382     }
12383 
12384     if (regime_using_lpae_format(env, mmu_idx)) {
12385         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
12386                                   phys_ptr, attrs, prot, page_size,
12387                                   fi, cacheattrs);
12388     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12389         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12390                                 phys_ptr, attrs, prot, page_size, fi);
12391     } else {
12392         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12393                                     phys_ptr, prot, page_size, fi);
12394     }
12395 }
12396 
12397 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12398                                          MemTxAttrs *attrs)
12399 {
12400     ARMCPU *cpu = ARM_CPU(cs);
12401     CPUARMState *env = &cpu->env;
12402     hwaddr phys_addr;
12403     target_ulong page_size;
12404     int prot;
12405     bool ret;
12406     ARMMMUFaultInfo fi = {};
12407     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12408     ARMCacheAttrs cacheattrs = {};
12409 
12410     *attrs = (MemTxAttrs) {};
12411 
12412     ret = get_phys_addr(env, addr, 0, mmu_idx, &phys_addr,
12413                         attrs, &prot, &page_size, &fi, &cacheattrs);
12414 
12415     if (ret) {
12416         return -1;
12417     }
12418     return phys_addr;
12419 }
12420 
12421 #endif
12422 
12423 /* Note that signed overflow is undefined in C.  The following routines are
12424    careful to use unsigned types where modulo arithmetic is required.
12425    Failure to do so _will_ break on newer gcc.  */
12426 
12427 /* Signed saturating arithmetic.  */
12428 
12429 /* Perform 16-bit signed saturating addition.  */
12430 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
12431 {
12432     uint16_t res;
12433 
12434     res = a + b;
12435     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
12436         if (a & 0x8000)
12437             res = 0x8000;
12438         else
12439             res = 0x7fff;
12440     }
12441     return res;
12442 }
12443 
12444 /* Perform 8-bit signed saturating addition.  */
12445 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
12446 {
12447     uint8_t res;
12448 
12449     res = a + b;
12450     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
12451         if (a & 0x80)
12452             res = 0x80;
12453         else
12454             res = 0x7f;
12455     }
12456     return res;
12457 }
12458 
12459 /* Perform 16-bit signed saturating subtraction.  */
12460 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
12461 {
12462     uint16_t res;
12463 
12464     res = a - b;
12465     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
12466         if (a & 0x8000)
12467             res = 0x8000;
12468         else
12469             res = 0x7fff;
12470     }
12471     return res;
12472 }
12473 
12474 /* Perform 8-bit signed saturating subtraction.  */
12475 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
12476 {
12477     uint8_t res;
12478 
12479     res = a - b;
12480     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
12481         if (a & 0x80)
12482             res = 0x80;
12483         else
12484             res = 0x7f;
12485     }
12486     return res;
12487 }
12488 
12489 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
12490 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
12491 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
12492 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
12493 #define PFX q
12494 
12495 #include "op_addsub.h"
12496 
12497 /* Unsigned saturating arithmetic.  */
12498 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
12499 {
12500     uint16_t res;
12501     res = a + b;
12502     if (res < a)
12503         res = 0xffff;
12504     return res;
12505 }
12506 
12507 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
12508 {
12509     if (a > b)
12510         return a - b;
12511     else
12512         return 0;
12513 }
12514 
12515 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
12516 {
12517     uint8_t res;
12518     res = a + b;
12519     if (res < a)
12520         res = 0xff;
12521     return res;
12522 }
12523 
12524 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
12525 {
12526     if (a > b)
12527         return a - b;
12528     else
12529         return 0;
12530 }
12531 
12532 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
12533 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
12534 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
12535 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
12536 #define PFX uq
12537 
12538 #include "op_addsub.h"
12539 
12540 /* Signed modulo arithmetic.  */
12541 #define SARITH16(a, b, n, op) do { \
12542     int32_t sum; \
12543     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
12544     RESULT(sum, n, 16); \
12545     if (sum >= 0) \
12546         ge |= 3 << (n * 2); \
12547     } while(0)
12548 
12549 #define SARITH8(a, b, n, op) do { \
12550     int32_t sum; \
12551     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
12552     RESULT(sum, n, 8); \
12553     if (sum >= 0) \
12554         ge |= 1 << n; \
12555     } while(0)
12556 
12557 
12558 #define ADD16(a, b, n) SARITH16(a, b, n, +)
12559 #define SUB16(a, b, n) SARITH16(a, b, n, -)
12560 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
12561 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
12562 #define PFX s
12563 #define ARITH_GE
12564 
12565 #include "op_addsub.h"
12566 
12567 /* Unsigned modulo arithmetic.  */
12568 #define ADD16(a, b, n) do { \
12569     uint32_t sum; \
12570     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
12571     RESULT(sum, n, 16); \
12572     if ((sum >> 16) == 1) \
12573         ge |= 3 << (n * 2); \
12574     } while(0)
12575 
12576 #define ADD8(a, b, n) do { \
12577     uint32_t sum; \
12578     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
12579     RESULT(sum, n, 8); \
12580     if ((sum >> 8) == 1) \
12581         ge |= 1 << n; \
12582     } while(0)
12583 
12584 #define SUB16(a, b, n) do { \
12585     uint32_t sum; \
12586     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
12587     RESULT(sum, n, 16); \
12588     if ((sum >> 16) == 0) \
12589         ge |= 3 << (n * 2); \
12590     } while(0)
12591 
12592 #define SUB8(a, b, n) do { \
12593     uint32_t sum; \
12594     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
12595     RESULT(sum, n, 8); \
12596     if ((sum >> 8) == 0) \
12597         ge |= 1 << n; \
12598     } while(0)
12599 
12600 #define PFX u
12601 #define ARITH_GE
12602 
12603 #include "op_addsub.h"
12604 
12605 /* Halved signed arithmetic.  */
12606 #define ADD16(a, b, n) \
12607   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
12608 #define SUB16(a, b, n) \
12609   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
12610 #define ADD8(a, b, n) \
12611   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
12612 #define SUB8(a, b, n) \
12613   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
12614 #define PFX sh
12615 
12616 #include "op_addsub.h"
12617 
12618 /* Halved unsigned arithmetic.  */
12619 #define ADD16(a, b, n) \
12620   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12621 #define SUB16(a, b, n) \
12622   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12623 #define ADD8(a, b, n) \
12624   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12625 #define SUB8(a, b, n) \
12626   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12627 #define PFX uh
12628 
12629 #include "op_addsub.h"
12630 
12631 static inline uint8_t do_usad(uint8_t a, uint8_t b)
12632 {
12633     if (a > b)
12634         return a - b;
12635     else
12636         return b - a;
12637 }
12638 
12639 /* Unsigned sum of absolute byte differences.  */
12640 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
12641 {
12642     uint32_t sum;
12643     sum = do_usad(a, b);
12644     sum += do_usad(a >> 8, b >> 8);
12645     sum += do_usad(a >> 16, b >> 16);
12646     sum += do_usad(a >> 24, b >> 24);
12647     return sum;
12648 }
12649 
12650 /* For ARMv6 SEL instruction.  */
12651 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
12652 {
12653     uint32_t mask;
12654 
12655     mask = 0;
12656     if (flags & 1)
12657         mask |= 0xff;
12658     if (flags & 2)
12659         mask |= 0xff00;
12660     if (flags & 4)
12661         mask |= 0xff0000;
12662     if (flags & 8)
12663         mask |= 0xff000000;
12664     return (a & mask) | (b & ~mask);
12665 }
12666 
12667 /* CRC helpers.
12668  * The upper bytes of val (above the number specified by 'bytes') must have
12669  * been zeroed out by the caller.
12670  */
12671 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12672 {
12673     uint8_t buf[4];
12674 
12675     stl_le_p(buf, val);
12676 
12677     /* zlib crc32 converts the accumulator and output to one's complement.  */
12678     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12679 }
12680 
12681 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12682 {
12683     uint8_t buf[4];
12684 
12685     stl_le_p(buf, val);
12686 
12687     /* Linux crc32c converts the output to one's complement.  */
12688     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12689 }
12690 
12691 /* Return the exception level to which FP-disabled exceptions should
12692  * be taken, or 0 if FP is enabled.
12693  */
12694 int fp_exception_el(CPUARMState *env, int cur_el)
12695 {
12696 #ifndef CONFIG_USER_ONLY
12697     /* CPACR and the CPTR registers don't exist before v6, so FP is
12698      * always accessible
12699      */
12700     if (!arm_feature(env, ARM_FEATURE_V6)) {
12701         return 0;
12702     }
12703 
12704     if (arm_feature(env, ARM_FEATURE_M)) {
12705         /* CPACR can cause a NOCP UsageFault taken to current security state */
12706         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
12707             return 1;
12708         }
12709 
12710         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
12711             if (!extract32(env->v7m.nsacr, 10, 1)) {
12712                 /* FP insns cause a NOCP UsageFault taken to Secure */
12713                 return 3;
12714             }
12715         }
12716 
12717         return 0;
12718     }
12719 
12720     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12721      * 0, 2 : trap EL0 and EL1/PL1 accesses
12722      * 1    : trap only EL0 accesses
12723      * 3    : trap no accesses
12724      * This register is ignored if E2H+TGE are both set.
12725      */
12726     if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
12727         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12728 
12729         switch (fpen) {
12730         case 0:
12731         case 2:
12732             if (cur_el == 0 || cur_el == 1) {
12733                 /* Trap to PL1, which might be EL1 or EL3 */
12734                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12735                     return 3;
12736                 }
12737                 return 1;
12738             }
12739             if (cur_el == 3 && !is_a64(env)) {
12740                 /* Secure PL1 running at EL3 */
12741                 return 3;
12742             }
12743             break;
12744         case 1:
12745             if (cur_el == 0) {
12746                 return 1;
12747             }
12748             break;
12749         case 3:
12750             break;
12751         }
12752     }
12753 
12754     /*
12755      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
12756      * to control non-secure access to the FPU. It doesn't have any
12757      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
12758      */
12759     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
12760          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
12761         if (!extract32(env->cp15.nsacr, 10, 1)) {
12762             /* FP insns act as UNDEF */
12763             return cur_el == 2 ? 2 : 1;
12764         }
12765     }
12766 
12767     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12768      * check because zero bits in the registers mean "don't trap".
12769      */
12770 
12771     /* CPTR_EL2 : present in v7VE or v8 */
12772     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12773         && arm_is_el2_enabled(env)) {
12774         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12775         return 2;
12776     }
12777 
12778     /* CPTR_EL3 : present in v8 */
12779     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12780         /* Trap all FP ops to EL3 */
12781         return 3;
12782     }
12783 #endif
12784     return 0;
12785 }
12786 
12787 /* Return the exception level we're running at if this is our mmu_idx */
12788 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
12789 {
12790     if (mmu_idx & ARM_MMU_IDX_M) {
12791         return mmu_idx & ARM_MMU_IDX_M_PRIV;
12792     }
12793 
12794     switch (mmu_idx) {
12795     case ARMMMUIdx_E10_0:
12796     case ARMMMUIdx_E20_0:
12797     case ARMMMUIdx_SE10_0:
12798     case ARMMMUIdx_SE20_0:
12799         return 0;
12800     case ARMMMUIdx_E10_1:
12801     case ARMMMUIdx_E10_1_PAN:
12802     case ARMMMUIdx_SE10_1:
12803     case ARMMMUIdx_SE10_1_PAN:
12804         return 1;
12805     case ARMMMUIdx_E2:
12806     case ARMMMUIdx_E20_2:
12807     case ARMMMUIdx_E20_2_PAN:
12808     case ARMMMUIdx_SE2:
12809     case ARMMMUIdx_SE20_2:
12810     case ARMMMUIdx_SE20_2_PAN:
12811         return 2;
12812     case ARMMMUIdx_SE3:
12813         return 3;
12814     default:
12815         g_assert_not_reached();
12816     }
12817 }
12818 
12819 #ifndef CONFIG_TCG
12820 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
12821 {
12822     g_assert_not_reached();
12823 }
12824 #endif
12825 
12826 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
12827 {
12828     ARMMMUIdx idx;
12829     uint64_t hcr;
12830 
12831     if (arm_feature(env, ARM_FEATURE_M)) {
12832         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
12833     }
12834 
12835     /* See ARM pseudo-function ELIsInHost.  */
12836     switch (el) {
12837     case 0:
12838         hcr = arm_hcr_el2_eff(env);
12839         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
12840             idx = ARMMMUIdx_E20_0;
12841         } else {
12842             idx = ARMMMUIdx_E10_0;
12843         }
12844         break;
12845     case 1:
12846         if (env->pstate & PSTATE_PAN) {
12847             idx = ARMMMUIdx_E10_1_PAN;
12848         } else {
12849             idx = ARMMMUIdx_E10_1;
12850         }
12851         break;
12852     case 2:
12853         /* Note that TGE does not apply at EL2.  */
12854         if (arm_hcr_el2_eff(env) & HCR_E2H) {
12855             if (env->pstate & PSTATE_PAN) {
12856                 idx = ARMMMUIdx_E20_2_PAN;
12857             } else {
12858                 idx = ARMMMUIdx_E20_2;
12859             }
12860         } else {
12861             idx = ARMMMUIdx_E2;
12862         }
12863         break;
12864     case 3:
12865         return ARMMMUIdx_SE3;
12866     default:
12867         g_assert_not_reached();
12868     }
12869 
12870     if (arm_is_secure_below_el3(env)) {
12871         idx &= ~ARM_MMU_IDX_A_NS;
12872     }
12873 
12874     return idx;
12875 }
12876 
12877 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
12878 {
12879     return arm_mmu_idx_el(env, arm_current_el(env));
12880 }
12881 
12882 #ifndef CONFIG_USER_ONLY
12883 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
12884 {
12885     return stage_1_mmu_idx(arm_mmu_idx(env));
12886 }
12887 #endif
12888 
12889 static uint32_t rebuild_hflags_common(CPUARMState *env, int fp_el,
12890                                       ARMMMUIdx mmu_idx, uint32_t flags)
12891 {
12892     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
12893     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX,
12894                        arm_to_core_mmu_idx(mmu_idx));
12895 
12896     if (arm_singlestep_active(env)) {
12897         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
12898     }
12899     return flags;
12900 }
12901 
12902 static uint32_t rebuild_hflags_common_32(CPUARMState *env, int fp_el,
12903                                          ARMMMUIdx mmu_idx, uint32_t flags)
12904 {
12905     bool sctlr_b = arm_sctlr_b(env);
12906 
12907     if (sctlr_b) {
12908         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, 1);
12909     }
12910     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
12911         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
12912     }
12913     flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
12914 
12915     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
12916 }
12917 
12918 static uint32_t rebuild_hflags_m32(CPUARMState *env, int fp_el,
12919                                    ARMMMUIdx mmu_idx)
12920 {
12921     uint32_t flags = 0;
12922 
12923     if (arm_v7m_is_handler_mode(env)) {
12924         flags = FIELD_DP32(flags, TBFLAG_M32, HANDLER, 1);
12925     }
12926 
12927     /*
12928      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
12929      * is suppressing them because the requested execution priority
12930      * is less than 0.
12931      */
12932     if (arm_feature(env, ARM_FEATURE_V8) &&
12933         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
12934           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
12935         flags = FIELD_DP32(flags, TBFLAG_M32, STACKCHECK, 1);
12936     }
12937 
12938     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
12939 }
12940 
12941 static uint32_t rebuild_hflags_aprofile(CPUARMState *env)
12942 {
12943     int flags = 0;
12944 
12945     flags = FIELD_DP32(flags, TBFLAG_ANY, DEBUG_TARGET_EL,
12946                        arm_debug_target_el(env));
12947     return flags;
12948 }
12949 
12950 static uint32_t rebuild_hflags_a32(CPUARMState *env, int fp_el,
12951                                    ARMMMUIdx mmu_idx)
12952 {
12953     uint32_t flags = rebuild_hflags_aprofile(env);
12954 
12955     if (arm_el_is_aa64(env, 1)) {
12956         flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
12957     }
12958 
12959     if (arm_current_el(env) < 2 && env->cp15.hstr_el2 &&
12960         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
12961         flags = FIELD_DP32(flags, TBFLAG_A32, HSTR_ACTIVE, 1);
12962     }
12963 
12964     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
12965 }
12966 
12967 static uint32_t rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
12968                                    ARMMMUIdx mmu_idx)
12969 {
12970     uint32_t flags = rebuild_hflags_aprofile(env);
12971     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
12972     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
12973     uint64_t sctlr;
12974     int tbii, tbid;
12975 
12976     flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
12977 
12978     /* Get control bits for tagged addresses.  */
12979     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
12980     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
12981 
12982     flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
12983     flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
12984 
12985     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
12986         int sve_el = sve_exception_el(env, el);
12987         uint32_t zcr_len;
12988 
12989         /*
12990          * If SVE is disabled, but FP is enabled,
12991          * then the effective len is 0.
12992          */
12993         if (sve_el != 0 && fp_el == 0) {
12994             zcr_len = 0;
12995         } else {
12996             zcr_len = sve_zcr_len_for_el(env, el);
12997         }
12998         flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
12999         flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
13000     }
13001 
13002     sctlr = regime_sctlr(env, stage1);
13003 
13004     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
13005         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
13006     }
13007 
13008     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
13009         /*
13010          * In order to save space in flags, we record only whether
13011          * pauth is "inactive", meaning all insns are implemented as
13012          * a nop, or "active" when some action must be performed.
13013          * The decision of which action to take is left to a helper.
13014          */
13015         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13016             flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
13017         }
13018     }
13019 
13020     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13021         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13022         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13023             flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
13024         }
13025     }
13026 
13027     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
13028     if (!(env->pstate & PSTATE_UAO)) {
13029         switch (mmu_idx) {
13030         case ARMMMUIdx_E10_1:
13031         case ARMMMUIdx_E10_1_PAN:
13032         case ARMMMUIdx_SE10_1:
13033         case ARMMMUIdx_SE10_1_PAN:
13034             /* TODO: ARMv8.3-NV */
13035             flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
13036             break;
13037         case ARMMMUIdx_E20_2:
13038         case ARMMMUIdx_E20_2_PAN:
13039         case ARMMMUIdx_SE20_2:
13040         case ARMMMUIdx_SE20_2_PAN:
13041             /*
13042              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
13043              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
13044              */
13045             if (env->cp15.hcr_el2 & HCR_TGE) {
13046                 flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
13047             }
13048             break;
13049         default:
13050             break;
13051         }
13052     }
13053 
13054     if (cpu_isar_feature(aa64_mte, env_archcpu(env))) {
13055         /*
13056          * Set MTE_ACTIVE if any access may be Checked, and leave clear
13057          * if all accesses must be Unchecked:
13058          * 1) If no TBI, then there are no tags in the address to check,
13059          * 2) If Tag Check Override, then all accesses are Unchecked,
13060          * 3) If Tag Check Fail == 0, then Checked access have no effect,
13061          * 4) If no Allocation Tag Access, then all accesses are Unchecked.
13062          */
13063         if (allocation_tag_access_enabled(env, el, sctlr)) {
13064             flags = FIELD_DP32(flags, TBFLAG_A64, ATA, 1);
13065             if (tbid
13066                 && !(env->pstate & PSTATE_TCO)
13067                 && (sctlr & (el == 0 ? SCTLR_TCF0 : SCTLR_TCF))) {
13068                 flags = FIELD_DP32(flags, TBFLAG_A64, MTE_ACTIVE, 1);
13069             }
13070         }
13071         /* And again for unprivileged accesses, if required.  */
13072         if (FIELD_EX32(flags, TBFLAG_A64, UNPRIV)
13073             && tbid
13074             && !(env->pstate & PSTATE_TCO)
13075             && (sctlr & SCTLR_TCF)
13076             && allocation_tag_access_enabled(env, 0, sctlr)) {
13077             flags = FIELD_DP32(flags, TBFLAG_A64, MTE0_ACTIVE, 1);
13078         }
13079         /* Cache TCMA as well as TBI. */
13080         flags = FIELD_DP32(flags, TBFLAG_A64, TCMA,
13081                            aa64_va_parameter_tcma(tcr, mmu_idx));
13082     }
13083 
13084     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13085 }
13086 
13087 static uint32_t rebuild_hflags_internal(CPUARMState *env)
13088 {
13089     int el = arm_current_el(env);
13090     int fp_el = fp_exception_el(env, el);
13091     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13092 
13093     if (is_a64(env)) {
13094         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13095     } else if (arm_feature(env, ARM_FEATURE_M)) {
13096         return rebuild_hflags_m32(env, fp_el, mmu_idx);
13097     } else {
13098         return rebuild_hflags_a32(env, fp_el, mmu_idx);
13099     }
13100 }
13101 
13102 void arm_rebuild_hflags(CPUARMState *env)
13103 {
13104     env->hflags = rebuild_hflags_internal(env);
13105 }
13106 
13107 /*
13108  * If we have triggered a EL state change we can't rely on the
13109  * translator having passed it to us, we need to recompute.
13110  */
13111 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
13112 {
13113     int el = arm_current_el(env);
13114     int fp_el = fp_exception_el(env, el);
13115     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13116     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13117 }
13118 
13119 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
13120 {
13121     int fp_el = fp_exception_el(env, el);
13122     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13123 
13124     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13125 }
13126 
13127 /*
13128  * If we have triggered a EL state change we can't rely on the
13129  * translator having passed it to us, we need to recompute.
13130  */
13131 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
13132 {
13133     int el = arm_current_el(env);
13134     int fp_el = fp_exception_el(env, el);
13135     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13136     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13137 }
13138 
13139 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
13140 {
13141     int fp_el = fp_exception_el(env, el);
13142     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13143 
13144     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13145 }
13146 
13147 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
13148 {
13149     int fp_el = fp_exception_el(env, el);
13150     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13151 
13152     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13153 }
13154 
13155 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
13156 {
13157 #ifdef CONFIG_DEBUG_TCG
13158     uint32_t env_flags_current = env->hflags;
13159     uint32_t env_flags_rebuilt = rebuild_hflags_internal(env);
13160 
13161     if (unlikely(env_flags_current != env_flags_rebuilt)) {
13162         fprintf(stderr, "TCG hflags mismatch (current:0x%08x rebuilt:0x%08x)\n",
13163                 env_flags_current, env_flags_rebuilt);
13164         abort();
13165     }
13166 #endif
13167 }
13168 
13169 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13170                           target_ulong *cs_base, uint32_t *pflags)
13171 {
13172     uint32_t flags = env->hflags;
13173     uint32_t pstate_for_ss;
13174 
13175     *cs_base = 0;
13176     assert_hflags_rebuild_correctly(env);
13177 
13178     if (FIELD_EX32(flags, TBFLAG_ANY, AARCH64_STATE)) {
13179         *pc = env->pc;
13180         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13181             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
13182         }
13183         pstate_for_ss = env->pstate;
13184     } else {
13185         *pc = env->regs[15];
13186 
13187         if (arm_feature(env, ARM_FEATURE_M)) {
13188             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13189                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
13190                 != env->v7m.secure) {
13191                 flags = FIELD_DP32(flags, TBFLAG_M32, FPCCR_S_WRONG, 1);
13192             }
13193 
13194             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13195                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13196                  (env->v7m.secure &&
13197                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13198                 /*
13199                  * ASPEN is set, but FPCA/SFPA indicate that there is no
13200                  * active FP context; we must create a new FP context before
13201                  * executing any FP insn.
13202                  */
13203                 flags = FIELD_DP32(flags, TBFLAG_M32, NEW_FP_CTXT_NEEDED, 1);
13204             }
13205 
13206             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13207             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13208                 flags = FIELD_DP32(flags, TBFLAG_M32, LSPACT, 1);
13209             }
13210         } else {
13211             /*
13212              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
13213              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
13214              */
13215             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13216                 flags = FIELD_DP32(flags, TBFLAG_A32,
13217                                    XSCALE_CPAR, env->cp15.c15_cpar);
13218             } else {
13219                 flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN,
13220                                    env->vfp.vec_len);
13221                 flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE,
13222                                    env->vfp.vec_stride);
13223             }
13224             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
13225                 flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
13226             }
13227         }
13228 
13229         flags = FIELD_DP32(flags, TBFLAG_AM32, THUMB, env->thumb);
13230         flags = FIELD_DP32(flags, TBFLAG_AM32, CONDEXEC, env->condexec_bits);
13231         pstate_for_ss = env->uncached_cpsr;
13232     }
13233 
13234     /*
13235      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13236      * states defined in the ARM ARM for software singlestep:
13237      *  SS_ACTIVE   PSTATE.SS   State
13238      *     0            x       Inactive (the TB flag for SS is always 0)
13239      *     1            0       Active-pending
13240      *     1            1       Active-not-pending
13241      * SS_ACTIVE is set in hflags; PSTATE_SS is computed every TB.
13242      */
13243     if (FIELD_EX32(flags, TBFLAG_ANY, SS_ACTIVE) &&
13244         (pstate_for_ss & PSTATE_SS)) {
13245         flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
13246     }
13247 
13248     *pflags = flags;
13249 }
13250 
13251 #ifdef TARGET_AARCH64
13252 /*
13253  * The manual says that when SVE is enabled and VQ is widened the
13254  * implementation is allowed to zero the previously inaccessible
13255  * portion of the registers.  The corollary to that is that when
13256  * SVE is enabled and VQ is narrowed we are also allowed to zero
13257  * the now inaccessible portion of the registers.
13258  *
13259  * The intent of this is that no predicate bit beyond VQ is ever set.
13260  * Which means that some operations on predicate registers themselves
13261  * may operate on full uint64_t or even unrolled across the maximum
13262  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13263  * may well be cheaper than conditionals to restrict the operation
13264  * to the relevant portion of a uint16_t[16].
13265  */
13266 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13267 {
13268     int i, j;
13269     uint64_t pmask;
13270 
13271     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13272     assert(vq <= env_archcpu(env)->sve_max_vq);
13273 
13274     /* Zap the high bits of the zregs.  */
13275     for (i = 0; i < 32; i++) {
13276         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13277     }
13278 
13279     /* Zap the high bits of the pregs and ffr.  */
13280     pmask = 0;
13281     if (vq & 3) {
13282         pmask = ~(-1ULL << (16 * (vq & 3)));
13283     }
13284     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13285         for (i = 0; i < 17; ++i) {
13286             env->vfp.pregs[i].p[j] &= pmask;
13287         }
13288         pmask = 0;
13289     }
13290 }
13291 
13292 /*
13293  * Notice a change in SVE vector size when changing EL.
13294  */
13295 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13296                            int new_el, bool el0_a64)
13297 {
13298     ARMCPU *cpu = env_archcpu(env);
13299     int old_len, new_len;
13300     bool old_a64, new_a64;
13301 
13302     /* Nothing to do if no SVE.  */
13303     if (!cpu_isar_feature(aa64_sve, cpu)) {
13304         return;
13305     }
13306 
13307     /* Nothing to do if FP is disabled in either EL.  */
13308     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13309         return;
13310     }
13311 
13312     /*
13313      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13314      * at ELx, or not available because the EL is in AArch32 state, then
13315      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13316      * has an effective value of 0".
13317      *
13318      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13319      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13320      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13321      * we already have the correct register contents when encountering the
13322      * vq0->vq0 transition between EL0->EL1.
13323      */
13324     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13325     old_len = (old_a64 && !sve_exception_el(env, old_el)
13326                ? sve_zcr_len_for_el(env, old_el) : 0);
13327     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13328     new_len = (new_a64 && !sve_exception_el(env, new_el)
13329                ? sve_zcr_len_for_el(env, new_el) : 0);
13330 
13331     /* When changing vector length, clear inaccessible state.  */
13332     if (new_len < old_len) {
13333         aarch64_sve_narrow_vq(env, new_len + 1);
13334     }
13335 }
13336 #endif
13337