xref: /qemu/target/arm/helper.c (revision 816f93b20045f3363a4bc1c31e5e7aebbb6c1087)
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 "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 "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     ARMCPU *cpu = env_archcpu(env);
1152 
1153     return (cpu->isar.reset_pmcr_el0 & PMCRN_MASK) >> PMCRN_SHIFT;
1154 }
1155 
1156 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1157 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1158 {
1159   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1160 }
1161 
1162 typedef struct pm_event {
1163     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1164     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1165     bool (*supported)(CPUARMState *);
1166     /*
1167      * Retrieve the current count of the underlying event. The programmed
1168      * counters hold a difference from the return value from this function
1169      */
1170     uint64_t (*get_count)(CPUARMState *);
1171     /*
1172      * Return how many nanoseconds it will take (at a minimum) for count events
1173      * to occur. A negative value indicates the counter will never overflow, or
1174      * that the counter has otherwise arranged for the overflow bit to be set
1175      * and the PMU interrupt to be raised on overflow.
1176      */
1177     int64_t (*ns_per_count)(uint64_t);
1178 } pm_event;
1179 
1180 static bool event_always_supported(CPUARMState *env)
1181 {
1182     return true;
1183 }
1184 
1185 static uint64_t swinc_get_count(CPUARMState *env)
1186 {
1187     /*
1188      * SW_INCR events are written directly to the pmevcntr's by writes to
1189      * PMSWINC, so there is no underlying count maintained by the PMU itself
1190      */
1191     return 0;
1192 }
1193 
1194 static int64_t swinc_ns_per(uint64_t ignored)
1195 {
1196     return -1;
1197 }
1198 
1199 /*
1200  * Return the underlying cycle count for the PMU cycle counters. If we're in
1201  * usermode, simply return 0.
1202  */
1203 static uint64_t cycles_get_count(CPUARMState *env)
1204 {
1205 #ifndef CONFIG_USER_ONLY
1206     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1207                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1208 #else
1209     return cpu_get_host_ticks();
1210 #endif
1211 }
1212 
1213 #ifndef CONFIG_USER_ONLY
1214 static int64_t cycles_ns_per(uint64_t cycles)
1215 {
1216     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1217 }
1218 
1219 static bool instructions_supported(CPUARMState *env)
1220 {
1221     return icount_enabled() == 1; /* Precise instruction counting */
1222 }
1223 
1224 static uint64_t instructions_get_count(CPUARMState *env)
1225 {
1226     return (uint64_t)icount_get_raw();
1227 }
1228 
1229 static int64_t instructions_ns_per(uint64_t icount)
1230 {
1231     return icount_to_ns((int64_t)icount);
1232 }
1233 #endif
1234 
1235 static bool pmu_8_1_events_supported(CPUARMState *env)
1236 {
1237     /* For events which are supported in any v8.1 PMU */
1238     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
1239 }
1240 
1241 static bool pmu_8_4_events_supported(CPUARMState *env)
1242 {
1243     /* For events which are supported in any v8.1 PMU */
1244     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
1245 }
1246 
1247 static uint64_t zero_event_get_count(CPUARMState *env)
1248 {
1249     /* For events which on QEMU never fire, so their count is always zero */
1250     return 0;
1251 }
1252 
1253 static int64_t zero_event_ns_per(uint64_t cycles)
1254 {
1255     /* An event which never fires can never overflow */
1256     return -1;
1257 }
1258 
1259 static const pm_event pm_events[] = {
1260     { .number = 0x000, /* SW_INCR */
1261       .supported = event_always_supported,
1262       .get_count = swinc_get_count,
1263       .ns_per_count = swinc_ns_per,
1264     },
1265 #ifndef CONFIG_USER_ONLY
1266     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1267       .supported = instructions_supported,
1268       .get_count = instructions_get_count,
1269       .ns_per_count = instructions_ns_per,
1270     },
1271     { .number = 0x011, /* CPU_CYCLES, Cycle */
1272       .supported = event_always_supported,
1273       .get_count = cycles_get_count,
1274       .ns_per_count = cycles_ns_per,
1275     },
1276 #endif
1277     { .number = 0x023, /* STALL_FRONTEND */
1278       .supported = pmu_8_1_events_supported,
1279       .get_count = zero_event_get_count,
1280       .ns_per_count = zero_event_ns_per,
1281     },
1282     { .number = 0x024, /* STALL_BACKEND */
1283       .supported = pmu_8_1_events_supported,
1284       .get_count = zero_event_get_count,
1285       .ns_per_count = zero_event_ns_per,
1286     },
1287     { .number = 0x03c, /* STALL */
1288       .supported = pmu_8_4_events_supported,
1289       .get_count = zero_event_get_count,
1290       .ns_per_count = zero_event_ns_per,
1291     },
1292 };
1293 
1294 /*
1295  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1296  * events (i.e. the statistical profiling extension), this implementation
1297  * should first be updated to something sparse instead of the current
1298  * supported_event_map[] array.
1299  */
1300 #define MAX_EVENT_ID 0x3c
1301 #define UNSUPPORTED_EVENT UINT16_MAX
1302 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1303 
1304 /*
1305  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1306  * of ARM event numbers to indices in our pm_events array.
1307  *
1308  * Note: Events in the 0x40XX range are not currently supported.
1309  */
1310 void pmu_init(ARMCPU *cpu)
1311 {
1312     unsigned int i;
1313 
1314     /*
1315      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1316      * events to them
1317      */
1318     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1319         supported_event_map[i] = UNSUPPORTED_EVENT;
1320     }
1321     cpu->pmceid0 = 0;
1322     cpu->pmceid1 = 0;
1323 
1324     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1325         const pm_event *cnt = &pm_events[i];
1326         assert(cnt->number <= MAX_EVENT_ID);
1327         /* We do not currently support events in the 0x40xx range */
1328         assert(cnt->number <= 0x3f);
1329 
1330         if (cnt->supported(&cpu->env)) {
1331             supported_event_map[cnt->number] = i;
1332             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1333             if (cnt->number & 0x20) {
1334                 cpu->pmceid1 |= event_mask;
1335             } else {
1336                 cpu->pmceid0 |= event_mask;
1337             }
1338         }
1339     }
1340 }
1341 
1342 /*
1343  * Check at runtime whether a PMU event is supported for the current machine
1344  */
1345 static bool event_supported(uint16_t number)
1346 {
1347     if (number > MAX_EVENT_ID) {
1348         return false;
1349     }
1350     return supported_event_map[number] != UNSUPPORTED_EVENT;
1351 }
1352 
1353 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1354                                    bool isread)
1355 {
1356     /* Performance monitor registers user accessibility is controlled
1357      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1358      * trapping to EL2 or EL3 for other accesses.
1359      */
1360     int el = arm_current_el(env);
1361     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1362 
1363     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1364         return CP_ACCESS_TRAP;
1365     }
1366     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
1367         return CP_ACCESS_TRAP_EL2;
1368     }
1369     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1370         return CP_ACCESS_TRAP_EL3;
1371     }
1372 
1373     return CP_ACCESS_OK;
1374 }
1375 
1376 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1377                                            const ARMCPRegInfo *ri,
1378                                            bool isread)
1379 {
1380     /* ER: event counter read trap control */
1381     if (arm_feature(env, ARM_FEATURE_V8)
1382         && arm_current_el(env) == 0
1383         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1384         && isread) {
1385         return CP_ACCESS_OK;
1386     }
1387 
1388     return pmreg_access(env, ri, isread);
1389 }
1390 
1391 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1392                                          const ARMCPRegInfo *ri,
1393                                          bool isread)
1394 {
1395     /* SW: software increment write trap control */
1396     if (arm_feature(env, ARM_FEATURE_V8)
1397         && arm_current_el(env) == 0
1398         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1399         && !isread) {
1400         return CP_ACCESS_OK;
1401     }
1402 
1403     return pmreg_access(env, ri, isread);
1404 }
1405 
1406 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1407                                         const ARMCPRegInfo *ri,
1408                                         bool isread)
1409 {
1410     /* ER: event counter read trap control */
1411     if (arm_feature(env, ARM_FEATURE_V8)
1412         && arm_current_el(env) == 0
1413         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1414         return CP_ACCESS_OK;
1415     }
1416 
1417     return pmreg_access(env, ri, isread);
1418 }
1419 
1420 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1421                                          const ARMCPRegInfo *ri,
1422                                          bool isread)
1423 {
1424     /* CR: cycle counter read trap control */
1425     if (arm_feature(env, ARM_FEATURE_V8)
1426         && arm_current_el(env) == 0
1427         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1428         && isread) {
1429         return CP_ACCESS_OK;
1430     }
1431 
1432     return pmreg_access(env, ri, isread);
1433 }
1434 
1435 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1436  * the current EL, security state, and register configuration.
1437  */
1438 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1439 {
1440     uint64_t filter;
1441     bool e, p, u, nsk, nsu, nsh, m;
1442     bool enabled, prohibited, filtered;
1443     bool secure = arm_is_secure(env);
1444     int el = arm_current_el(env);
1445     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1446     uint8_t hpmn = mdcr_el2 & MDCR_HPMN;
1447 
1448     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1449         return false;
1450     }
1451 
1452     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1453             (counter < hpmn || counter == 31)) {
1454         e = env->cp15.c9_pmcr & PMCRE;
1455     } else {
1456         e = mdcr_el2 & MDCR_HPME;
1457     }
1458     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1459 
1460     if (!secure) {
1461         if (el == 2 && (counter < hpmn || counter == 31)) {
1462             prohibited = mdcr_el2 & MDCR_HPMD;
1463         } else {
1464             prohibited = false;
1465         }
1466     } else {
1467         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1468            !(env->cp15.mdcr_el3 & MDCR_SPME);
1469     }
1470 
1471     if (prohibited && counter == 31) {
1472         prohibited = env->cp15.c9_pmcr & PMCRDP;
1473     }
1474 
1475     if (counter == 31) {
1476         filter = env->cp15.pmccfiltr_el0;
1477     } else {
1478         filter = env->cp15.c14_pmevtyper[counter];
1479     }
1480 
1481     p   = filter & PMXEVTYPER_P;
1482     u   = filter & PMXEVTYPER_U;
1483     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1484     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1485     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1486     m   = arm_el_is_aa64(env, 1) &&
1487               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1488 
1489     if (el == 0) {
1490         filtered = secure ? u : u != nsu;
1491     } else if (el == 1) {
1492         filtered = secure ? p : p != nsk;
1493     } else if (el == 2) {
1494         filtered = !nsh;
1495     } else { /* EL3 */
1496         filtered = m != p;
1497     }
1498 
1499     if (counter != 31) {
1500         /*
1501          * If not checking PMCCNTR, ensure the counter is setup to an event we
1502          * support
1503          */
1504         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1505         if (!event_supported(event)) {
1506             return false;
1507         }
1508     }
1509 
1510     return enabled && !prohibited && !filtered;
1511 }
1512 
1513 static void pmu_update_irq(CPUARMState *env)
1514 {
1515     ARMCPU *cpu = env_archcpu(env);
1516     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1517             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1518 }
1519 
1520 /*
1521  * Ensure c15_ccnt is the guest-visible count so that operations such as
1522  * enabling/disabling the counter or filtering, modifying the count itself,
1523  * etc. can be done logically. This is essentially a no-op if the counter is
1524  * not enabled at the time of the call.
1525  */
1526 static void pmccntr_op_start(CPUARMState *env)
1527 {
1528     uint64_t cycles = cycles_get_count(env);
1529 
1530     if (pmu_counter_enabled(env, 31)) {
1531         uint64_t eff_cycles = cycles;
1532         if (env->cp15.c9_pmcr & PMCRD) {
1533             /* Increment once every 64 processor clock cycles */
1534             eff_cycles /= 64;
1535         }
1536 
1537         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1538 
1539         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1540                                  1ull << 63 : 1ull << 31;
1541         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1542             env->cp15.c9_pmovsr |= (1 << 31);
1543             pmu_update_irq(env);
1544         }
1545 
1546         env->cp15.c15_ccnt = new_pmccntr;
1547     }
1548     env->cp15.c15_ccnt_delta = cycles;
1549 }
1550 
1551 /*
1552  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1553  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1554  * pmccntr_op_start.
1555  */
1556 static void pmccntr_op_finish(CPUARMState *env)
1557 {
1558     if (pmu_counter_enabled(env, 31)) {
1559 #ifndef CONFIG_USER_ONLY
1560         /* Calculate when the counter will next overflow */
1561         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1562         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1563             remaining_cycles = (uint32_t)remaining_cycles;
1564         }
1565         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1566 
1567         if (overflow_in > 0) {
1568             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1569                 overflow_in;
1570             ARMCPU *cpu = env_archcpu(env);
1571             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1572         }
1573 #endif
1574 
1575         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1576         if (env->cp15.c9_pmcr & PMCRD) {
1577             /* Increment once every 64 processor clock cycles */
1578             prev_cycles /= 64;
1579         }
1580         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1581     }
1582 }
1583 
1584 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1585 {
1586 
1587     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1588     uint64_t count = 0;
1589     if (event_supported(event)) {
1590         uint16_t event_idx = supported_event_map[event];
1591         count = pm_events[event_idx].get_count(env);
1592     }
1593 
1594     if (pmu_counter_enabled(env, counter)) {
1595         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1596 
1597         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1598             env->cp15.c9_pmovsr |= (1 << counter);
1599             pmu_update_irq(env);
1600         }
1601         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1602     }
1603     env->cp15.c14_pmevcntr_delta[counter] = count;
1604 }
1605 
1606 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1607 {
1608     if (pmu_counter_enabled(env, counter)) {
1609 #ifndef CONFIG_USER_ONLY
1610         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1611         uint16_t event_idx = supported_event_map[event];
1612         uint64_t delta = UINT32_MAX -
1613             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1614         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1615 
1616         if (overflow_in > 0) {
1617             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1618                 overflow_in;
1619             ARMCPU *cpu = env_archcpu(env);
1620             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1621         }
1622 #endif
1623 
1624         env->cp15.c14_pmevcntr_delta[counter] -=
1625             env->cp15.c14_pmevcntr[counter];
1626     }
1627 }
1628 
1629 void pmu_op_start(CPUARMState *env)
1630 {
1631     unsigned int i;
1632     pmccntr_op_start(env);
1633     for (i = 0; i < pmu_num_counters(env); i++) {
1634         pmevcntr_op_start(env, i);
1635     }
1636 }
1637 
1638 void pmu_op_finish(CPUARMState *env)
1639 {
1640     unsigned int i;
1641     pmccntr_op_finish(env);
1642     for (i = 0; i < pmu_num_counters(env); i++) {
1643         pmevcntr_op_finish(env, i);
1644     }
1645 }
1646 
1647 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1648 {
1649     pmu_op_start(&cpu->env);
1650 }
1651 
1652 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1653 {
1654     pmu_op_finish(&cpu->env);
1655 }
1656 
1657 void arm_pmu_timer_cb(void *opaque)
1658 {
1659     ARMCPU *cpu = opaque;
1660 
1661     /*
1662      * Update all the counter values based on the current underlying counts,
1663      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1664      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1665      * counter may expire.
1666      */
1667     pmu_op_start(&cpu->env);
1668     pmu_op_finish(&cpu->env);
1669 }
1670 
1671 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1672                        uint64_t value)
1673 {
1674     pmu_op_start(env);
1675 
1676     if (value & PMCRC) {
1677         /* The counter has been reset */
1678         env->cp15.c15_ccnt = 0;
1679     }
1680 
1681     if (value & PMCRP) {
1682         unsigned int i;
1683         for (i = 0; i < pmu_num_counters(env); i++) {
1684             env->cp15.c14_pmevcntr[i] = 0;
1685         }
1686     }
1687 
1688     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1689     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1690 
1691     pmu_op_finish(env);
1692 }
1693 
1694 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1695                           uint64_t value)
1696 {
1697     unsigned int i;
1698     for (i = 0; i < pmu_num_counters(env); i++) {
1699         /* Increment a counter's count iff: */
1700         if ((value & (1 << i)) && /* counter's bit is set */
1701                 /* counter is enabled and not filtered */
1702                 pmu_counter_enabled(env, i) &&
1703                 /* counter is SW_INCR */
1704                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1705             pmevcntr_op_start(env, i);
1706 
1707             /*
1708              * Detect if this write causes an overflow since we can't predict
1709              * PMSWINC overflows like we can for other events
1710              */
1711             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1712 
1713             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1714                 env->cp15.c9_pmovsr |= (1 << i);
1715                 pmu_update_irq(env);
1716             }
1717 
1718             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1719 
1720             pmevcntr_op_finish(env, i);
1721         }
1722     }
1723 }
1724 
1725 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1726 {
1727     uint64_t ret;
1728     pmccntr_op_start(env);
1729     ret = env->cp15.c15_ccnt;
1730     pmccntr_op_finish(env);
1731     return ret;
1732 }
1733 
1734 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1735                          uint64_t value)
1736 {
1737     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1738      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1739      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1740      * accessed.
1741      */
1742     env->cp15.c9_pmselr = value & 0x1f;
1743 }
1744 
1745 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1746                         uint64_t value)
1747 {
1748     pmccntr_op_start(env);
1749     env->cp15.c15_ccnt = value;
1750     pmccntr_op_finish(env);
1751 }
1752 
1753 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1754                             uint64_t value)
1755 {
1756     uint64_t cur_val = pmccntr_read(env, NULL);
1757 
1758     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1759 }
1760 
1761 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1762                             uint64_t value)
1763 {
1764     pmccntr_op_start(env);
1765     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1766     pmccntr_op_finish(env);
1767 }
1768 
1769 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1770                             uint64_t value)
1771 {
1772     pmccntr_op_start(env);
1773     /* M is not accessible from AArch32 */
1774     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1775         (value & PMCCFILTR);
1776     pmccntr_op_finish(env);
1777 }
1778 
1779 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1780 {
1781     /* M is not visible in AArch32 */
1782     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1783 }
1784 
1785 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1786                             uint64_t value)
1787 {
1788     value &= pmu_counter_mask(env);
1789     env->cp15.c9_pmcnten |= value;
1790 }
1791 
1792 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1793                              uint64_t value)
1794 {
1795     value &= pmu_counter_mask(env);
1796     env->cp15.c9_pmcnten &= ~value;
1797 }
1798 
1799 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1800                          uint64_t value)
1801 {
1802     value &= pmu_counter_mask(env);
1803     env->cp15.c9_pmovsr &= ~value;
1804     pmu_update_irq(env);
1805 }
1806 
1807 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1808                          uint64_t value)
1809 {
1810     value &= pmu_counter_mask(env);
1811     env->cp15.c9_pmovsr |= value;
1812     pmu_update_irq(env);
1813 }
1814 
1815 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1816                              uint64_t value, const uint8_t counter)
1817 {
1818     if (counter == 31) {
1819         pmccfiltr_write(env, ri, value);
1820     } else if (counter < pmu_num_counters(env)) {
1821         pmevcntr_op_start(env, counter);
1822 
1823         /*
1824          * If this counter's event type is changing, store the current
1825          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1826          * pmevcntr_op_finish has the correct baseline when it converts back to
1827          * a delta.
1828          */
1829         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1830             PMXEVTYPER_EVTCOUNT;
1831         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1832         if (old_event != new_event) {
1833             uint64_t count = 0;
1834             if (event_supported(new_event)) {
1835                 uint16_t event_idx = supported_event_map[new_event];
1836                 count = pm_events[event_idx].get_count(env);
1837             }
1838             env->cp15.c14_pmevcntr_delta[counter] = count;
1839         }
1840 
1841         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1842         pmevcntr_op_finish(env, counter);
1843     }
1844     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1845      * PMSELR value is equal to or greater than the number of implemented
1846      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1847      */
1848 }
1849 
1850 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1851                                const uint8_t counter)
1852 {
1853     if (counter == 31) {
1854         return env->cp15.pmccfiltr_el0;
1855     } else if (counter < pmu_num_counters(env)) {
1856         return env->cp15.c14_pmevtyper[counter];
1857     } else {
1858       /*
1859        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1860        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1861        */
1862         return 0;
1863     }
1864 }
1865 
1866 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1867                               uint64_t value)
1868 {
1869     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1870     pmevtyper_write(env, ri, value, counter);
1871 }
1872 
1873 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1874                                uint64_t value)
1875 {
1876     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1877     env->cp15.c14_pmevtyper[counter] = value;
1878 
1879     /*
1880      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1881      * pmu_op_finish calls when loading saved state for a migration. Because
1882      * we're potentially updating the type of event here, the value written to
1883      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1884      * different counter type. Therefore, we need to set this value to the
1885      * current count for the counter type we're writing so that pmu_op_finish
1886      * has the correct count for its calculation.
1887      */
1888     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1889     if (event_supported(event)) {
1890         uint16_t event_idx = supported_event_map[event];
1891         env->cp15.c14_pmevcntr_delta[counter] =
1892             pm_events[event_idx].get_count(env);
1893     }
1894 }
1895 
1896 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1897 {
1898     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1899     return pmevtyper_read(env, ri, counter);
1900 }
1901 
1902 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1903                              uint64_t value)
1904 {
1905     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1906 }
1907 
1908 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1909 {
1910     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1911 }
1912 
1913 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1914                              uint64_t value, uint8_t counter)
1915 {
1916     if (counter < pmu_num_counters(env)) {
1917         pmevcntr_op_start(env, counter);
1918         env->cp15.c14_pmevcntr[counter] = value;
1919         pmevcntr_op_finish(env, counter);
1920     }
1921     /*
1922      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1923      * are CONSTRAINED UNPREDICTABLE.
1924      */
1925 }
1926 
1927 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1928                               uint8_t counter)
1929 {
1930     if (counter < pmu_num_counters(env)) {
1931         uint64_t ret;
1932         pmevcntr_op_start(env, counter);
1933         ret = env->cp15.c14_pmevcntr[counter];
1934         pmevcntr_op_finish(env, counter);
1935         return ret;
1936     } else {
1937       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1938        * are CONSTRAINED UNPREDICTABLE. */
1939         return 0;
1940     }
1941 }
1942 
1943 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1944                              uint64_t value)
1945 {
1946     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1947     pmevcntr_write(env, ri, value, counter);
1948 }
1949 
1950 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1951 {
1952     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1953     return pmevcntr_read(env, ri, counter);
1954 }
1955 
1956 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1957                              uint64_t value)
1958 {
1959     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1960     assert(counter < pmu_num_counters(env));
1961     env->cp15.c14_pmevcntr[counter] = value;
1962     pmevcntr_write(env, ri, value, counter);
1963 }
1964 
1965 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1966 {
1967     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1968     assert(counter < pmu_num_counters(env));
1969     return env->cp15.c14_pmevcntr[counter];
1970 }
1971 
1972 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1973                              uint64_t value)
1974 {
1975     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1976 }
1977 
1978 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1979 {
1980     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1981 }
1982 
1983 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1984                             uint64_t value)
1985 {
1986     if (arm_feature(env, ARM_FEATURE_V8)) {
1987         env->cp15.c9_pmuserenr = value & 0xf;
1988     } else {
1989         env->cp15.c9_pmuserenr = value & 1;
1990     }
1991 }
1992 
1993 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1994                              uint64_t value)
1995 {
1996     /* We have no event counters so only the C bit can be changed */
1997     value &= pmu_counter_mask(env);
1998     env->cp15.c9_pminten |= value;
1999     pmu_update_irq(env);
2000 }
2001 
2002 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2003                              uint64_t value)
2004 {
2005     value &= pmu_counter_mask(env);
2006     env->cp15.c9_pminten &= ~value;
2007     pmu_update_irq(env);
2008 }
2009 
2010 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
2011                        uint64_t value)
2012 {
2013     /* Note that even though the AArch64 view of this register has bits
2014      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
2015      * architectural requirements for bits which are RES0 only in some
2016      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
2017      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
2018      */
2019     raw_write(env, ri, value & ~0x1FULL);
2020 }
2021 
2022 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2023 {
2024     /* Begin with base v8.0 state.  */
2025     uint32_t valid_mask = 0x3fff;
2026     ARMCPU *cpu = env_archcpu(env);
2027 
2028     if (ri->state == ARM_CP_STATE_AA64) {
2029         if (arm_feature(env, ARM_FEATURE_AARCH64) &&
2030             !cpu_isar_feature(aa64_aa32_el1, cpu)) {
2031                 value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
2032         }
2033         valid_mask &= ~SCR_NET;
2034 
2035         if (cpu_isar_feature(aa64_lor, cpu)) {
2036             valid_mask |= SCR_TLOR;
2037         }
2038         if (cpu_isar_feature(aa64_pauth, cpu)) {
2039             valid_mask |= SCR_API | SCR_APK;
2040         }
2041         if (cpu_isar_feature(aa64_sel2, cpu)) {
2042             valid_mask |= SCR_EEL2;
2043         }
2044         if (cpu_isar_feature(aa64_mte, cpu)) {
2045             valid_mask |= SCR_ATA;
2046         }
2047     } else {
2048         valid_mask &= ~(SCR_RW | SCR_ST);
2049     }
2050 
2051     if (!arm_feature(env, ARM_FEATURE_EL2)) {
2052         valid_mask &= ~SCR_HCE;
2053 
2054         /* On ARMv7, SMD (or SCD as it is called in v7) is only
2055          * supported if EL2 exists. The bit is UNK/SBZP when
2056          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
2057          * when EL2 is unavailable.
2058          * On ARMv8, this bit is always available.
2059          */
2060         if (arm_feature(env, ARM_FEATURE_V7) &&
2061             !arm_feature(env, ARM_FEATURE_V8)) {
2062             valid_mask &= ~SCR_SMD;
2063         }
2064     }
2065 
2066     /* Clear all-context RES0 bits.  */
2067     value &= valid_mask;
2068     raw_write(env, ri, value);
2069 }
2070 
2071 static void scr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2072 {
2073     /*
2074      * scr_write will set the RES1 bits on an AArch64-only CPU.
2075      * The reset value will be 0x30 on an AArch64-only CPU and 0 otherwise.
2076      */
2077     scr_write(env, ri, 0);
2078 }
2079 
2080 static CPAccessResult access_aa64_tid2(CPUARMState *env,
2081                                        const ARMCPRegInfo *ri,
2082                                        bool isread)
2083 {
2084     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
2085         return CP_ACCESS_TRAP_EL2;
2086     }
2087 
2088     return CP_ACCESS_OK;
2089 }
2090 
2091 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2092 {
2093     ARMCPU *cpu = env_archcpu(env);
2094 
2095     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
2096      * bank
2097      */
2098     uint32_t index = A32_BANKED_REG_GET(env, csselr,
2099                                         ri->secure & ARM_CP_SECSTATE_S);
2100 
2101     return cpu->ccsidr[index];
2102 }
2103 
2104 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2105                          uint64_t value)
2106 {
2107     raw_write(env, ri, value & 0xf);
2108 }
2109 
2110 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2111 {
2112     CPUState *cs = env_cpu(env);
2113     bool el1 = arm_current_el(env) == 1;
2114     uint64_t hcr_el2 = el1 ? arm_hcr_el2_eff(env) : 0;
2115     uint64_t ret = 0;
2116 
2117     if (hcr_el2 & HCR_IMO) {
2118         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
2119             ret |= CPSR_I;
2120         }
2121     } else {
2122         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
2123             ret |= CPSR_I;
2124         }
2125     }
2126 
2127     if (hcr_el2 & HCR_FMO) {
2128         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
2129             ret |= CPSR_F;
2130         }
2131     } else {
2132         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
2133             ret |= CPSR_F;
2134         }
2135     }
2136 
2137     /* External aborts are not possible in QEMU so A bit is always clear */
2138     return ret;
2139 }
2140 
2141 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2142                                        bool isread)
2143 {
2144     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
2145         return CP_ACCESS_TRAP_EL2;
2146     }
2147 
2148     return CP_ACCESS_OK;
2149 }
2150 
2151 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2152                                        bool isread)
2153 {
2154     if (arm_feature(env, ARM_FEATURE_V8)) {
2155         return access_aa64_tid1(env, ri, isread);
2156     }
2157 
2158     return CP_ACCESS_OK;
2159 }
2160 
2161 static const ARMCPRegInfo v7_cp_reginfo[] = {
2162     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
2163     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
2164       .access = PL1_W, .type = ARM_CP_NOP },
2165     /* Performance monitors are implementation defined in v7,
2166      * but with an ARM recommended set of registers, which we
2167      * follow.
2168      *
2169      * Performance registers fall into three categories:
2170      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
2171      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
2172      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
2173      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
2174      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
2175      */
2176     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
2177       .access = PL0_RW, .type = ARM_CP_ALIAS,
2178       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2179       .writefn = pmcntenset_write,
2180       .accessfn = pmreg_access,
2181       .raw_writefn = raw_write },
2182     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
2183       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
2184       .access = PL0_RW, .accessfn = pmreg_access,
2185       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
2186       .writefn = pmcntenset_write, .raw_writefn = raw_write },
2187     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
2188       .access = PL0_RW,
2189       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2190       .accessfn = pmreg_access,
2191       .writefn = pmcntenclr_write,
2192       .type = ARM_CP_ALIAS },
2193     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
2194       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
2195       .access = PL0_RW, .accessfn = pmreg_access,
2196       .type = ARM_CP_ALIAS,
2197       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
2198       .writefn = pmcntenclr_write },
2199     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
2200       .access = PL0_RW, .type = ARM_CP_IO,
2201       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2202       .accessfn = pmreg_access,
2203       .writefn = pmovsr_write,
2204       .raw_writefn = raw_write },
2205     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2206       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2207       .access = PL0_RW, .accessfn = pmreg_access,
2208       .type = ARM_CP_ALIAS | ARM_CP_IO,
2209       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2210       .writefn = pmovsr_write,
2211       .raw_writefn = raw_write },
2212     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2213       .access = PL0_W, .accessfn = pmreg_access_swinc,
2214       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2215       .writefn = pmswinc_write },
2216     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2217       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2218       .access = PL0_W, .accessfn = pmreg_access_swinc,
2219       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2220       .writefn = pmswinc_write },
2221     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2222       .access = PL0_RW, .type = ARM_CP_ALIAS,
2223       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2224       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2225       .raw_writefn = raw_write},
2226     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2227       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2228       .access = PL0_RW, .accessfn = pmreg_access_selr,
2229       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2230       .writefn = pmselr_write, .raw_writefn = raw_write, },
2231     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2232       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2233       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2234       .accessfn = pmreg_access_ccntr },
2235     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2236       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2237       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2238       .type = ARM_CP_IO,
2239       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2240       .readfn = pmccntr_read, .writefn = pmccntr_write,
2241       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2242     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2243       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2244       .access = PL0_RW, .accessfn = pmreg_access,
2245       .type = ARM_CP_ALIAS | ARM_CP_IO,
2246       .resetvalue = 0, },
2247     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2248       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2249       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2250       .access = PL0_RW, .accessfn = pmreg_access,
2251       .type = ARM_CP_IO,
2252       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2253       .resetvalue = 0, },
2254     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2255       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2256       .accessfn = pmreg_access,
2257       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2258     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2259       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2260       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2261       .accessfn = pmreg_access,
2262       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2263     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2264       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2265       .accessfn = pmreg_access_xevcntr,
2266       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2267     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2268       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2269       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2270       .accessfn = pmreg_access_xevcntr,
2271       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2272     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2273       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2274       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2275       .resetvalue = 0,
2276       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2277     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2278       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2279       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2280       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2281       .resetvalue = 0,
2282       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2283     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2284       .access = PL1_RW, .accessfn = access_tpm,
2285       .type = ARM_CP_ALIAS | ARM_CP_IO,
2286       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2287       .resetvalue = 0,
2288       .writefn = pmintenset_write, .raw_writefn = raw_write },
2289     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2290       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2291       .access = PL1_RW, .accessfn = access_tpm,
2292       .type = ARM_CP_IO,
2293       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2294       .writefn = pmintenset_write, .raw_writefn = raw_write,
2295       .resetvalue = 0x0 },
2296     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2297       .access = PL1_RW, .accessfn = access_tpm,
2298       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2299       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2300       .writefn = pmintenclr_write, },
2301     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2302       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2303       .access = PL1_RW, .accessfn = access_tpm,
2304       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2305       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2306       .writefn = pmintenclr_write },
2307     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2308       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2309       .access = PL1_R,
2310       .accessfn = access_aa64_tid2,
2311       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2312     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2313       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2314       .access = PL1_RW,
2315       .accessfn = access_aa64_tid2,
2316       .writefn = csselr_write, .resetvalue = 0,
2317       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2318                              offsetof(CPUARMState, cp15.csselr_ns) } },
2319     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2320      * just RAZ for all cores:
2321      */
2322     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2323       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2324       .access = PL1_R, .type = ARM_CP_CONST,
2325       .accessfn = access_aa64_tid1,
2326       .resetvalue = 0 },
2327     /* Auxiliary fault status registers: these also are IMPDEF, and we
2328      * choose to RAZ/WI for all cores.
2329      */
2330     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2331       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2332       .access = PL1_RW, .accessfn = access_tvm_trvm,
2333       .type = ARM_CP_CONST, .resetvalue = 0 },
2334     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2335       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2336       .access = PL1_RW, .accessfn = access_tvm_trvm,
2337       .type = ARM_CP_CONST, .resetvalue = 0 },
2338     /* MAIR can just read-as-written because we don't implement caches
2339      * and so don't need to care about memory attributes.
2340      */
2341     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2342       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2343       .access = PL1_RW, .accessfn = access_tvm_trvm,
2344       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2345       .resetvalue = 0 },
2346     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2347       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2348       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2349       .resetvalue = 0 },
2350     /* For non-long-descriptor page tables these are PRRR and NMRR;
2351      * regardless they still act as reads-as-written for QEMU.
2352      */
2353      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2354       * allows them to assign the correct fieldoffset based on the endianness
2355       * handled in the field definitions.
2356       */
2357     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2358       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2359       .access = PL1_RW, .accessfn = access_tvm_trvm,
2360       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2361                              offsetof(CPUARMState, cp15.mair0_ns) },
2362       .resetfn = arm_cp_reset_ignore },
2363     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2364       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2365       .access = PL1_RW, .accessfn = access_tvm_trvm,
2366       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2367                              offsetof(CPUARMState, cp15.mair1_ns) },
2368       .resetfn = arm_cp_reset_ignore },
2369     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2370       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2371       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2372     /* 32 bit ITLB invalidates */
2373     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2374       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2375       .writefn = tlbiall_write },
2376     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2377       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2378       .writefn = tlbimva_write },
2379     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2380       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2381       .writefn = tlbiasid_write },
2382     /* 32 bit DTLB invalidates */
2383     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2384       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2385       .writefn = tlbiall_write },
2386     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2387       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2388       .writefn = tlbimva_write },
2389     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2390       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2391       .writefn = tlbiasid_write },
2392     /* 32 bit TLB invalidates */
2393     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2394       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2395       .writefn = tlbiall_write },
2396     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2397       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2398       .writefn = tlbimva_write },
2399     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2400       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2401       .writefn = tlbiasid_write },
2402     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2403       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2404       .writefn = tlbimvaa_write },
2405     REGINFO_SENTINEL
2406 };
2407 
2408 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2409     /* 32 bit TLB invalidates, Inner Shareable */
2410     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2411       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2412       .writefn = tlbiall_is_write },
2413     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2414       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2415       .writefn = tlbimva_is_write },
2416     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2417       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2418       .writefn = tlbiasid_is_write },
2419     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2420       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2421       .writefn = tlbimvaa_is_write },
2422     REGINFO_SENTINEL
2423 };
2424 
2425 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2426     /* PMOVSSET is not implemented in v7 before v7ve */
2427     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2428       .access = PL0_RW, .accessfn = pmreg_access,
2429       .type = ARM_CP_ALIAS | ARM_CP_IO,
2430       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2431       .writefn = pmovsset_write,
2432       .raw_writefn = raw_write },
2433     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2434       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2435       .access = PL0_RW, .accessfn = pmreg_access,
2436       .type = ARM_CP_ALIAS | ARM_CP_IO,
2437       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2438       .writefn = pmovsset_write,
2439       .raw_writefn = raw_write },
2440     REGINFO_SENTINEL
2441 };
2442 
2443 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2444                         uint64_t value)
2445 {
2446     value &= 1;
2447     env->teecr = value;
2448 }
2449 
2450 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2451                                     bool isread)
2452 {
2453     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2454         return CP_ACCESS_TRAP;
2455     }
2456     return CP_ACCESS_OK;
2457 }
2458 
2459 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2460     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2461       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2462       .resetvalue = 0,
2463       .writefn = teecr_write },
2464     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2465       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2466       .accessfn = teehbr_access, .resetvalue = 0 },
2467     REGINFO_SENTINEL
2468 };
2469 
2470 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2471     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2472       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2473       .access = PL0_RW,
2474       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2475     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2476       .access = PL0_RW,
2477       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2478                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2479       .resetfn = arm_cp_reset_ignore },
2480     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2481       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2482       .access = PL0_R|PL1_W,
2483       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2484       .resetvalue = 0},
2485     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2486       .access = PL0_R|PL1_W,
2487       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2488                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2489       .resetfn = arm_cp_reset_ignore },
2490     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2491       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2492       .access = PL1_RW,
2493       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2494     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2495       .access = PL1_RW,
2496       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2497                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2498       .resetvalue = 0 },
2499     REGINFO_SENTINEL
2500 };
2501 
2502 #ifndef CONFIG_USER_ONLY
2503 
2504 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2505                                        bool isread)
2506 {
2507     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2508      * Writable only at the highest implemented exception level.
2509      */
2510     int el = arm_current_el(env);
2511     uint64_t hcr;
2512     uint32_t cntkctl;
2513 
2514     switch (el) {
2515     case 0:
2516         hcr = arm_hcr_el2_eff(env);
2517         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2518             cntkctl = env->cp15.cnthctl_el2;
2519         } else {
2520             cntkctl = env->cp15.c14_cntkctl;
2521         }
2522         if (!extract32(cntkctl, 0, 2)) {
2523             return CP_ACCESS_TRAP;
2524         }
2525         break;
2526     case 1:
2527         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2528             arm_is_secure_below_el3(env)) {
2529             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2530             return CP_ACCESS_TRAP_UNCATEGORIZED;
2531         }
2532         break;
2533     case 2:
2534     case 3:
2535         break;
2536     }
2537 
2538     if (!isread && el < arm_highest_el(env)) {
2539         return CP_ACCESS_TRAP_UNCATEGORIZED;
2540     }
2541 
2542     return CP_ACCESS_OK;
2543 }
2544 
2545 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2546                                         bool isread)
2547 {
2548     unsigned int cur_el = arm_current_el(env);
2549     bool has_el2 = arm_is_el2_enabled(env);
2550     uint64_t hcr = arm_hcr_el2_eff(env);
2551 
2552     switch (cur_el) {
2553     case 0:
2554         /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2555         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2556             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2557                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2558         }
2559 
2560         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2561         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2562             return CP_ACCESS_TRAP;
2563         }
2564 
2565         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2566         if (hcr & HCR_E2H) {
2567             if (timeridx == GTIMER_PHYS &&
2568                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2569                 return CP_ACCESS_TRAP_EL2;
2570             }
2571         } else {
2572             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2573             if (has_el2 && timeridx == GTIMER_PHYS &&
2574                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2575                 return CP_ACCESS_TRAP_EL2;
2576             }
2577         }
2578         break;
2579 
2580     case 1:
2581         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2582         if (has_el2 && timeridx == GTIMER_PHYS &&
2583             (hcr & HCR_E2H
2584              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2585              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2586             return CP_ACCESS_TRAP_EL2;
2587         }
2588         break;
2589     }
2590     return CP_ACCESS_OK;
2591 }
2592 
2593 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2594                                       bool isread)
2595 {
2596     unsigned int cur_el = arm_current_el(env);
2597     bool has_el2 = arm_is_el2_enabled(env);
2598     uint64_t hcr = arm_hcr_el2_eff(env);
2599 
2600     switch (cur_el) {
2601     case 0:
2602         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2603             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2604             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2605                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2606         }
2607 
2608         /*
2609          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2610          * EL0 if EL0[PV]TEN is zero.
2611          */
2612         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2613             return CP_ACCESS_TRAP;
2614         }
2615         /* fall through */
2616 
2617     case 1:
2618         if (has_el2 && timeridx == GTIMER_PHYS) {
2619             if (hcr & HCR_E2H) {
2620                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2621                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2622                     return CP_ACCESS_TRAP_EL2;
2623                 }
2624             } else {
2625                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2626                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2627                     return CP_ACCESS_TRAP_EL2;
2628                 }
2629             }
2630         }
2631         break;
2632     }
2633     return CP_ACCESS_OK;
2634 }
2635 
2636 static CPAccessResult gt_pct_access(CPUARMState *env,
2637                                     const ARMCPRegInfo *ri,
2638                                     bool isread)
2639 {
2640     return gt_counter_access(env, GTIMER_PHYS, isread);
2641 }
2642 
2643 static CPAccessResult gt_vct_access(CPUARMState *env,
2644                                     const ARMCPRegInfo *ri,
2645                                     bool isread)
2646 {
2647     return gt_counter_access(env, GTIMER_VIRT, isread);
2648 }
2649 
2650 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2651                                        bool isread)
2652 {
2653     return gt_timer_access(env, GTIMER_PHYS, isread);
2654 }
2655 
2656 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2657                                        bool isread)
2658 {
2659     return gt_timer_access(env, GTIMER_VIRT, isread);
2660 }
2661 
2662 static CPAccessResult gt_stimer_access(CPUARMState *env,
2663                                        const ARMCPRegInfo *ri,
2664                                        bool isread)
2665 {
2666     /* The AArch64 register view of the secure physical timer is
2667      * always accessible from EL3, and configurably accessible from
2668      * Secure EL1.
2669      */
2670     switch (arm_current_el(env)) {
2671     case 1:
2672         if (!arm_is_secure(env)) {
2673             return CP_ACCESS_TRAP;
2674         }
2675         if (!(env->cp15.scr_el3 & SCR_ST)) {
2676             return CP_ACCESS_TRAP_EL3;
2677         }
2678         return CP_ACCESS_OK;
2679     case 0:
2680     case 2:
2681         return CP_ACCESS_TRAP;
2682     case 3:
2683         return CP_ACCESS_OK;
2684     default:
2685         g_assert_not_reached();
2686     }
2687 }
2688 
2689 static uint64_t gt_get_countervalue(CPUARMState *env)
2690 {
2691     ARMCPU *cpu = env_archcpu(env);
2692 
2693     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2694 }
2695 
2696 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2697 {
2698     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2699 
2700     if (gt->ctl & 1) {
2701         /* Timer enabled: calculate and set current ISTATUS, irq, and
2702          * reset timer to when ISTATUS next has to change
2703          */
2704         uint64_t offset = timeridx == GTIMER_VIRT ?
2705                                       cpu->env.cp15.cntvoff_el2 : 0;
2706         uint64_t count = gt_get_countervalue(&cpu->env);
2707         /* Note that this must be unsigned 64 bit arithmetic: */
2708         int istatus = count - offset >= gt->cval;
2709         uint64_t nexttick;
2710         int irqstate;
2711 
2712         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2713 
2714         irqstate = (istatus && !(gt->ctl & 2));
2715         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2716 
2717         if (istatus) {
2718             /* Next transition is when count rolls back over to zero */
2719             nexttick = UINT64_MAX;
2720         } else {
2721             /* Next transition is when we hit cval */
2722             nexttick = gt->cval + offset;
2723         }
2724         /* Note that the desired next expiry time might be beyond the
2725          * signed-64-bit range of a QEMUTimer -- in this case we just
2726          * set the timer for as far in the future as possible. When the
2727          * timer expires we will reset the timer for any remaining period.
2728          */
2729         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2730             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2731         } else {
2732             timer_mod(cpu->gt_timer[timeridx], nexttick);
2733         }
2734         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2735     } else {
2736         /* Timer disabled: ISTATUS and timer output always clear */
2737         gt->ctl &= ~4;
2738         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2739         timer_del(cpu->gt_timer[timeridx]);
2740         trace_arm_gt_recalc_disabled(timeridx);
2741     }
2742 }
2743 
2744 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2745                            int timeridx)
2746 {
2747     ARMCPU *cpu = env_archcpu(env);
2748 
2749     timer_del(cpu->gt_timer[timeridx]);
2750 }
2751 
2752 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2753 {
2754     return gt_get_countervalue(env);
2755 }
2756 
2757 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2758 {
2759     uint64_t hcr;
2760 
2761     switch (arm_current_el(env)) {
2762     case 2:
2763         hcr = arm_hcr_el2_eff(env);
2764         if (hcr & HCR_E2H) {
2765             return 0;
2766         }
2767         break;
2768     case 0:
2769         hcr = arm_hcr_el2_eff(env);
2770         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2771             return 0;
2772         }
2773         break;
2774     }
2775 
2776     return env->cp15.cntvoff_el2;
2777 }
2778 
2779 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2780 {
2781     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2782 }
2783 
2784 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2785                           int timeridx,
2786                           uint64_t value)
2787 {
2788     trace_arm_gt_cval_write(timeridx, value);
2789     env->cp15.c14_timer[timeridx].cval = value;
2790     gt_recalc_timer(env_archcpu(env), timeridx);
2791 }
2792 
2793 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2794                              int timeridx)
2795 {
2796     uint64_t offset = 0;
2797 
2798     switch (timeridx) {
2799     case GTIMER_VIRT:
2800     case GTIMER_HYPVIRT:
2801         offset = gt_virt_cnt_offset(env);
2802         break;
2803     }
2804 
2805     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2806                       (gt_get_countervalue(env) - offset));
2807 }
2808 
2809 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2810                           int timeridx,
2811                           uint64_t value)
2812 {
2813     uint64_t offset = 0;
2814 
2815     switch (timeridx) {
2816     case GTIMER_VIRT:
2817     case GTIMER_HYPVIRT:
2818         offset = gt_virt_cnt_offset(env);
2819         break;
2820     }
2821 
2822     trace_arm_gt_tval_write(timeridx, value);
2823     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2824                                          sextract64(value, 0, 32);
2825     gt_recalc_timer(env_archcpu(env), timeridx);
2826 }
2827 
2828 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2829                          int timeridx,
2830                          uint64_t value)
2831 {
2832     ARMCPU *cpu = env_archcpu(env);
2833     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2834 
2835     trace_arm_gt_ctl_write(timeridx, value);
2836     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2837     if ((oldval ^ value) & 1) {
2838         /* Enable toggled */
2839         gt_recalc_timer(cpu, timeridx);
2840     } else if ((oldval ^ value) & 2) {
2841         /* IMASK toggled: don't need to recalculate,
2842          * just set the interrupt line based on ISTATUS
2843          */
2844         int irqstate = (oldval & 4) && !(value & 2);
2845 
2846         trace_arm_gt_imask_toggle(timeridx, irqstate);
2847         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2848     }
2849 }
2850 
2851 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2852 {
2853     gt_timer_reset(env, ri, GTIMER_PHYS);
2854 }
2855 
2856 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2857                                uint64_t value)
2858 {
2859     gt_cval_write(env, ri, GTIMER_PHYS, value);
2860 }
2861 
2862 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2863 {
2864     return gt_tval_read(env, ri, GTIMER_PHYS);
2865 }
2866 
2867 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2868                                uint64_t value)
2869 {
2870     gt_tval_write(env, ri, GTIMER_PHYS, value);
2871 }
2872 
2873 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2874                               uint64_t value)
2875 {
2876     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2877 }
2878 
2879 static int gt_phys_redir_timeridx(CPUARMState *env)
2880 {
2881     switch (arm_mmu_idx(env)) {
2882     case ARMMMUIdx_E20_0:
2883     case ARMMMUIdx_E20_2:
2884     case ARMMMUIdx_E20_2_PAN:
2885     case ARMMMUIdx_SE20_0:
2886     case ARMMMUIdx_SE20_2:
2887     case ARMMMUIdx_SE20_2_PAN:
2888         return GTIMER_HYP;
2889     default:
2890         return GTIMER_PHYS;
2891     }
2892 }
2893 
2894 static int gt_virt_redir_timeridx(CPUARMState *env)
2895 {
2896     switch (arm_mmu_idx(env)) {
2897     case ARMMMUIdx_E20_0:
2898     case ARMMMUIdx_E20_2:
2899     case ARMMMUIdx_E20_2_PAN:
2900     case ARMMMUIdx_SE20_0:
2901     case ARMMMUIdx_SE20_2:
2902     case ARMMMUIdx_SE20_2_PAN:
2903         return GTIMER_HYPVIRT;
2904     default:
2905         return GTIMER_VIRT;
2906     }
2907 }
2908 
2909 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2910                                         const ARMCPRegInfo *ri)
2911 {
2912     int timeridx = gt_phys_redir_timeridx(env);
2913     return env->cp15.c14_timer[timeridx].cval;
2914 }
2915 
2916 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2917                                      uint64_t value)
2918 {
2919     int timeridx = gt_phys_redir_timeridx(env);
2920     gt_cval_write(env, ri, timeridx, value);
2921 }
2922 
2923 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2924                                         const ARMCPRegInfo *ri)
2925 {
2926     int timeridx = gt_phys_redir_timeridx(env);
2927     return gt_tval_read(env, ri, timeridx);
2928 }
2929 
2930 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2931                                      uint64_t value)
2932 {
2933     int timeridx = gt_phys_redir_timeridx(env);
2934     gt_tval_write(env, ri, timeridx, value);
2935 }
2936 
2937 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2938                                        const ARMCPRegInfo *ri)
2939 {
2940     int timeridx = gt_phys_redir_timeridx(env);
2941     return env->cp15.c14_timer[timeridx].ctl;
2942 }
2943 
2944 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2945                                     uint64_t value)
2946 {
2947     int timeridx = gt_phys_redir_timeridx(env);
2948     gt_ctl_write(env, ri, timeridx, value);
2949 }
2950 
2951 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2952 {
2953     gt_timer_reset(env, ri, GTIMER_VIRT);
2954 }
2955 
2956 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2957                                uint64_t value)
2958 {
2959     gt_cval_write(env, ri, GTIMER_VIRT, value);
2960 }
2961 
2962 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2963 {
2964     return gt_tval_read(env, ri, GTIMER_VIRT);
2965 }
2966 
2967 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2968                                uint64_t value)
2969 {
2970     gt_tval_write(env, ri, GTIMER_VIRT, value);
2971 }
2972 
2973 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2974                               uint64_t value)
2975 {
2976     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2977 }
2978 
2979 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2980                               uint64_t value)
2981 {
2982     ARMCPU *cpu = env_archcpu(env);
2983 
2984     trace_arm_gt_cntvoff_write(value);
2985     raw_write(env, ri, value);
2986     gt_recalc_timer(cpu, GTIMER_VIRT);
2987 }
2988 
2989 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
2990                                         const ARMCPRegInfo *ri)
2991 {
2992     int timeridx = gt_virt_redir_timeridx(env);
2993     return env->cp15.c14_timer[timeridx].cval;
2994 }
2995 
2996 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2997                                      uint64_t value)
2998 {
2999     int timeridx = gt_virt_redir_timeridx(env);
3000     gt_cval_write(env, ri, timeridx, value);
3001 }
3002 
3003 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
3004                                         const ARMCPRegInfo *ri)
3005 {
3006     int timeridx = gt_virt_redir_timeridx(env);
3007     return gt_tval_read(env, ri, timeridx);
3008 }
3009 
3010 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3011                                      uint64_t value)
3012 {
3013     int timeridx = gt_virt_redir_timeridx(env);
3014     gt_tval_write(env, ri, timeridx, value);
3015 }
3016 
3017 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
3018                                        const ARMCPRegInfo *ri)
3019 {
3020     int timeridx = gt_virt_redir_timeridx(env);
3021     return env->cp15.c14_timer[timeridx].ctl;
3022 }
3023 
3024 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3025                                     uint64_t value)
3026 {
3027     int timeridx = gt_virt_redir_timeridx(env);
3028     gt_ctl_write(env, ri, timeridx, value);
3029 }
3030 
3031 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3032 {
3033     gt_timer_reset(env, ri, GTIMER_HYP);
3034 }
3035 
3036 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3037                               uint64_t value)
3038 {
3039     gt_cval_write(env, ri, GTIMER_HYP, value);
3040 }
3041 
3042 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3043 {
3044     return gt_tval_read(env, ri, GTIMER_HYP);
3045 }
3046 
3047 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3048                               uint64_t value)
3049 {
3050     gt_tval_write(env, ri, GTIMER_HYP, value);
3051 }
3052 
3053 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3054                               uint64_t value)
3055 {
3056     gt_ctl_write(env, ri, GTIMER_HYP, value);
3057 }
3058 
3059 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3060 {
3061     gt_timer_reset(env, ri, GTIMER_SEC);
3062 }
3063 
3064 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3065                               uint64_t value)
3066 {
3067     gt_cval_write(env, ri, GTIMER_SEC, value);
3068 }
3069 
3070 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3071 {
3072     return gt_tval_read(env, ri, GTIMER_SEC);
3073 }
3074 
3075 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3076                               uint64_t value)
3077 {
3078     gt_tval_write(env, ri, GTIMER_SEC, value);
3079 }
3080 
3081 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3082                               uint64_t value)
3083 {
3084     gt_ctl_write(env, ri, GTIMER_SEC, value);
3085 }
3086 
3087 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3088 {
3089     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
3090 }
3091 
3092 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3093                              uint64_t value)
3094 {
3095     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
3096 }
3097 
3098 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3099 {
3100     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
3101 }
3102 
3103 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3104                              uint64_t value)
3105 {
3106     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
3107 }
3108 
3109 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3110                             uint64_t value)
3111 {
3112     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
3113 }
3114 
3115 void arm_gt_ptimer_cb(void *opaque)
3116 {
3117     ARMCPU *cpu = opaque;
3118 
3119     gt_recalc_timer(cpu, GTIMER_PHYS);
3120 }
3121 
3122 void arm_gt_vtimer_cb(void *opaque)
3123 {
3124     ARMCPU *cpu = opaque;
3125 
3126     gt_recalc_timer(cpu, GTIMER_VIRT);
3127 }
3128 
3129 void arm_gt_htimer_cb(void *opaque)
3130 {
3131     ARMCPU *cpu = opaque;
3132 
3133     gt_recalc_timer(cpu, GTIMER_HYP);
3134 }
3135 
3136 void arm_gt_stimer_cb(void *opaque)
3137 {
3138     ARMCPU *cpu = opaque;
3139 
3140     gt_recalc_timer(cpu, GTIMER_SEC);
3141 }
3142 
3143 void arm_gt_hvtimer_cb(void *opaque)
3144 {
3145     ARMCPU *cpu = opaque;
3146 
3147     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
3148 }
3149 
3150 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
3151 {
3152     ARMCPU *cpu = env_archcpu(env);
3153 
3154     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
3155 }
3156 
3157 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3158     /* Note that CNTFRQ is purely reads-as-written for the benefit
3159      * of software; writing it doesn't actually change the timer frequency.
3160      * Our reset value matches the fixed frequency we implement the timer at.
3161      */
3162     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
3163       .type = ARM_CP_ALIAS,
3164       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3165       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
3166     },
3167     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3168       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3169       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3170       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3171       .resetfn = arm_gt_cntfrq_reset,
3172     },
3173     /* overall control: mostly access permissions */
3174     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
3175       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
3176       .access = PL1_RW,
3177       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
3178       .resetvalue = 0,
3179     },
3180     /* per-timer control */
3181     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3182       .secure = ARM_CP_SECSTATE_NS,
3183       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3184       .accessfn = gt_ptimer_access,
3185       .fieldoffset = offsetoflow32(CPUARMState,
3186                                    cp15.c14_timer[GTIMER_PHYS].ctl),
3187       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3188       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3189     },
3190     { .name = "CNTP_CTL_S",
3191       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3192       .secure = ARM_CP_SECSTATE_S,
3193       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3194       .accessfn = gt_ptimer_access,
3195       .fieldoffset = offsetoflow32(CPUARMState,
3196                                    cp15.c14_timer[GTIMER_SEC].ctl),
3197       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3198     },
3199     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
3200       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
3201       .type = ARM_CP_IO, .access = PL0_RW,
3202       .accessfn = gt_ptimer_access,
3203       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
3204       .resetvalue = 0,
3205       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3206       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3207     },
3208     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
3209       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3210       .accessfn = gt_vtimer_access,
3211       .fieldoffset = offsetoflow32(CPUARMState,
3212                                    cp15.c14_timer[GTIMER_VIRT].ctl),
3213       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3214       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3215     },
3216     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
3217       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
3218       .type = ARM_CP_IO, .access = PL0_RW,
3219       .accessfn = gt_vtimer_access,
3220       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
3221       .resetvalue = 0,
3222       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3223       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3224     },
3225     /* TimerValue views: a 32 bit downcounting view of the underlying state */
3226     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3227       .secure = ARM_CP_SECSTATE_NS,
3228       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3229       .accessfn = gt_ptimer_access,
3230       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3231     },
3232     { .name = "CNTP_TVAL_S",
3233       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3234       .secure = ARM_CP_SECSTATE_S,
3235       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3236       .accessfn = gt_ptimer_access,
3237       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
3238     },
3239     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3240       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
3241       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3242       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
3243       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3244     },
3245     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
3246       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3247       .accessfn = gt_vtimer_access,
3248       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3249     },
3250     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3251       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
3252       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3253       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
3254       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3255     },
3256     /* The counter itself */
3257     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
3258       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3259       .accessfn = gt_pct_access,
3260       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
3261     },
3262     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
3263       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
3264       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3265       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
3266     },
3267     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3268       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3269       .accessfn = gt_vct_access,
3270       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3271     },
3272     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3273       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3274       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3275       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3276     },
3277     /* Comparison value, indicating when the timer goes off */
3278     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3279       .secure = ARM_CP_SECSTATE_NS,
3280       .access = PL0_RW,
3281       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3282       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3283       .accessfn = gt_ptimer_access,
3284       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3285       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3286     },
3287     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3288       .secure = ARM_CP_SECSTATE_S,
3289       .access = PL0_RW,
3290       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3291       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3292       .accessfn = gt_ptimer_access,
3293       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3294     },
3295     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3296       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3297       .access = PL0_RW,
3298       .type = ARM_CP_IO,
3299       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3300       .resetvalue = 0, .accessfn = gt_ptimer_access,
3301       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3302       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3303     },
3304     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3305       .access = PL0_RW,
3306       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3307       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3308       .accessfn = gt_vtimer_access,
3309       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3310       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3311     },
3312     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3313       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3314       .access = PL0_RW,
3315       .type = ARM_CP_IO,
3316       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3317       .resetvalue = 0, .accessfn = gt_vtimer_access,
3318       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3319       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3320     },
3321     /* Secure timer -- this is actually restricted to only EL3
3322      * and configurably Secure-EL1 via the accessfn.
3323      */
3324     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3325       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3326       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3327       .accessfn = gt_stimer_access,
3328       .readfn = gt_sec_tval_read,
3329       .writefn = gt_sec_tval_write,
3330       .resetfn = gt_sec_timer_reset,
3331     },
3332     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3333       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3334       .type = ARM_CP_IO, .access = PL1_RW,
3335       .accessfn = gt_stimer_access,
3336       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3337       .resetvalue = 0,
3338       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3339     },
3340     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3341       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3342       .type = ARM_CP_IO, .access = PL1_RW,
3343       .accessfn = gt_stimer_access,
3344       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3345       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3346     },
3347     REGINFO_SENTINEL
3348 };
3349 
3350 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3351                                  bool isread)
3352 {
3353     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3354         return CP_ACCESS_TRAP;
3355     }
3356     return CP_ACCESS_OK;
3357 }
3358 
3359 #else
3360 
3361 /* In user-mode most of the generic timer registers are inaccessible
3362  * however modern kernels (4.12+) allow access to cntvct_el0
3363  */
3364 
3365 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3366 {
3367     ARMCPU *cpu = env_archcpu(env);
3368 
3369     /* Currently we have no support for QEMUTimer in linux-user so we
3370      * can't call gt_get_countervalue(env), instead we directly
3371      * call the lower level functions.
3372      */
3373     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3374 }
3375 
3376 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3377     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3378       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3379       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3380       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3381       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3382     },
3383     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3384       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3385       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3386       .readfn = gt_virt_cnt_read,
3387     },
3388     REGINFO_SENTINEL
3389 };
3390 
3391 #endif
3392 
3393 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3394 {
3395     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3396         raw_write(env, ri, value);
3397     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3398         raw_write(env, ri, value & 0xfffff6ff);
3399     } else {
3400         raw_write(env, ri, value & 0xfffff1ff);
3401     }
3402 }
3403 
3404 #ifndef CONFIG_USER_ONLY
3405 /* get_phys_addr() isn't present for user-mode-only targets */
3406 
3407 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3408                                  bool isread)
3409 {
3410     if (ri->opc2 & 4) {
3411         /* The ATS12NSO* operations must trap to EL3 or EL2 if executed in
3412          * Secure EL1 (which can only happen if EL3 is AArch64).
3413          * They are simply UNDEF if executed from NS EL1.
3414          * They function normally from EL2 or EL3.
3415          */
3416         if (arm_current_el(env) == 1) {
3417             if (arm_is_secure_below_el3(env)) {
3418                 if (env->cp15.scr_el3 & SCR_EEL2) {
3419                     return CP_ACCESS_TRAP_UNCATEGORIZED_EL2;
3420                 }
3421                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3422             }
3423             return CP_ACCESS_TRAP_UNCATEGORIZED;
3424         }
3425     }
3426     return CP_ACCESS_OK;
3427 }
3428 
3429 #ifdef CONFIG_TCG
3430 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3431                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3432 {
3433     hwaddr phys_addr;
3434     target_ulong page_size;
3435     int prot;
3436     bool ret;
3437     uint64_t par64;
3438     bool format64 = false;
3439     MemTxAttrs attrs = {};
3440     ARMMMUFaultInfo fi = {};
3441     ARMCacheAttrs cacheattrs = {};
3442 
3443     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3444                         &prot, &page_size, &fi, &cacheattrs);
3445 
3446     if (ret) {
3447         /*
3448          * Some kinds of translation fault must cause exceptions rather
3449          * than being reported in the PAR.
3450          */
3451         int current_el = arm_current_el(env);
3452         int target_el;
3453         uint32_t syn, fsr, fsc;
3454         bool take_exc = false;
3455 
3456         if (fi.s1ptw && current_el == 1
3457             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3458             /*
3459              * Synchronous stage 2 fault on an access made as part of the
3460              * translation table walk for AT S1E0* or AT S1E1* insn
3461              * executed from NS EL1. If this is a synchronous external abort
3462              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3463              * to EL3. Otherwise the fault is taken as an exception to EL2,
3464              * and HPFAR_EL2 holds the faulting IPA.
3465              */
3466             if (fi.type == ARMFault_SyncExternalOnWalk &&
3467                 (env->cp15.scr_el3 & SCR_EA)) {
3468                 target_el = 3;
3469             } else {
3470                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3471                 if (arm_is_secure_below_el3(env) && fi.s1ns) {
3472                     env->cp15.hpfar_el2 |= HPFAR_NS;
3473                 }
3474                 target_el = 2;
3475             }
3476             take_exc = true;
3477         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3478             /*
3479              * Synchronous external aborts during a translation table walk
3480              * are taken as Data Abort exceptions.
3481              */
3482             if (fi.stage2) {
3483                 if (current_el == 3) {
3484                     target_el = 3;
3485                 } else {
3486                     target_el = 2;
3487                 }
3488             } else {
3489                 target_el = exception_target_el(env);
3490             }
3491             take_exc = true;
3492         }
3493 
3494         if (take_exc) {
3495             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3496             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3497                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3498                 fsr = arm_fi_to_lfsc(&fi);
3499                 fsc = extract32(fsr, 0, 6);
3500             } else {
3501                 fsr = arm_fi_to_sfsc(&fi);
3502                 fsc = 0x3f;
3503             }
3504             /*
3505              * Report exception with ESR indicating a fault due to a
3506              * translation table walk for a cache maintenance instruction.
3507              */
3508             syn = syn_data_abort_no_iss(current_el == target_el, 0,
3509                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3510             env->exception.vaddress = value;
3511             env->exception.fsr = fsr;
3512             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3513         }
3514     }
3515 
3516     if (is_a64(env)) {
3517         format64 = true;
3518     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3519         /*
3520          * ATS1Cxx:
3521          * * TTBCR.EAE determines whether the result is returned using the
3522          *   32-bit or the 64-bit PAR format
3523          * * Instructions executed in Hyp mode always use the 64bit format
3524          *
3525          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3526          * * The Non-secure TTBCR.EAE bit is set to 1
3527          * * The implementation includes EL2, and the value of HCR.VM is 1
3528          *
3529          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3530          *
3531          * ATS1Hx always uses the 64bit format.
3532          */
3533         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3534 
3535         if (arm_feature(env, ARM_FEATURE_EL2)) {
3536             if (mmu_idx == ARMMMUIdx_E10_0 ||
3537                 mmu_idx == ARMMMUIdx_E10_1 ||
3538                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3539                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3540             } else {
3541                 format64 |= arm_current_el(env) == 2;
3542             }
3543         }
3544     }
3545 
3546     if (format64) {
3547         /* Create a 64-bit PAR */
3548         par64 = (1 << 11); /* LPAE bit always set */
3549         if (!ret) {
3550             par64 |= phys_addr & ~0xfffULL;
3551             if (!attrs.secure) {
3552                 par64 |= (1 << 9); /* NS */
3553             }
3554             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3555             par64 |= cacheattrs.shareability << 7; /* SH */
3556         } else {
3557             uint32_t fsr = arm_fi_to_lfsc(&fi);
3558 
3559             par64 |= 1; /* F */
3560             par64 |= (fsr & 0x3f) << 1; /* FS */
3561             if (fi.stage2) {
3562                 par64 |= (1 << 9); /* S */
3563             }
3564             if (fi.s1ptw) {
3565                 par64 |= (1 << 8); /* PTW */
3566             }
3567         }
3568     } else {
3569         /* fsr is a DFSR/IFSR value for the short descriptor
3570          * translation table format (with WnR always clear).
3571          * Convert it to a 32-bit PAR.
3572          */
3573         if (!ret) {
3574             /* We do not set any attribute bits in the PAR */
3575             if (page_size == (1 << 24)
3576                 && arm_feature(env, ARM_FEATURE_V7)) {
3577                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3578             } else {
3579                 par64 = phys_addr & 0xfffff000;
3580             }
3581             if (!attrs.secure) {
3582                 par64 |= (1 << 9); /* NS */
3583             }
3584         } else {
3585             uint32_t fsr = arm_fi_to_sfsc(&fi);
3586 
3587             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3588                     ((fsr & 0xf) << 1) | 1;
3589         }
3590     }
3591     return par64;
3592 }
3593 #endif /* CONFIG_TCG */
3594 
3595 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3596 {
3597 #ifdef CONFIG_TCG
3598     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3599     uint64_t par64;
3600     ARMMMUIdx mmu_idx;
3601     int el = arm_current_el(env);
3602     bool secure = arm_is_secure_below_el3(env);
3603 
3604     switch (ri->opc2 & 6) {
3605     case 0:
3606         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3607         switch (el) {
3608         case 3:
3609             mmu_idx = ARMMMUIdx_SE3;
3610             break;
3611         case 2:
3612             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3613             /* fall through */
3614         case 1:
3615             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3616                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3617                            : ARMMMUIdx_Stage1_E1_PAN);
3618             } else {
3619                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3620             }
3621             break;
3622         default:
3623             g_assert_not_reached();
3624         }
3625         break;
3626     case 2:
3627         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3628         switch (el) {
3629         case 3:
3630             mmu_idx = ARMMMUIdx_SE10_0;
3631             break;
3632         case 2:
3633             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3634             mmu_idx = ARMMMUIdx_Stage1_E0;
3635             break;
3636         case 1:
3637             mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3638             break;
3639         default:
3640             g_assert_not_reached();
3641         }
3642         break;
3643     case 4:
3644         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3645         mmu_idx = ARMMMUIdx_E10_1;
3646         break;
3647     case 6:
3648         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3649         mmu_idx = ARMMMUIdx_E10_0;
3650         break;
3651     default:
3652         g_assert_not_reached();
3653     }
3654 
3655     par64 = do_ats_write(env, value, access_type, mmu_idx);
3656 
3657     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3658 #else
3659     /* Handled by hardware accelerator. */
3660     g_assert_not_reached();
3661 #endif /* CONFIG_TCG */
3662 }
3663 
3664 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3665                         uint64_t value)
3666 {
3667 #ifdef CONFIG_TCG
3668     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3669     uint64_t par64;
3670 
3671     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3672 
3673     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3674 #else
3675     /* Handled by hardware accelerator. */
3676     g_assert_not_reached();
3677 #endif /* CONFIG_TCG */
3678 }
3679 
3680 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3681                                      bool isread)
3682 {
3683     if (arm_current_el(env) == 3 &&
3684         !(env->cp15.scr_el3 & (SCR_NS | SCR_EEL2))) {
3685         return CP_ACCESS_TRAP;
3686     }
3687     return CP_ACCESS_OK;
3688 }
3689 
3690 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3691                         uint64_t value)
3692 {
3693 #ifdef CONFIG_TCG
3694     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3695     ARMMMUIdx mmu_idx;
3696     int secure = arm_is_secure_below_el3(env);
3697 
3698     switch (ri->opc2 & 6) {
3699     case 0:
3700         switch (ri->opc1) {
3701         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3702             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3703                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3704                            : ARMMMUIdx_Stage1_E1_PAN);
3705             } else {
3706                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3707             }
3708             break;
3709         case 4: /* AT S1E2R, AT S1E2W */
3710             mmu_idx = secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2;
3711             break;
3712         case 6: /* AT S1E3R, AT S1E3W */
3713             mmu_idx = ARMMMUIdx_SE3;
3714             break;
3715         default:
3716             g_assert_not_reached();
3717         }
3718         break;
3719     case 2: /* AT S1E0R, AT S1E0W */
3720         mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3721         break;
3722     case 4: /* AT S12E1R, AT S12E1W */
3723         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3724         break;
3725     case 6: /* AT S12E0R, AT S12E0W */
3726         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3727         break;
3728     default:
3729         g_assert_not_reached();
3730     }
3731 
3732     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3733 #else
3734     /* Handled by hardware accelerator. */
3735     g_assert_not_reached();
3736 #endif /* CONFIG_TCG */
3737 }
3738 #endif
3739 
3740 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3741     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3742       .access = PL1_RW, .resetvalue = 0,
3743       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3744                              offsetoflow32(CPUARMState, cp15.par_ns) },
3745       .writefn = par_write },
3746 #ifndef CONFIG_USER_ONLY
3747     /* This underdecoding is safe because the reginfo is NO_RAW. */
3748     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3749       .access = PL1_W, .accessfn = ats_access,
3750       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3751 #endif
3752     REGINFO_SENTINEL
3753 };
3754 
3755 /* Return basic MPU access permission bits.  */
3756 static uint32_t simple_mpu_ap_bits(uint32_t val)
3757 {
3758     uint32_t ret;
3759     uint32_t mask;
3760     int i;
3761     ret = 0;
3762     mask = 3;
3763     for (i = 0; i < 16; i += 2) {
3764         ret |= (val >> i) & mask;
3765         mask <<= 2;
3766     }
3767     return ret;
3768 }
3769 
3770 /* Pad basic MPU access permission bits to extended format.  */
3771 static uint32_t extended_mpu_ap_bits(uint32_t val)
3772 {
3773     uint32_t ret;
3774     uint32_t mask;
3775     int i;
3776     ret = 0;
3777     mask = 3;
3778     for (i = 0; i < 16; i += 2) {
3779         ret |= (val & mask) << i;
3780         mask <<= 2;
3781     }
3782     return ret;
3783 }
3784 
3785 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3786                                  uint64_t value)
3787 {
3788     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3789 }
3790 
3791 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3792 {
3793     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3794 }
3795 
3796 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3797                                  uint64_t value)
3798 {
3799     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3800 }
3801 
3802 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3803 {
3804     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3805 }
3806 
3807 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3808 {
3809     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3810 
3811     if (!u32p) {
3812         return 0;
3813     }
3814 
3815     u32p += env->pmsav7.rnr[M_REG_NS];
3816     return *u32p;
3817 }
3818 
3819 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3820                          uint64_t value)
3821 {
3822     ARMCPU *cpu = env_archcpu(env);
3823     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3824 
3825     if (!u32p) {
3826         return;
3827     }
3828 
3829     u32p += env->pmsav7.rnr[M_REG_NS];
3830     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3831     *u32p = value;
3832 }
3833 
3834 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3835                               uint64_t value)
3836 {
3837     ARMCPU *cpu = env_archcpu(env);
3838     uint32_t nrgs = cpu->pmsav7_dregion;
3839 
3840     if (value >= nrgs) {
3841         qemu_log_mask(LOG_GUEST_ERROR,
3842                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3843                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3844         return;
3845     }
3846 
3847     raw_write(env, ri, value);
3848 }
3849 
3850 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3851     /* Reset for all these registers is handled in arm_cpu_reset(),
3852      * because the PMSAv7 is also used by M-profile CPUs, which do
3853      * not register cpregs but still need the state to be reset.
3854      */
3855     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3856       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3857       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3858       .readfn = pmsav7_read, .writefn = pmsav7_write,
3859       .resetfn = arm_cp_reset_ignore },
3860     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3861       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3862       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3863       .readfn = pmsav7_read, .writefn = pmsav7_write,
3864       .resetfn = arm_cp_reset_ignore },
3865     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3866       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3867       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3868       .readfn = pmsav7_read, .writefn = pmsav7_write,
3869       .resetfn = arm_cp_reset_ignore },
3870     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3871       .access = PL1_RW,
3872       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3873       .writefn = pmsav7_rgnr_write,
3874       .resetfn = arm_cp_reset_ignore },
3875     REGINFO_SENTINEL
3876 };
3877 
3878 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3879     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3880       .access = PL1_RW, .type = ARM_CP_ALIAS,
3881       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3882       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3883     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3884       .access = PL1_RW, .type = ARM_CP_ALIAS,
3885       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3886       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3887     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3888       .access = PL1_RW,
3889       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3890       .resetvalue = 0, },
3891     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3892       .access = PL1_RW,
3893       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3894       .resetvalue = 0, },
3895     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3896       .access = PL1_RW,
3897       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3898     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3899       .access = PL1_RW,
3900       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3901     /* Protection region base and size registers */
3902     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3903       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3904       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3905     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3906       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3907       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3908     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3909       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3910       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3911     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3912       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3913       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3914     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3915       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3916       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3917     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3918       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3919       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3920     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3921       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3922       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3923     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3924       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3925       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3926     REGINFO_SENTINEL
3927 };
3928 
3929 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3930                                  uint64_t value)
3931 {
3932     TCR *tcr = raw_ptr(env, ri);
3933     int maskshift = extract32(value, 0, 3);
3934 
3935     if (!arm_feature(env, ARM_FEATURE_V8)) {
3936         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3937             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3938              * using Long-desciptor translation table format */
3939             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3940         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3941             /* In an implementation that includes the Security Extensions
3942              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3943              * Short-descriptor translation table format.
3944              */
3945             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3946         } else {
3947             value &= TTBCR_N;
3948         }
3949     }
3950 
3951     /* Update the masks corresponding to the TCR bank being written
3952      * Note that we always calculate mask and base_mask, but
3953      * they are only used for short-descriptor tables (ie if EAE is 0);
3954      * for long-descriptor tables the TCR fields are used differently
3955      * and the mask and base_mask values are meaningless.
3956      */
3957     tcr->raw_tcr = value;
3958     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3959     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3960 }
3961 
3962 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3963                              uint64_t value)
3964 {
3965     ARMCPU *cpu = env_archcpu(env);
3966     TCR *tcr = raw_ptr(env, ri);
3967 
3968     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3969         /* With LPAE the TTBCR could result in a change of ASID
3970          * via the TTBCR.A1 bit, so do a TLB flush.
3971          */
3972         tlb_flush(CPU(cpu));
3973     }
3974     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3975     value = deposit64(tcr->raw_tcr, 0, 32, value);
3976     vmsa_ttbcr_raw_write(env, ri, value);
3977 }
3978 
3979 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3980 {
3981     TCR *tcr = raw_ptr(env, ri);
3982 
3983     /* Reset both the TCR as well as the masks corresponding to the bank of
3984      * the TCR being reset.
3985      */
3986     tcr->raw_tcr = 0;
3987     tcr->mask = 0;
3988     tcr->base_mask = 0xffffc000u;
3989 }
3990 
3991 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3992                                uint64_t value)
3993 {
3994     ARMCPU *cpu = env_archcpu(env);
3995     TCR *tcr = raw_ptr(env, ri);
3996 
3997     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3998     tlb_flush(CPU(cpu));
3999     tcr->raw_tcr = value;
4000 }
4001 
4002 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4003                             uint64_t value)
4004 {
4005     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
4006     if (cpreg_field_is_64bit(ri) &&
4007         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
4008         ARMCPU *cpu = env_archcpu(env);
4009         tlb_flush(CPU(cpu));
4010     }
4011     raw_write(env, ri, value);
4012 }
4013 
4014 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4015                                     uint64_t value)
4016 {
4017     /*
4018      * If we are running with E2&0 regime, then an ASID is active.
4019      * Flush if that might be changing.  Note we're not checking
4020      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
4021      * holds the active ASID, only checking the field that might.
4022      */
4023     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
4024         (arm_hcr_el2_eff(env) & HCR_E2H)) {
4025         uint16_t mask = ARMMMUIdxBit_E20_2 |
4026                         ARMMMUIdxBit_E20_2_PAN |
4027                         ARMMMUIdxBit_E20_0;
4028 
4029         if (arm_is_secure_below_el3(env)) {
4030             mask >>= ARM_MMU_IDX_A_NS;
4031         }
4032 
4033         tlb_flush_by_mmuidx(env_cpu(env), mask);
4034     }
4035     raw_write(env, ri, value);
4036 }
4037 
4038 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4039                         uint64_t value)
4040 {
4041     ARMCPU *cpu = env_archcpu(env);
4042     CPUState *cs = CPU(cpu);
4043 
4044     /*
4045      * A change in VMID to the stage2 page table (Stage2) invalidates
4046      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
4047      */
4048     if (raw_read(env, ri) != value) {
4049         uint16_t mask = ARMMMUIdxBit_E10_1 |
4050                         ARMMMUIdxBit_E10_1_PAN |
4051                         ARMMMUIdxBit_E10_0;
4052 
4053         if (arm_is_secure_below_el3(env)) {
4054             mask >>= ARM_MMU_IDX_A_NS;
4055         }
4056 
4057         tlb_flush_by_mmuidx(cs, mask);
4058         raw_write(env, ri, value);
4059     }
4060 }
4061 
4062 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
4063     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
4064       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
4065       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
4066                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
4067     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
4068       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4069       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
4070                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
4071     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
4072       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4073       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
4074                              offsetof(CPUARMState, cp15.dfar_ns) } },
4075     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
4076       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
4077       .access = PL1_RW, .accessfn = access_tvm_trvm,
4078       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
4079       .resetvalue = 0, },
4080     REGINFO_SENTINEL
4081 };
4082 
4083 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
4084     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
4085       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
4086       .access = PL1_RW, .accessfn = access_tvm_trvm,
4087       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
4088     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
4089       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
4090       .access = PL1_RW, .accessfn = access_tvm_trvm,
4091       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4092       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4093                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
4094     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
4095       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
4096       .access = PL1_RW, .accessfn = access_tvm_trvm,
4097       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4098       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4099                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
4100     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
4101       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4102       .access = PL1_RW, .accessfn = access_tvm_trvm,
4103       .writefn = vmsa_tcr_el12_write,
4104       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
4105       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
4106     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4107       .access = PL1_RW, .accessfn = access_tvm_trvm,
4108       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
4109       .raw_writefn = vmsa_ttbcr_raw_write,
4110       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
4111                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
4112     REGINFO_SENTINEL
4113 };
4114 
4115 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
4116  * qemu tlbs nor adjusting cached masks.
4117  */
4118 static const ARMCPRegInfo ttbcr2_reginfo = {
4119     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
4120     .access = PL1_RW, .accessfn = access_tvm_trvm,
4121     .type = ARM_CP_ALIAS,
4122     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
4123                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
4124 };
4125 
4126 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
4127                                 uint64_t value)
4128 {
4129     env->cp15.c15_ticonfig = value & 0xe7;
4130     /* The OS_TYPE bit in this register changes the reported CPUID! */
4131     env->cp15.c0_cpuid = (value & (1 << 5)) ?
4132         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
4133 }
4134 
4135 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
4136                                 uint64_t value)
4137 {
4138     env->cp15.c15_threadid = value & 0xffff;
4139 }
4140 
4141 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
4142                            uint64_t value)
4143 {
4144     /* Wait-for-interrupt (deprecated) */
4145     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
4146 }
4147 
4148 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
4149                                   uint64_t value)
4150 {
4151     /* On OMAP there are registers indicating the max/min index of dcache lines
4152      * containing a dirty line; cache flush operations have to reset these.
4153      */
4154     env->cp15.c15_i_max = 0x000;
4155     env->cp15.c15_i_min = 0xff0;
4156 }
4157 
4158 static const ARMCPRegInfo omap_cp_reginfo[] = {
4159     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
4160       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
4161       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
4162       .resetvalue = 0, },
4163     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
4164       .access = PL1_RW, .type = ARM_CP_NOP },
4165     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
4166       .access = PL1_RW,
4167       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
4168       .writefn = omap_ticonfig_write },
4169     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
4170       .access = PL1_RW,
4171       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
4172     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
4173       .access = PL1_RW, .resetvalue = 0xff0,
4174       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
4175     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
4176       .access = PL1_RW,
4177       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
4178       .writefn = omap_threadid_write },
4179     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
4180       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4181       .type = ARM_CP_NO_RAW,
4182       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
4183     /* TODO: Peripheral port remap register:
4184      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
4185      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
4186      * when MMU is off.
4187      */
4188     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
4189       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
4190       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
4191       .writefn = omap_cachemaint_write },
4192     { .name = "C9", .cp = 15, .crn = 9,
4193       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
4194       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
4195     REGINFO_SENTINEL
4196 };
4197 
4198 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4199                               uint64_t value)
4200 {
4201     env->cp15.c15_cpar = value & 0x3fff;
4202 }
4203 
4204 static const ARMCPRegInfo xscale_cp_reginfo[] = {
4205     { .name = "XSCALE_CPAR",
4206       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4207       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
4208       .writefn = xscale_cpar_write, },
4209     { .name = "XSCALE_AUXCR",
4210       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
4211       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
4212       .resetvalue = 0, },
4213     /* XScale specific cache-lockdown: since we have no cache we NOP these
4214      * and hope the guest does not really rely on cache behaviour.
4215      */
4216     { .name = "XSCALE_LOCK_ICACHE_LINE",
4217       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
4218       .access = PL1_W, .type = ARM_CP_NOP },
4219     { .name = "XSCALE_UNLOCK_ICACHE",
4220       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
4221       .access = PL1_W, .type = ARM_CP_NOP },
4222     { .name = "XSCALE_DCACHE_LOCK",
4223       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
4224       .access = PL1_RW, .type = ARM_CP_NOP },
4225     { .name = "XSCALE_UNLOCK_DCACHE",
4226       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
4227       .access = PL1_W, .type = ARM_CP_NOP },
4228     REGINFO_SENTINEL
4229 };
4230 
4231 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
4232     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
4233      * implementation of this implementation-defined space.
4234      * Ideally this should eventually disappear in favour of actually
4235      * implementing the correct behaviour for all cores.
4236      */
4237     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
4238       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4239       .access = PL1_RW,
4240       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
4241       .resetvalue = 0 },
4242     REGINFO_SENTINEL
4243 };
4244 
4245 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
4246     /* Cache status: RAZ because we have no cache so it's always clean */
4247     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
4248       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4249       .resetvalue = 0 },
4250     REGINFO_SENTINEL
4251 };
4252 
4253 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
4254     /* We never have a a block transfer operation in progress */
4255     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
4256       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4257       .resetvalue = 0 },
4258     /* The cache ops themselves: these all NOP for QEMU */
4259     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
4260       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4261     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
4262       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4263     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
4264       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4265     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4266       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4267     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4268       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4269     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4270       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4271     REGINFO_SENTINEL
4272 };
4273 
4274 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4275     /* The cache test-and-clean instructions always return (1 << 30)
4276      * to indicate that there are no dirty cache lines.
4277      */
4278     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4279       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4280       .resetvalue = (1 << 30) },
4281     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4282       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4283       .resetvalue = (1 << 30) },
4284     REGINFO_SENTINEL
4285 };
4286 
4287 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4288     /* Ignore ReadBuffer accesses */
4289     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4290       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4291       .access = PL1_RW, .resetvalue = 0,
4292       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4293     REGINFO_SENTINEL
4294 };
4295 
4296 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4297 {
4298     unsigned int cur_el = arm_current_el(env);
4299 
4300     if (arm_is_el2_enabled(env) && cur_el == 1) {
4301         return env->cp15.vpidr_el2;
4302     }
4303     return raw_read(env, ri);
4304 }
4305 
4306 static uint64_t mpidr_read_val(CPUARMState *env)
4307 {
4308     ARMCPU *cpu = env_archcpu(env);
4309     uint64_t mpidr = cpu->mp_affinity;
4310 
4311     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4312         mpidr |= (1U << 31);
4313         /* Cores which are uniprocessor (non-coherent)
4314          * but still implement the MP extensions set
4315          * bit 30. (For instance, Cortex-R5).
4316          */
4317         if (cpu->mp_is_up) {
4318             mpidr |= (1u << 30);
4319         }
4320     }
4321     return mpidr;
4322 }
4323 
4324 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4325 {
4326     unsigned int cur_el = arm_current_el(env);
4327 
4328     if (arm_is_el2_enabled(env) && cur_el == 1) {
4329         return env->cp15.vmpidr_el2;
4330     }
4331     return mpidr_read_val(env);
4332 }
4333 
4334 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4335     /* NOP AMAIR0/1 */
4336     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4337       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4338       .access = PL1_RW, .accessfn = access_tvm_trvm,
4339       .type = ARM_CP_CONST, .resetvalue = 0 },
4340     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4341     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4342       .access = PL1_RW, .accessfn = access_tvm_trvm,
4343       .type = ARM_CP_CONST, .resetvalue = 0 },
4344     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4345       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4346       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4347                              offsetof(CPUARMState, cp15.par_ns)} },
4348     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4349       .access = PL1_RW, .accessfn = access_tvm_trvm,
4350       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4351       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4352                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4353       .writefn = vmsa_ttbr_write, },
4354     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4355       .access = PL1_RW, .accessfn = access_tvm_trvm,
4356       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4357       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4358                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4359       .writefn = vmsa_ttbr_write, },
4360     REGINFO_SENTINEL
4361 };
4362 
4363 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4364 {
4365     return vfp_get_fpcr(env);
4366 }
4367 
4368 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4369                             uint64_t value)
4370 {
4371     vfp_set_fpcr(env, value);
4372 }
4373 
4374 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4375 {
4376     return vfp_get_fpsr(env);
4377 }
4378 
4379 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4380                             uint64_t value)
4381 {
4382     vfp_set_fpsr(env, value);
4383 }
4384 
4385 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4386                                        bool isread)
4387 {
4388     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4389         return CP_ACCESS_TRAP;
4390     }
4391     return CP_ACCESS_OK;
4392 }
4393 
4394 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4395                             uint64_t value)
4396 {
4397     env->daif = value & PSTATE_DAIF;
4398 }
4399 
4400 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4401 {
4402     return env->pstate & PSTATE_PAN;
4403 }
4404 
4405 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4406                            uint64_t value)
4407 {
4408     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4409 }
4410 
4411 static const ARMCPRegInfo pan_reginfo = {
4412     .name = "PAN", .state = ARM_CP_STATE_AA64,
4413     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4414     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4415     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4416 };
4417 
4418 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4419 {
4420     return env->pstate & PSTATE_UAO;
4421 }
4422 
4423 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4424                            uint64_t value)
4425 {
4426     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4427 }
4428 
4429 static const ARMCPRegInfo uao_reginfo = {
4430     .name = "UAO", .state = ARM_CP_STATE_AA64,
4431     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4432     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4433     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4434 };
4435 
4436 static uint64_t aa64_dit_read(CPUARMState *env, const ARMCPRegInfo *ri)
4437 {
4438     return env->pstate & PSTATE_DIT;
4439 }
4440 
4441 static void aa64_dit_write(CPUARMState *env, const ARMCPRegInfo *ri,
4442                            uint64_t value)
4443 {
4444     env->pstate = (env->pstate & ~PSTATE_DIT) | (value & PSTATE_DIT);
4445 }
4446 
4447 static const ARMCPRegInfo dit_reginfo = {
4448     .name = "DIT", .state = ARM_CP_STATE_AA64,
4449     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 5,
4450     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4451     .readfn = aa64_dit_read, .writefn = aa64_dit_write
4452 };
4453 
4454 static uint64_t aa64_ssbs_read(CPUARMState *env, const ARMCPRegInfo *ri)
4455 {
4456     return env->pstate & PSTATE_SSBS;
4457 }
4458 
4459 static void aa64_ssbs_write(CPUARMState *env, const ARMCPRegInfo *ri,
4460                            uint64_t value)
4461 {
4462     env->pstate = (env->pstate & ~PSTATE_SSBS) | (value & PSTATE_SSBS);
4463 }
4464 
4465 static const ARMCPRegInfo ssbs_reginfo = {
4466     .name = "SSBS", .state = ARM_CP_STATE_AA64,
4467     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 6,
4468     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4469     .readfn = aa64_ssbs_read, .writefn = aa64_ssbs_write
4470 };
4471 
4472 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4473                                               const ARMCPRegInfo *ri,
4474                                               bool isread)
4475 {
4476     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4477     switch (arm_current_el(env)) {
4478     case 0:
4479         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4480         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4481             return CP_ACCESS_TRAP;
4482         }
4483         /* fall through */
4484     case 1:
4485         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4486         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4487             return CP_ACCESS_TRAP_EL2;
4488         }
4489         break;
4490     }
4491     return CP_ACCESS_OK;
4492 }
4493 
4494 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4495                                               const ARMCPRegInfo *ri,
4496                                               bool isread)
4497 {
4498     /* Cache invalidate/clean to Point of Unification... */
4499     switch (arm_current_el(env)) {
4500     case 0:
4501         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4502         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4503             return CP_ACCESS_TRAP;
4504         }
4505         /* fall through */
4506     case 1:
4507         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4508         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4509             return CP_ACCESS_TRAP_EL2;
4510         }
4511         break;
4512     }
4513     return CP_ACCESS_OK;
4514 }
4515 
4516 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4517  * Page D4-1736 (DDI0487A.b)
4518  */
4519 
4520 static int vae1_tlbmask(CPUARMState *env)
4521 {
4522     uint64_t hcr = arm_hcr_el2_eff(env);
4523     uint16_t mask;
4524 
4525     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4526         mask = ARMMMUIdxBit_E20_2 |
4527                ARMMMUIdxBit_E20_2_PAN |
4528                ARMMMUIdxBit_E20_0;
4529     } else {
4530         mask = ARMMMUIdxBit_E10_1 |
4531                ARMMMUIdxBit_E10_1_PAN |
4532                ARMMMUIdxBit_E10_0;
4533     }
4534 
4535     if (arm_is_secure_below_el3(env)) {
4536         mask >>= ARM_MMU_IDX_A_NS;
4537     }
4538 
4539     return mask;
4540 }
4541 
4542 /* Return 56 if TBI is enabled, 64 otherwise. */
4543 static int tlbbits_for_regime(CPUARMState *env, ARMMMUIdx mmu_idx,
4544                               uint64_t addr)
4545 {
4546     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
4547     int tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
4548     int select = extract64(addr, 55, 1);
4549 
4550     return (tbi >> select) & 1 ? 56 : 64;
4551 }
4552 
4553 static int vae1_tlbbits(CPUARMState *env, uint64_t addr)
4554 {
4555     uint64_t hcr = arm_hcr_el2_eff(env);
4556     ARMMMUIdx mmu_idx;
4557 
4558     /* Only the regime of the mmu_idx below is significant. */
4559     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4560         mmu_idx = ARMMMUIdx_E20_0;
4561     } else {
4562         mmu_idx = ARMMMUIdx_E10_0;
4563     }
4564 
4565     if (arm_is_secure_below_el3(env)) {
4566         mmu_idx &= ~ARM_MMU_IDX_A_NS;
4567     }
4568 
4569     return tlbbits_for_regime(env, mmu_idx, addr);
4570 }
4571 
4572 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4573                                       uint64_t value)
4574 {
4575     CPUState *cs = env_cpu(env);
4576     int mask = vae1_tlbmask(env);
4577 
4578     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4579 }
4580 
4581 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4582                                     uint64_t value)
4583 {
4584     CPUState *cs = env_cpu(env);
4585     int mask = vae1_tlbmask(env);
4586 
4587     if (tlb_force_broadcast(env)) {
4588         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4589     } else {
4590         tlb_flush_by_mmuidx(cs, mask);
4591     }
4592 }
4593 
4594 static int alle1_tlbmask(CPUARMState *env)
4595 {
4596     /*
4597      * Note that the 'ALL' scope must invalidate both stage 1 and
4598      * stage 2 translations, whereas most other scopes only invalidate
4599      * stage 1 translations.
4600      */
4601     if (arm_is_secure_below_el3(env)) {
4602         return ARMMMUIdxBit_SE10_1 |
4603                ARMMMUIdxBit_SE10_1_PAN |
4604                ARMMMUIdxBit_SE10_0;
4605     } else {
4606         return ARMMMUIdxBit_E10_1 |
4607                ARMMMUIdxBit_E10_1_PAN |
4608                ARMMMUIdxBit_E10_0;
4609     }
4610 }
4611 
4612 static int e2_tlbmask(CPUARMState *env)
4613 {
4614     if (arm_is_secure_below_el3(env)) {
4615         return ARMMMUIdxBit_SE20_0 |
4616                ARMMMUIdxBit_SE20_2 |
4617                ARMMMUIdxBit_SE20_2_PAN |
4618                ARMMMUIdxBit_SE2;
4619     } else {
4620         return ARMMMUIdxBit_E20_0 |
4621                ARMMMUIdxBit_E20_2 |
4622                ARMMMUIdxBit_E20_2_PAN |
4623                ARMMMUIdxBit_E2;
4624     }
4625 }
4626 
4627 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4628                                   uint64_t value)
4629 {
4630     CPUState *cs = env_cpu(env);
4631     int mask = alle1_tlbmask(env);
4632 
4633     tlb_flush_by_mmuidx(cs, mask);
4634 }
4635 
4636 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4637                                   uint64_t value)
4638 {
4639     CPUState *cs = env_cpu(env);
4640     int mask = e2_tlbmask(env);
4641 
4642     tlb_flush_by_mmuidx(cs, mask);
4643 }
4644 
4645 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4646                                   uint64_t value)
4647 {
4648     ARMCPU *cpu = env_archcpu(env);
4649     CPUState *cs = CPU(cpu);
4650 
4651     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4652 }
4653 
4654 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4655                                     uint64_t value)
4656 {
4657     CPUState *cs = env_cpu(env);
4658     int mask = alle1_tlbmask(env);
4659 
4660     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4661 }
4662 
4663 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4664                                     uint64_t value)
4665 {
4666     CPUState *cs = env_cpu(env);
4667     int mask = e2_tlbmask(env);
4668 
4669     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4670 }
4671 
4672 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4673                                     uint64_t value)
4674 {
4675     CPUState *cs = env_cpu(env);
4676 
4677     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4678 }
4679 
4680 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4681                                  uint64_t value)
4682 {
4683     /* Invalidate by VA, EL2
4684      * Currently handles both VAE2 and VALE2, since we don't support
4685      * flush-last-level-only.
4686      */
4687     CPUState *cs = env_cpu(env);
4688     int mask = e2_tlbmask(env);
4689     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4690 
4691     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4692 }
4693 
4694 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4695                                  uint64_t value)
4696 {
4697     /* Invalidate by VA, EL3
4698      * Currently handles both VAE3 and VALE3, since we don't support
4699      * flush-last-level-only.
4700      */
4701     ARMCPU *cpu = env_archcpu(env);
4702     CPUState *cs = CPU(cpu);
4703     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4704 
4705     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4706 }
4707 
4708 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4709                                    uint64_t value)
4710 {
4711     CPUState *cs = env_cpu(env);
4712     int mask = vae1_tlbmask(env);
4713     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4714     int bits = vae1_tlbbits(env, pageaddr);
4715 
4716     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4717 }
4718 
4719 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4720                                  uint64_t value)
4721 {
4722     /* Invalidate by VA, EL1&0 (AArch64 version).
4723      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4724      * since we don't support flush-for-specific-ASID-only or
4725      * flush-last-level-only.
4726      */
4727     CPUState *cs = env_cpu(env);
4728     int mask = vae1_tlbmask(env);
4729     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4730     int bits = vae1_tlbbits(env, pageaddr);
4731 
4732     if (tlb_force_broadcast(env)) {
4733         tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4734     } else {
4735         tlb_flush_page_bits_by_mmuidx(cs, pageaddr, mask, bits);
4736     }
4737 }
4738 
4739 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4740                                    uint64_t value)
4741 {
4742     CPUState *cs = env_cpu(env);
4743     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4744     bool secure = arm_is_secure_below_el3(env);
4745     int mask = secure ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2;
4746     int bits = tlbbits_for_regime(env, secure ? ARMMMUIdx_E2 : ARMMMUIdx_SE2,
4747                                   pageaddr);
4748 
4749     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4750 }
4751 
4752 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4753                                    uint64_t value)
4754 {
4755     CPUState *cs = env_cpu(env);
4756     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4757     int bits = tlbbits_for_regime(env, ARMMMUIdx_SE3, pageaddr);
4758 
4759     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr,
4760                                                   ARMMMUIdxBit_SE3, bits);
4761 }
4762 
4763 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4764                                       bool isread)
4765 {
4766     int cur_el = arm_current_el(env);
4767 
4768     if (cur_el < 2) {
4769         uint64_t hcr = arm_hcr_el2_eff(env);
4770 
4771         if (cur_el == 0) {
4772             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4773                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4774                     return CP_ACCESS_TRAP_EL2;
4775                 }
4776             } else {
4777                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4778                     return CP_ACCESS_TRAP;
4779                 }
4780                 if (hcr & HCR_TDZ) {
4781                     return CP_ACCESS_TRAP_EL2;
4782                 }
4783             }
4784         } else if (hcr & HCR_TDZ) {
4785             return CP_ACCESS_TRAP_EL2;
4786         }
4787     }
4788     return CP_ACCESS_OK;
4789 }
4790 
4791 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4792 {
4793     ARMCPU *cpu = env_archcpu(env);
4794     int dzp_bit = 1 << 4;
4795 
4796     /* DZP indicates whether DC ZVA access is allowed */
4797     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4798         dzp_bit = 0;
4799     }
4800     return cpu->dcz_blocksize | dzp_bit;
4801 }
4802 
4803 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4804                                     bool isread)
4805 {
4806     if (!(env->pstate & PSTATE_SP)) {
4807         /* Access to SP_EL0 is undefined if it's being used as
4808          * the stack pointer.
4809          */
4810         return CP_ACCESS_TRAP_UNCATEGORIZED;
4811     }
4812     return CP_ACCESS_OK;
4813 }
4814 
4815 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4816 {
4817     return env->pstate & PSTATE_SP;
4818 }
4819 
4820 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4821 {
4822     update_spsel(env, val);
4823 }
4824 
4825 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4826                         uint64_t value)
4827 {
4828     ARMCPU *cpu = env_archcpu(env);
4829 
4830     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4831         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4832         value &= ~SCTLR_M;
4833     }
4834 
4835     /* ??? Lots of these bits are not implemented.  */
4836 
4837     if (ri->state == ARM_CP_STATE_AA64 && !cpu_isar_feature(aa64_mte, cpu)) {
4838         if (ri->opc1 == 6) { /* SCTLR_EL3 */
4839             value &= ~(SCTLR_ITFSB | SCTLR_TCF | SCTLR_ATA);
4840         } else {
4841             value &= ~(SCTLR_ITFSB | SCTLR_TCF0 | SCTLR_TCF |
4842                        SCTLR_ATA0 | SCTLR_ATA);
4843         }
4844     }
4845 
4846     if (raw_read(env, ri) == value) {
4847         /* Skip the TLB flush if nothing actually changed; Linux likes
4848          * to do a lot of pointless SCTLR writes.
4849          */
4850         return;
4851     }
4852 
4853     raw_write(env, ri, value);
4854 
4855     /* This may enable/disable the MMU, so do a TLB flush.  */
4856     tlb_flush(CPU(cpu));
4857 
4858     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4859         /*
4860          * Normally we would always end the TB on an SCTLR write; see the
4861          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
4862          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
4863          * of hflags from the translator, so do it here.
4864          */
4865         arm_rebuild_hflags(env);
4866     }
4867 }
4868 
4869 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
4870                                      bool isread)
4871 {
4872     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
4873         return CP_ACCESS_TRAP_FP_EL2;
4874     }
4875     if (env->cp15.cptr_el[3] & CPTR_TFP) {
4876         return CP_ACCESS_TRAP_FP_EL3;
4877     }
4878     return CP_ACCESS_OK;
4879 }
4880 
4881 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4882                        uint64_t value)
4883 {
4884     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
4885 }
4886 
4887 static const ARMCPRegInfo v8_cp_reginfo[] = {
4888     /* Minimal set of EL0-visible registers. This will need to be expanded
4889      * significantly for system emulation of AArch64 CPUs.
4890      */
4891     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
4892       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
4893       .access = PL0_RW, .type = ARM_CP_NZCV },
4894     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
4895       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
4896       .type = ARM_CP_NO_RAW,
4897       .access = PL0_RW, .accessfn = aa64_daif_access,
4898       .fieldoffset = offsetof(CPUARMState, daif),
4899       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
4900     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
4901       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
4902       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4903       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
4904     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
4905       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
4906       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
4907       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
4908     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
4909       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
4910       .access = PL0_R, .type = ARM_CP_NO_RAW,
4911       .readfn = aa64_dczid_read },
4912     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
4913       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
4914       .access = PL0_W, .type = ARM_CP_DC_ZVA,
4915 #ifndef CONFIG_USER_ONLY
4916       /* Avoid overhead of an access check that always passes in user-mode */
4917       .accessfn = aa64_zva_access,
4918 #endif
4919     },
4920     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
4921       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
4922       .access = PL1_R, .type = ARM_CP_CURRENTEL },
4923     /* Cache ops: all NOPs since we don't emulate caches */
4924     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
4925       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
4926       .access = PL1_W, .type = ARM_CP_NOP,
4927       .accessfn = aa64_cacheop_pou_access },
4928     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
4929       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
4930       .access = PL1_W, .type = ARM_CP_NOP,
4931       .accessfn = aa64_cacheop_pou_access },
4932     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
4933       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
4934       .access = PL0_W, .type = ARM_CP_NOP,
4935       .accessfn = aa64_cacheop_pou_access },
4936     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
4937       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
4938       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
4939       .type = ARM_CP_NOP },
4940     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
4941       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
4942       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4943     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
4944       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
4945       .access = PL0_W, .type = ARM_CP_NOP,
4946       .accessfn = aa64_cacheop_poc_access },
4947     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
4948       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
4949       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4950     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
4951       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
4952       .access = PL0_W, .type = ARM_CP_NOP,
4953       .accessfn = aa64_cacheop_pou_access },
4954     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
4955       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
4956       .access = PL0_W, .type = ARM_CP_NOP,
4957       .accessfn = aa64_cacheop_poc_access },
4958     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
4959       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
4960       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
4961     /* TLBI operations */
4962     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
4963       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
4964       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4965       .writefn = tlbi_aa64_vmalle1is_write },
4966     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
4967       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
4968       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4969       .writefn = tlbi_aa64_vae1is_write },
4970     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
4971       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
4972       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4973       .writefn = tlbi_aa64_vmalle1is_write },
4974     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
4975       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
4976       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4977       .writefn = tlbi_aa64_vae1is_write },
4978     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
4979       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
4980       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4981       .writefn = tlbi_aa64_vae1is_write },
4982     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
4983       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
4984       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4985       .writefn = tlbi_aa64_vae1is_write },
4986     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
4987       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
4988       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4989       .writefn = tlbi_aa64_vmalle1_write },
4990     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
4991       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
4992       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4993       .writefn = tlbi_aa64_vae1_write },
4994     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
4995       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
4996       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
4997       .writefn = tlbi_aa64_vmalle1_write },
4998     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
4999       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
5000       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5001       .writefn = tlbi_aa64_vae1_write },
5002     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
5003       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
5004       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5005       .writefn = tlbi_aa64_vae1_write },
5006     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
5007       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
5008       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5009       .writefn = tlbi_aa64_vae1_write },
5010     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
5011       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5012       .access = PL2_W, .type = ARM_CP_NOP },
5013     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
5014       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5015       .access = PL2_W, .type = ARM_CP_NOP },
5016     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
5017       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5018       .access = PL2_W, .type = ARM_CP_NO_RAW,
5019       .writefn = tlbi_aa64_alle1is_write },
5020     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
5021       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
5022       .access = PL2_W, .type = ARM_CP_NO_RAW,
5023       .writefn = tlbi_aa64_alle1is_write },
5024     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
5025       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5026       .access = PL2_W, .type = ARM_CP_NOP },
5027     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
5028       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5029       .access = PL2_W, .type = ARM_CP_NOP },
5030     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
5031       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5032       .access = PL2_W, .type = ARM_CP_NO_RAW,
5033       .writefn = tlbi_aa64_alle1_write },
5034     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
5035       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
5036       .access = PL2_W, .type = ARM_CP_NO_RAW,
5037       .writefn = tlbi_aa64_alle1is_write },
5038 #ifndef CONFIG_USER_ONLY
5039     /* 64 bit address translation operations */
5040     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
5041       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
5042       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5043       .writefn = ats_write64 },
5044     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
5045       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
5046       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5047       .writefn = ats_write64 },
5048     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
5049       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
5050       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5051       .writefn = ats_write64 },
5052     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
5053       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
5054       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5055       .writefn = ats_write64 },
5056     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
5057       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
5058       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5059       .writefn = ats_write64 },
5060     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
5061       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
5062       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5063       .writefn = ats_write64 },
5064     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
5065       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
5066       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5067       .writefn = ats_write64 },
5068     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
5069       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
5070       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5071       .writefn = ats_write64 },
5072     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
5073     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
5074       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
5075       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5076       .writefn = ats_write64 },
5077     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
5078       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
5079       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5080       .writefn = ats_write64 },
5081     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
5082       .type = ARM_CP_ALIAS,
5083       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
5084       .access = PL1_RW, .resetvalue = 0,
5085       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
5086       .writefn = par_write },
5087 #endif
5088     /* TLB invalidate last level of translation table walk */
5089     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
5090       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5091       .writefn = tlbimva_is_write },
5092     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
5093       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5094       .writefn = tlbimvaa_is_write },
5095     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
5096       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5097       .writefn = tlbimva_write },
5098     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
5099       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5100       .writefn = tlbimvaa_write },
5101     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5102       .type = ARM_CP_NO_RAW, .access = PL2_W,
5103       .writefn = tlbimva_hyp_write },
5104     { .name = "TLBIMVALHIS",
5105       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5106       .type = ARM_CP_NO_RAW, .access = PL2_W,
5107       .writefn = tlbimva_hyp_is_write },
5108     { .name = "TLBIIPAS2",
5109       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5110       .type = ARM_CP_NOP, .access = PL2_W },
5111     { .name = "TLBIIPAS2IS",
5112       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5113       .type = ARM_CP_NOP, .access = PL2_W },
5114     { .name = "TLBIIPAS2L",
5115       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5116       .type = ARM_CP_NOP, .access = PL2_W },
5117     { .name = "TLBIIPAS2LIS",
5118       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5119       .type = ARM_CP_NOP, .access = PL2_W },
5120     /* 32 bit cache operations */
5121     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5122       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5123     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5124       .type = ARM_CP_NOP, .access = PL1_W },
5125     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5126       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5127     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5128       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5129     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5130       .type = ARM_CP_NOP, .access = PL1_W },
5131     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5132       .type = ARM_CP_NOP, .access = PL1_W },
5133     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5134       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5135     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5136       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5137     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5138       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5139     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5140       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5141     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5142       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5143     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5144       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5145     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5146       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5147     /* MMU Domain access control / MPU write buffer control */
5148     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5149       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5150       .writefn = dacr_write, .raw_writefn = raw_write,
5151       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5152                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5153     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5154       .type = ARM_CP_ALIAS,
5155       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5156       .access = PL1_RW,
5157       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5158     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5159       .type = ARM_CP_ALIAS,
5160       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5161       .access = PL1_RW,
5162       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5163     /* We rely on the access checks not allowing the guest to write to the
5164      * state field when SPSel indicates that it's being used as the stack
5165      * pointer.
5166      */
5167     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5168       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5169       .access = PL1_RW, .accessfn = sp_el0_access,
5170       .type = ARM_CP_ALIAS,
5171       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5172     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5173       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5174       .access = PL2_RW, .type = ARM_CP_ALIAS,
5175       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5176     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5177       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5178       .type = ARM_CP_NO_RAW,
5179       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5180     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5181       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5182       .type = ARM_CP_ALIAS,
5183       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
5184       .access = PL2_RW, .accessfn = fpexc32_access },
5185     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5186       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5187       .access = PL2_RW, .resetvalue = 0,
5188       .writefn = dacr_write, .raw_writefn = raw_write,
5189       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5190     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5191       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5192       .access = PL2_RW, .resetvalue = 0,
5193       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5194     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5195       .type = ARM_CP_ALIAS,
5196       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5197       .access = PL2_RW,
5198       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5199     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5200       .type = ARM_CP_ALIAS,
5201       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5202       .access = PL2_RW,
5203       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5204     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5205       .type = ARM_CP_ALIAS,
5206       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5207       .access = PL2_RW,
5208       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5209     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5210       .type = ARM_CP_ALIAS,
5211       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5212       .access = PL2_RW,
5213       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5214     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5215       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5216       .resetvalue = 0,
5217       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5218     { .name = "SDCR", .type = ARM_CP_ALIAS,
5219       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5220       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5221       .writefn = sdcr_write,
5222       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5223     REGINFO_SENTINEL
5224 };
5225 
5226 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
5227 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
5228     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5229       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5230       .access = PL2_RW,
5231       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
5232     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
5233       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5234       .access = PL2_RW,
5235       .type = ARM_CP_CONST, .resetvalue = 0 },
5236     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5237       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5238       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5239     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5240       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5241       .access = PL2_RW,
5242       .type = ARM_CP_CONST, .resetvalue = 0 },
5243     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5244       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5245       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5246     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5247       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5248       .access = PL2_RW, .type = ARM_CP_CONST,
5249       .resetvalue = 0 },
5250     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5251       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5252       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5253     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5254       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5255       .access = PL2_RW, .type = ARM_CP_CONST,
5256       .resetvalue = 0 },
5257     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5258       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5259       .access = PL2_RW, .type = ARM_CP_CONST,
5260       .resetvalue = 0 },
5261     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5262       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5263       .access = PL2_RW, .type = ARM_CP_CONST,
5264       .resetvalue = 0 },
5265     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5266       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5267       .access = PL2_RW, .type = ARM_CP_CONST,
5268       .resetvalue = 0 },
5269     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5270       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5271       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5272     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
5273       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5274       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5275       .type = ARM_CP_CONST, .resetvalue = 0 },
5276     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5277       .cp = 15, .opc1 = 6, .crm = 2,
5278       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5279       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
5280     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5281       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5282       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5283     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5284       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5285       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5286     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5287       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5288       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5289     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5290       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5291       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5292     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5293       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5294       .resetvalue = 0 },
5295     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5296       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5297       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5298     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5299       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5300       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5301     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5302       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5303       .resetvalue = 0 },
5304     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5305       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5306       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5307     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5308       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5309       .resetvalue = 0 },
5310     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5311       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5312       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5313     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5314       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5315       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5316     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5317       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5318       .access = PL2_RW, .accessfn = access_tda,
5319       .type = ARM_CP_CONST, .resetvalue = 0 },
5320     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
5321       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5322       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5323       .type = ARM_CP_CONST, .resetvalue = 0 },
5324     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5325       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5326       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5327     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5328       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5329       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5330     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5331       .type = ARM_CP_CONST,
5332       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5333       .access = PL2_RW, .resetvalue = 0 },
5334     REGINFO_SENTINEL
5335 };
5336 
5337 /* Ditto, but for registers which exist in ARMv8 but not v7 */
5338 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
5339     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5340       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5341       .access = PL2_RW,
5342       .type = ARM_CP_CONST, .resetvalue = 0 },
5343     REGINFO_SENTINEL
5344 };
5345 
5346 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5347 {
5348     ARMCPU *cpu = env_archcpu(env);
5349 
5350     if (arm_feature(env, ARM_FEATURE_V8)) {
5351         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5352     } else {
5353         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5354     }
5355 
5356     if (arm_feature(env, ARM_FEATURE_EL3)) {
5357         valid_mask &= ~HCR_HCD;
5358     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5359         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5360          * However, if we're using the SMC PSCI conduit then QEMU is
5361          * effectively acting like EL3 firmware and so the guest at
5362          * EL2 should retain the ability to prevent EL1 from being
5363          * able to make SMC calls into the ersatz firmware, so in
5364          * that case HCR.TSC should be read/write.
5365          */
5366         valid_mask &= ~HCR_TSC;
5367     }
5368 
5369     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5370         if (cpu_isar_feature(aa64_vh, cpu)) {
5371             valid_mask |= HCR_E2H;
5372         }
5373         if (cpu_isar_feature(aa64_lor, cpu)) {
5374             valid_mask |= HCR_TLOR;
5375         }
5376         if (cpu_isar_feature(aa64_pauth, cpu)) {
5377             valid_mask |= HCR_API | HCR_APK;
5378         }
5379         if (cpu_isar_feature(aa64_mte, cpu)) {
5380             valid_mask |= HCR_ATA | HCR_DCT | HCR_TID5;
5381         }
5382     }
5383 
5384     /* Clear RES0 bits.  */
5385     value &= valid_mask;
5386 
5387     /*
5388      * These bits change the MMU setup:
5389      * HCR_VM enables stage 2 translation
5390      * HCR_PTW forbids certain page-table setups
5391      * HCR_DC disables stage1 and enables stage2 translation
5392      * HCR_DCT enables tagging on (disabled) stage1 translation
5393      */
5394     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC | HCR_DCT)) {
5395         tlb_flush(CPU(cpu));
5396     }
5397     env->cp15.hcr_el2 = value;
5398 
5399     /*
5400      * Updates to VI and VF require us to update the status of
5401      * virtual interrupts, which are the logical OR of these bits
5402      * and the state of the input lines from the GIC. (This requires
5403      * that we have the iothread lock, which is done by marking the
5404      * reginfo structs as ARM_CP_IO.)
5405      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5406      * possible for it to be taken immediately, because VIRQ and
5407      * VFIQ are masked unless running at EL0 or EL1, and HCR
5408      * can only be written at EL2.
5409      */
5410     g_assert(qemu_mutex_iothread_locked());
5411     arm_cpu_update_virq(cpu);
5412     arm_cpu_update_vfiq(cpu);
5413 }
5414 
5415 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5416 {
5417     do_hcr_write(env, value, 0);
5418 }
5419 
5420 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5421                           uint64_t value)
5422 {
5423     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5424     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5425     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5426 }
5427 
5428 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5429                          uint64_t value)
5430 {
5431     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5432     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5433     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5434 }
5435 
5436 /*
5437  * Return the effective value of HCR_EL2.
5438  * Bits that are not included here:
5439  * RW       (read from SCR_EL3.RW as needed)
5440  */
5441 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5442 {
5443     uint64_t ret = env->cp15.hcr_el2;
5444 
5445     if (!arm_is_el2_enabled(env)) {
5446         /*
5447          * "This register has no effect if EL2 is not enabled in the
5448          * current Security state".  This is ARMv8.4-SecEL2 speak for
5449          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5450          *
5451          * Prior to that, the language was "In an implementation that
5452          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5453          * as if this field is 0 for all purposes other than a direct
5454          * read or write access of HCR_EL2".  With lots of enumeration
5455          * on a per-field basis.  In current QEMU, this is condition
5456          * is arm_is_secure_below_el3.
5457          *
5458          * Since the v8.4 language applies to the entire register, and
5459          * appears to be backward compatible, use that.
5460          */
5461         return 0;
5462     }
5463 
5464     /*
5465      * For a cpu that supports both aarch64 and aarch32, we can set bits
5466      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5467      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5468      */
5469     if (!arm_el_is_aa64(env, 2)) {
5470         uint64_t aa32_valid;
5471 
5472         /*
5473          * These bits are up-to-date as of ARMv8.6.
5474          * For HCR, it's easiest to list just the 2 bits that are invalid.
5475          * For HCR2, list those that are valid.
5476          */
5477         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5478         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5479                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5480         ret &= aa32_valid;
5481     }
5482 
5483     if (ret & HCR_TGE) {
5484         /* These bits are up-to-date as of ARMv8.6.  */
5485         if (ret & HCR_E2H) {
5486             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5487                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5488                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5489                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5490                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5491                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5492         } else {
5493             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5494         }
5495         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5496                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5497                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5498                  HCR_TLOR);
5499     }
5500 
5501     return ret;
5502 }
5503 
5504 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5505                            uint64_t value)
5506 {
5507     /*
5508      * For A-profile AArch32 EL3, if NSACR.CP10
5509      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5510      */
5511     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5512         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5513         value &= ~(0x3 << 10);
5514         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5515     }
5516     env->cp15.cptr_el[2] = value;
5517 }
5518 
5519 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5520 {
5521     /*
5522      * For A-profile AArch32 EL3, if NSACR.CP10
5523      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5524      */
5525     uint64_t value = env->cp15.cptr_el[2];
5526 
5527     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5528         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5529         value |= 0x3 << 10;
5530     }
5531     return value;
5532 }
5533 
5534 static const ARMCPRegInfo el2_cp_reginfo[] = {
5535     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5536       .type = ARM_CP_IO,
5537       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5538       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5539       .writefn = hcr_write },
5540     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5541       .type = ARM_CP_ALIAS | ARM_CP_IO,
5542       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5543       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5544       .writefn = hcr_writelow },
5545     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5546       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5547       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5548     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5549       .type = ARM_CP_ALIAS,
5550       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5551       .access = PL2_RW,
5552       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5553     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5554       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5555       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5556     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5557       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5558       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5559     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5560       .type = ARM_CP_ALIAS,
5561       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5562       .access = PL2_RW,
5563       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5564     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5565       .type = ARM_CP_ALIAS,
5566       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5567       .access = PL2_RW,
5568       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5569     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5570       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5571       .access = PL2_RW, .writefn = vbar_write,
5572       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5573       .resetvalue = 0 },
5574     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5575       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5576       .access = PL3_RW, .type = ARM_CP_ALIAS,
5577       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5578     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5579       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5580       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5581       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5582       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5583     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5584       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5585       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5586       .resetvalue = 0 },
5587     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5588       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5589       .access = PL2_RW, .type = ARM_CP_ALIAS,
5590       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5591     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5592       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5593       .access = PL2_RW, .type = ARM_CP_CONST,
5594       .resetvalue = 0 },
5595     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5596     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5597       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5598       .access = PL2_RW, .type = ARM_CP_CONST,
5599       .resetvalue = 0 },
5600     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5601       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5602       .access = PL2_RW, .type = ARM_CP_CONST,
5603       .resetvalue = 0 },
5604     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5605       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5606       .access = PL2_RW, .type = ARM_CP_CONST,
5607       .resetvalue = 0 },
5608     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5609       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5610       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5611       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5612       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5613     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5614       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5615       .type = ARM_CP_ALIAS,
5616       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5617       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5618     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5619       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5620       .access = PL2_RW,
5621       /* no .writefn needed as this can't cause an ASID change;
5622        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5623        */
5624       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5625     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5626       .cp = 15, .opc1 = 6, .crm = 2,
5627       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5628       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5629       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5630       .writefn = vttbr_write },
5631     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5632       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5633       .access = PL2_RW, .writefn = vttbr_write,
5634       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5635     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5636       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5637       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5638       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5639     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5640       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5641       .access = PL2_RW, .resetvalue = 0,
5642       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5643     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5644       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5645       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5646       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5647     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5648       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5649       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5650     { .name = "TLBIALLNSNH",
5651       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5652       .type = ARM_CP_NO_RAW, .access = PL2_W,
5653       .writefn = tlbiall_nsnh_write },
5654     { .name = "TLBIALLNSNHIS",
5655       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5656       .type = ARM_CP_NO_RAW, .access = PL2_W,
5657       .writefn = tlbiall_nsnh_is_write },
5658     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5659       .type = ARM_CP_NO_RAW, .access = PL2_W,
5660       .writefn = tlbiall_hyp_write },
5661     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5662       .type = ARM_CP_NO_RAW, .access = PL2_W,
5663       .writefn = tlbiall_hyp_is_write },
5664     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5665       .type = ARM_CP_NO_RAW, .access = PL2_W,
5666       .writefn = tlbimva_hyp_write },
5667     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5668       .type = ARM_CP_NO_RAW, .access = PL2_W,
5669       .writefn = tlbimva_hyp_is_write },
5670     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5671       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5672       .type = ARM_CP_NO_RAW, .access = PL2_W,
5673       .writefn = tlbi_aa64_alle2_write },
5674     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5675       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5676       .type = ARM_CP_NO_RAW, .access = PL2_W,
5677       .writefn = tlbi_aa64_vae2_write },
5678     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5679       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5680       .access = PL2_W, .type = ARM_CP_NO_RAW,
5681       .writefn = tlbi_aa64_vae2_write },
5682     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5683       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5684       .access = PL2_W, .type = ARM_CP_NO_RAW,
5685       .writefn = tlbi_aa64_alle2is_write },
5686     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5687       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5688       .type = ARM_CP_NO_RAW, .access = PL2_W,
5689       .writefn = tlbi_aa64_vae2is_write },
5690     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5691       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5692       .access = PL2_W, .type = ARM_CP_NO_RAW,
5693       .writefn = tlbi_aa64_vae2is_write },
5694 #ifndef CONFIG_USER_ONLY
5695     /* Unlike the other EL2-related AT operations, these must
5696      * UNDEF from EL3 if EL2 is not implemented, which is why we
5697      * define them here rather than with the rest of the AT ops.
5698      */
5699     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5700       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5701       .access = PL2_W, .accessfn = at_s1e2_access,
5702       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5703     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5704       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5705       .access = PL2_W, .accessfn = at_s1e2_access,
5706       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5707     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5708      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5709      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5710      * to behave as if SCR.NS was 1.
5711      */
5712     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5713       .access = PL2_W,
5714       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5715     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5716       .access = PL2_W,
5717       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5718     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5719       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5720       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5721        * reset values as IMPDEF. We choose to reset to 3 to comply with
5722        * both ARMv7 and ARMv8.
5723        */
5724       .access = PL2_RW, .resetvalue = 3,
5725       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5726     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5727       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5728       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5729       .writefn = gt_cntvoff_write,
5730       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5731     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5732       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5733       .writefn = gt_cntvoff_write,
5734       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5735     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5736       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5737       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5738       .type = ARM_CP_IO, .access = PL2_RW,
5739       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5740     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5741       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5742       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5743       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5744     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5745       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5746       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5747       .resetfn = gt_hyp_timer_reset,
5748       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5749     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5750       .type = ARM_CP_IO,
5751       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5752       .access = PL2_RW,
5753       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5754       .resetvalue = 0,
5755       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5756 #endif
5757     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5758       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5759       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5760       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5761     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5762       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5763       .access = PL2_RW,
5764       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5765     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5766       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5767       .access = PL2_RW,
5768       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5769     REGINFO_SENTINEL
5770 };
5771 
5772 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5773     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5774       .type = ARM_CP_ALIAS | ARM_CP_IO,
5775       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5776       .access = PL2_RW,
5777       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5778       .writefn = hcr_writehigh },
5779     REGINFO_SENTINEL
5780 };
5781 
5782 static CPAccessResult sel2_access(CPUARMState *env, const ARMCPRegInfo *ri,
5783                                   bool isread)
5784 {
5785     if (arm_current_el(env) == 3 || arm_is_secure_below_el3(env)) {
5786         return CP_ACCESS_OK;
5787     }
5788     return CP_ACCESS_TRAP_UNCATEGORIZED;
5789 }
5790 
5791 static const ARMCPRegInfo el2_sec_cp_reginfo[] = {
5792     { .name = "VSTTBR_EL2", .state = ARM_CP_STATE_AA64,
5793       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 0,
5794       .access = PL2_RW, .accessfn = sel2_access,
5795       .fieldoffset = offsetof(CPUARMState, cp15.vsttbr_el2) },
5796     { .name = "VSTCR_EL2", .state = ARM_CP_STATE_AA64,
5797       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 2,
5798       .access = PL2_RW, .accessfn = sel2_access,
5799       .fieldoffset = offsetof(CPUARMState, cp15.vstcr_el2) },
5800     REGINFO_SENTINEL
5801 };
5802 
5803 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5804                                    bool isread)
5805 {
5806     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5807      * At Secure EL1 it traps to EL3 or EL2.
5808      */
5809     if (arm_current_el(env) == 3) {
5810         return CP_ACCESS_OK;
5811     }
5812     if (arm_is_secure_below_el3(env)) {
5813         if (env->cp15.scr_el3 & SCR_EEL2) {
5814             return CP_ACCESS_TRAP_EL2;
5815         }
5816         return CP_ACCESS_TRAP_EL3;
5817     }
5818     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5819     if (isread) {
5820         return CP_ACCESS_OK;
5821     }
5822     return CP_ACCESS_TRAP_UNCATEGORIZED;
5823 }
5824 
5825 static const ARMCPRegInfo el3_cp_reginfo[] = {
5826     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5827       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5828       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5829       .resetfn = scr_reset, .writefn = scr_write },
5830     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5831       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5832       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5833       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5834       .writefn = scr_write },
5835     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5836       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5837       .access = PL3_RW, .resetvalue = 0,
5838       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5839     { .name = "SDER",
5840       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5841       .access = PL3_RW, .resetvalue = 0,
5842       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5843     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5844       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5845       .writefn = vbar_write, .resetvalue = 0,
5846       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5847     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5848       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5849       .access = PL3_RW, .resetvalue = 0,
5850       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5851     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5852       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5853       .access = PL3_RW,
5854       /* no .writefn needed as this can't cause an ASID change;
5855        * we must provide a .raw_writefn and .resetfn because we handle
5856        * reset and migration for the AArch32 TTBCR(S), which might be
5857        * using mask and base_mask.
5858        */
5859       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
5860       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
5861     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
5862       .type = ARM_CP_ALIAS,
5863       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
5864       .access = PL3_RW,
5865       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
5866     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
5867       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
5868       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
5869     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
5870       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
5871       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
5872     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
5873       .type = ARM_CP_ALIAS,
5874       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
5875       .access = PL3_RW,
5876       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
5877     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
5878       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
5879       .access = PL3_RW, .writefn = vbar_write,
5880       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
5881       .resetvalue = 0 },
5882     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
5883       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
5884       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
5885       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
5886     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
5887       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
5888       .access = PL3_RW, .resetvalue = 0,
5889       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
5890     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
5891       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
5892       .access = PL3_RW, .type = ARM_CP_CONST,
5893       .resetvalue = 0 },
5894     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
5895       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
5896       .access = PL3_RW, .type = ARM_CP_CONST,
5897       .resetvalue = 0 },
5898     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
5899       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
5900       .access = PL3_RW, .type = ARM_CP_CONST,
5901       .resetvalue = 0 },
5902     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
5903       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
5904       .access = PL3_W, .type = ARM_CP_NO_RAW,
5905       .writefn = tlbi_aa64_alle3is_write },
5906     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
5907       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
5908       .access = PL3_W, .type = ARM_CP_NO_RAW,
5909       .writefn = tlbi_aa64_vae3is_write },
5910     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
5911       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
5912       .access = PL3_W, .type = ARM_CP_NO_RAW,
5913       .writefn = tlbi_aa64_vae3is_write },
5914     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
5915       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
5916       .access = PL3_W, .type = ARM_CP_NO_RAW,
5917       .writefn = tlbi_aa64_alle3_write },
5918     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
5919       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
5920       .access = PL3_W, .type = ARM_CP_NO_RAW,
5921       .writefn = tlbi_aa64_vae3_write },
5922     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
5923       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
5924       .access = PL3_W, .type = ARM_CP_NO_RAW,
5925       .writefn = tlbi_aa64_vae3_write },
5926     REGINFO_SENTINEL
5927 };
5928 
5929 #ifndef CONFIG_USER_ONLY
5930 /* Test if system register redirection is to occur in the current state.  */
5931 static bool redirect_for_e2h(CPUARMState *env)
5932 {
5933     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
5934 }
5935 
5936 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
5937 {
5938     CPReadFn *readfn;
5939 
5940     if (redirect_for_e2h(env)) {
5941         /* Switch to the saved EL2 version of the register.  */
5942         ri = ri->opaque;
5943         readfn = ri->readfn;
5944     } else {
5945         readfn = ri->orig_readfn;
5946     }
5947     if (readfn == NULL) {
5948         readfn = raw_read;
5949     }
5950     return readfn(env, ri);
5951 }
5952 
5953 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
5954                           uint64_t value)
5955 {
5956     CPWriteFn *writefn;
5957 
5958     if (redirect_for_e2h(env)) {
5959         /* Switch to the saved EL2 version of the register.  */
5960         ri = ri->opaque;
5961         writefn = ri->writefn;
5962     } else {
5963         writefn = ri->orig_writefn;
5964     }
5965     if (writefn == NULL) {
5966         writefn = raw_write;
5967     }
5968     writefn(env, ri, value);
5969 }
5970 
5971 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
5972 {
5973     struct E2HAlias {
5974         uint32_t src_key, dst_key, new_key;
5975         const char *src_name, *dst_name, *new_name;
5976         bool (*feature)(const ARMISARegisters *id);
5977     };
5978 
5979 #define K(op0, op1, crn, crm, op2) \
5980     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
5981 
5982     static const struct E2HAlias aliases[] = {
5983         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
5984           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
5985         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
5986           "CPACR", "CPTR_EL2", "CPACR_EL12" },
5987         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
5988           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
5989         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
5990           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
5991         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
5992           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
5993         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
5994           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
5995         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
5996           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
5997         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
5998           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
5999         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
6000           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
6001         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
6002           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
6003         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
6004           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
6005         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
6006           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
6007         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
6008           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
6009         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
6010           "VBAR", "VBAR_EL2", "VBAR_EL12" },
6011         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
6012           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
6013         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
6014           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
6015 
6016         /*
6017          * Note that redirection of ZCR is mentioned in the description
6018          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
6019          * not in the summary table.
6020          */
6021         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
6022           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
6023 
6024         { K(3, 0,  5, 6, 0), K(3, 4,  5, 6, 0), K(3, 5, 5, 6, 0),
6025           "TFSR_EL1", "TFSR_EL2", "TFSR_EL12", isar_feature_aa64_mte },
6026 
6027         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
6028         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
6029     };
6030 #undef K
6031 
6032     size_t i;
6033 
6034     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
6035         const struct E2HAlias *a = &aliases[i];
6036         ARMCPRegInfo *src_reg, *dst_reg;
6037 
6038         if (a->feature && !a->feature(&cpu->isar)) {
6039             continue;
6040         }
6041 
6042         src_reg = g_hash_table_lookup(cpu->cp_regs, &a->src_key);
6043         dst_reg = g_hash_table_lookup(cpu->cp_regs, &a->dst_key);
6044         g_assert(src_reg != NULL);
6045         g_assert(dst_reg != NULL);
6046 
6047         /* Cross-compare names to detect typos in the keys.  */
6048         g_assert(strcmp(src_reg->name, a->src_name) == 0);
6049         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
6050 
6051         /* None of the core system registers use opaque; we will.  */
6052         g_assert(src_reg->opaque == NULL);
6053 
6054         /* Create alias before redirection so we dup the right data. */
6055         if (a->new_key) {
6056             ARMCPRegInfo *new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
6057             uint32_t *new_key = g_memdup(&a->new_key, sizeof(uint32_t));
6058             bool ok;
6059 
6060             new_reg->name = a->new_name;
6061             new_reg->type |= ARM_CP_ALIAS;
6062             /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
6063             new_reg->access &= PL2_RW | PL3_RW;
6064 
6065             ok = g_hash_table_insert(cpu->cp_regs, new_key, new_reg);
6066             g_assert(ok);
6067         }
6068 
6069         src_reg->opaque = dst_reg;
6070         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
6071         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
6072         if (!src_reg->raw_readfn) {
6073             src_reg->raw_readfn = raw_read;
6074         }
6075         if (!src_reg->raw_writefn) {
6076             src_reg->raw_writefn = raw_write;
6077         }
6078         src_reg->readfn = el2_e2h_read;
6079         src_reg->writefn = el2_e2h_write;
6080     }
6081 }
6082 #endif
6083 
6084 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
6085                                      bool isread)
6086 {
6087     int cur_el = arm_current_el(env);
6088 
6089     if (cur_el < 2) {
6090         uint64_t hcr = arm_hcr_el2_eff(env);
6091 
6092         if (cur_el == 0) {
6093             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
6094                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
6095                     return CP_ACCESS_TRAP_EL2;
6096                 }
6097             } else {
6098                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
6099                     return CP_ACCESS_TRAP;
6100                 }
6101                 if (hcr & HCR_TID2) {
6102                     return CP_ACCESS_TRAP_EL2;
6103                 }
6104             }
6105         } else if (hcr & HCR_TID2) {
6106             return CP_ACCESS_TRAP_EL2;
6107         }
6108     }
6109 
6110     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
6111         return CP_ACCESS_TRAP_EL2;
6112     }
6113 
6114     return CP_ACCESS_OK;
6115 }
6116 
6117 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
6118                         uint64_t value)
6119 {
6120     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
6121      * read via a bit in OSLSR_EL1.
6122      */
6123     int oslock;
6124 
6125     if (ri->state == ARM_CP_STATE_AA32) {
6126         oslock = (value == 0xC5ACCE55);
6127     } else {
6128         oslock = value & 1;
6129     }
6130 
6131     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
6132 }
6133 
6134 static const ARMCPRegInfo debug_cp_reginfo[] = {
6135     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
6136      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
6137      * unlike DBGDRAR it is never accessible from EL0.
6138      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
6139      * accessor.
6140      */
6141     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
6142       .access = PL0_R, .accessfn = access_tdra,
6143       .type = ARM_CP_CONST, .resetvalue = 0 },
6144     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
6145       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6146       .access = PL1_R, .accessfn = access_tdra,
6147       .type = ARM_CP_CONST, .resetvalue = 0 },
6148     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
6149       .access = PL0_R, .accessfn = access_tdra,
6150       .type = ARM_CP_CONST, .resetvalue = 0 },
6151     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
6152     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
6153       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
6154       .access = PL1_RW, .accessfn = access_tda,
6155       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
6156       .resetvalue = 0 },
6157     /* MDCCSR_EL0, aka DBGDSCRint. This is a read-only mirror of MDSCR_EL1.
6158      * We don't implement the configurable EL0 access.
6159      */
6160     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_BOTH,
6161       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6162       .type = ARM_CP_ALIAS,
6163       .access = PL1_R, .accessfn = access_tda,
6164       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
6165     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
6166       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
6167       .access = PL1_W, .type = ARM_CP_NO_RAW,
6168       .accessfn = access_tdosa,
6169       .writefn = oslar_write },
6170     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
6171       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
6172       .access = PL1_R, .resetvalue = 10,
6173       .accessfn = access_tdosa,
6174       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
6175     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
6176     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
6177       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
6178       .access = PL1_RW, .accessfn = access_tdosa,
6179       .type = ARM_CP_NOP },
6180     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
6181      * implement vector catch debug events yet.
6182      */
6183     { .name = "DBGVCR",
6184       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6185       .access = PL1_RW, .accessfn = access_tda,
6186       .type = ARM_CP_NOP },
6187     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
6188      * to save and restore a 32-bit guest's DBGVCR)
6189      */
6190     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
6191       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
6192       .access = PL2_RW, .accessfn = access_tda,
6193       .type = ARM_CP_NOP },
6194     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6195      * Channel but Linux may try to access this register. The 32-bit
6196      * alias is DBGDCCINT.
6197      */
6198     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6199       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6200       .access = PL1_RW, .accessfn = access_tda,
6201       .type = ARM_CP_NOP },
6202     REGINFO_SENTINEL
6203 };
6204 
6205 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6206     /* 64 bit access versions of the (dummy) debug registers */
6207     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6208       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6209     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6210       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6211     REGINFO_SENTINEL
6212 };
6213 
6214 /* Return the exception level to which exceptions should be taken
6215  * via SVEAccessTrap.  If an exception should be routed through
6216  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6217  * take care of raising that exception.
6218  * C.f. the ARM pseudocode function CheckSVEEnabled.
6219  */
6220 int sve_exception_el(CPUARMState *env, int el)
6221 {
6222 #ifndef CONFIG_USER_ONLY
6223     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6224 
6225     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6226         bool disabled = false;
6227 
6228         /* The CPACR.ZEN controls traps to EL1:
6229          * 0, 2 : trap EL0 and EL1 accesses
6230          * 1    : trap only EL0 accesses
6231          * 3    : trap no accesses
6232          */
6233         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
6234             disabled = true;
6235         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
6236             disabled = el == 0;
6237         }
6238         if (disabled) {
6239             /* route_to_el2 */
6240             return hcr_el2 & HCR_TGE ? 2 : 1;
6241         }
6242 
6243         /* Check CPACR.FPEN.  */
6244         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
6245             disabled = true;
6246         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
6247             disabled = el == 0;
6248         }
6249         if (disabled) {
6250             return 0;
6251         }
6252     }
6253 
6254     /* CPTR_EL2.  Since TZ and TFP are positive,
6255      * they will be zero when EL2 is not present.
6256      */
6257     if (el <= 2 && arm_is_el2_enabled(env)) {
6258         if (env->cp15.cptr_el[2] & CPTR_TZ) {
6259             return 2;
6260         }
6261         if (env->cp15.cptr_el[2] & CPTR_TFP) {
6262             return 0;
6263         }
6264     }
6265 
6266     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6267     if (arm_feature(env, ARM_FEATURE_EL3)
6268         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6269         return 3;
6270     }
6271 #endif
6272     return 0;
6273 }
6274 
6275 static uint32_t sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6276 {
6277     uint32_t end_len;
6278 
6279     end_len = start_len &= 0xf;
6280     if (!test_bit(start_len, cpu->sve_vq_map)) {
6281         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6282         assert(end_len < start_len);
6283     }
6284     return end_len;
6285 }
6286 
6287 /*
6288  * Given that SVE is enabled, return the vector length for EL.
6289  */
6290 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6291 {
6292     ARMCPU *cpu = env_archcpu(env);
6293     uint32_t zcr_len = cpu->sve_max_vq - 1;
6294 
6295     if (el <= 1) {
6296         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6297     }
6298     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6299         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6300     }
6301     if (arm_feature(env, ARM_FEATURE_EL3)) {
6302         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6303     }
6304 
6305     return sve_zcr_get_valid_len(cpu, zcr_len);
6306 }
6307 
6308 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6309                       uint64_t value)
6310 {
6311     int cur_el = arm_current_el(env);
6312     int old_len = sve_zcr_len_for_el(env, cur_el);
6313     int new_len;
6314 
6315     /* Bits other than [3:0] are RAZ/WI.  */
6316     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6317     raw_write(env, ri, value & 0xf);
6318 
6319     /*
6320      * Because we arrived here, we know both FP and SVE are enabled;
6321      * otherwise we would have trapped access to the ZCR_ELn register.
6322      */
6323     new_len = sve_zcr_len_for_el(env, cur_el);
6324     if (new_len < old_len) {
6325         aarch64_sve_narrow_vq(env, new_len + 1);
6326     }
6327 }
6328 
6329 static const ARMCPRegInfo zcr_el1_reginfo = {
6330     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6331     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6332     .access = PL1_RW, .type = ARM_CP_SVE,
6333     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6334     .writefn = zcr_write, .raw_writefn = raw_write
6335 };
6336 
6337 static const ARMCPRegInfo zcr_el2_reginfo = {
6338     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6339     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6340     .access = PL2_RW, .type = ARM_CP_SVE,
6341     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6342     .writefn = zcr_write, .raw_writefn = raw_write
6343 };
6344 
6345 static const ARMCPRegInfo zcr_no_el2_reginfo = {
6346     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6347     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6348     .access = PL2_RW, .type = ARM_CP_SVE,
6349     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
6350 };
6351 
6352 static const ARMCPRegInfo zcr_el3_reginfo = {
6353     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6354     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6355     .access = PL3_RW, .type = ARM_CP_SVE,
6356     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6357     .writefn = zcr_write, .raw_writefn = raw_write
6358 };
6359 
6360 void hw_watchpoint_update(ARMCPU *cpu, int n)
6361 {
6362     CPUARMState *env = &cpu->env;
6363     vaddr len = 0;
6364     vaddr wvr = env->cp15.dbgwvr[n];
6365     uint64_t wcr = env->cp15.dbgwcr[n];
6366     int mask;
6367     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6368 
6369     if (env->cpu_watchpoint[n]) {
6370         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6371         env->cpu_watchpoint[n] = NULL;
6372     }
6373 
6374     if (!extract64(wcr, 0, 1)) {
6375         /* E bit clear : watchpoint disabled */
6376         return;
6377     }
6378 
6379     switch (extract64(wcr, 3, 2)) {
6380     case 0:
6381         /* LSC 00 is reserved and must behave as if the wp is disabled */
6382         return;
6383     case 1:
6384         flags |= BP_MEM_READ;
6385         break;
6386     case 2:
6387         flags |= BP_MEM_WRITE;
6388         break;
6389     case 3:
6390         flags |= BP_MEM_ACCESS;
6391         break;
6392     }
6393 
6394     /* Attempts to use both MASK and BAS fields simultaneously are
6395      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6396      * thus generating a watchpoint for every byte in the masked region.
6397      */
6398     mask = extract64(wcr, 24, 4);
6399     if (mask == 1 || mask == 2) {
6400         /* Reserved values of MASK; we must act as if the mask value was
6401          * some non-reserved value, or as if the watchpoint were disabled.
6402          * We choose the latter.
6403          */
6404         return;
6405     } else if (mask) {
6406         /* Watchpoint covers an aligned area up to 2GB in size */
6407         len = 1ULL << mask;
6408         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6409          * whether the watchpoint fires when the unmasked bits match; we opt
6410          * to generate the exceptions.
6411          */
6412         wvr &= ~(len - 1);
6413     } else {
6414         /* Watchpoint covers bytes defined by the byte address select bits */
6415         int bas = extract64(wcr, 5, 8);
6416         int basstart;
6417 
6418         if (extract64(wvr, 2, 1)) {
6419             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6420              * ignored, and BAS[3:0] define which bytes to watch.
6421              */
6422             bas &= 0xf;
6423         }
6424 
6425         if (bas == 0) {
6426             /* This must act as if the watchpoint is disabled */
6427             return;
6428         }
6429 
6430         /* The BAS bits are supposed to be programmed to indicate a contiguous
6431          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6432          * we fire for each byte in the word/doubleword addressed by the WVR.
6433          * We choose to ignore any non-zero bits after the first range of 1s.
6434          */
6435         basstart = ctz32(bas);
6436         len = cto32(bas >> basstart);
6437         wvr += basstart;
6438     }
6439 
6440     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6441                           &env->cpu_watchpoint[n]);
6442 }
6443 
6444 void hw_watchpoint_update_all(ARMCPU *cpu)
6445 {
6446     int i;
6447     CPUARMState *env = &cpu->env;
6448 
6449     /* Completely clear out existing QEMU watchpoints and our array, to
6450      * avoid possible stale entries following migration load.
6451      */
6452     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6453     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6454 
6455     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6456         hw_watchpoint_update(cpu, i);
6457     }
6458 }
6459 
6460 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6461                          uint64_t value)
6462 {
6463     ARMCPU *cpu = env_archcpu(env);
6464     int i = ri->crm;
6465 
6466     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
6467      * register reads and behaves as if values written are sign extended.
6468      * Bits [1:0] are RES0.
6469      */
6470     value = sextract64(value, 0, 49) & ~3ULL;
6471 
6472     raw_write(env, ri, value);
6473     hw_watchpoint_update(cpu, i);
6474 }
6475 
6476 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6477                          uint64_t value)
6478 {
6479     ARMCPU *cpu = env_archcpu(env);
6480     int i = ri->crm;
6481 
6482     raw_write(env, ri, value);
6483     hw_watchpoint_update(cpu, i);
6484 }
6485 
6486 void hw_breakpoint_update(ARMCPU *cpu, int n)
6487 {
6488     CPUARMState *env = &cpu->env;
6489     uint64_t bvr = env->cp15.dbgbvr[n];
6490     uint64_t bcr = env->cp15.dbgbcr[n];
6491     vaddr addr;
6492     int bt;
6493     int flags = BP_CPU;
6494 
6495     if (env->cpu_breakpoint[n]) {
6496         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6497         env->cpu_breakpoint[n] = NULL;
6498     }
6499 
6500     if (!extract64(bcr, 0, 1)) {
6501         /* E bit clear : watchpoint disabled */
6502         return;
6503     }
6504 
6505     bt = extract64(bcr, 20, 4);
6506 
6507     switch (bt) {
6508     case 4: /* unlinked address mismatch (reserved if AArch64) */
6509     case 5: /* linked address mismatch (reserved if AArch64) */
6510         qemu_log_mask(LOG_UNIMP,
6511                       "arm: address mismatch breakpoint types not implemented\n");
6512         return;
6513     case 0: /* unlinked address match */
6514     case 1: /* linked address match */
6515     {
6516         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
6517          * we behave as if the register was sign extended. Bits [1:0] are
6518          * RES0. The BAS field is used to allow setting breakpoints on 16
6519          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6520          * a bp will fire if the addresses covered by the bp and the addresses
6521          * covered by the insn overlap but the insn doesn't start at the
6522          * start of the bp address range. We choose to require the insn and
6523          * the bp to have the same address. The constraints on writing to
6524          * BAS enforced in dbgbcr_write mean we have only four cases:
6525          *  0b0000  => no breakpoint
6526          *  0b0011  => breakpoint on addr
6527          *  0b1100  => breakpoint on addr + 2
6528          *  0b1111  => breakpoint on addr
6529          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6530          */
6531         int bas = extract64(bcr, 5, 4);
6532         addr = sextract64(bvr, 0, 49) & ~3ULL;
6533         if (bas == 0) {
6534             return;
6535         }
6536         if (bas == 0xc) {
6537             addr += 2;
6538         }
6539         break;
6540     }
6541     case 2: /* unlinked context ID match */
6542     case 8: /* unlinked VMID match (reserved if no EL2) */
6543     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6544         qemu_log_mask(LOG_UNIMP,
6545                       "arm: unlinked context breakpoint types not implemented\n");
6546         return;
6547     case 9: /* linked VMID match (reserved if no EL2) */
6548     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6549     case 3: /* linked context ID match */
6550     default:
6551         /* We must generate no events for Linked context matches (unless
6552          * they are linked to by some other bp/wp, which is handled in
6553          * updates for the linking bp/wp). We choose to also generate no events
6554          * for reserved values.
6555          */
6556         return;
6557     }
6558 
6559     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6560 }
6561 
6562 void hw_breakpoint_update_all(ARMCPU *cpu)
6563 {
6564     int i;
6565     CPUARMState *env = &cpu->env;
6566 
6567     /* Completely clear out existing QEMU breakpoints and our array, to
6568      * avoid possible stale entries following migration load.
6569      */
6570     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6571     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6572 
6573     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6574         hw_breakpoint_update(cpu, i);
6575     }
6576 }
6577 
6578 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6579                          uint64_t value)
6580 {
6581     ARMCPU *cpu = env_archcpu(env);
6582     int i = ri->crm;
6583 
6584     raw_write(env, ri, value);
6585     hw_breakpoint_update(cpu, i);
6586 }
6587 
6588 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6589                          uint64_t value)
6590 {
6591     ARMCPU *cpu = env_archcpu(env);
6592     int i = ri->crm;
6593 
6594     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6595      * copy of BAS[0].
6596      */
6597     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6598     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6599 
6600     raw_write(env, ri, value);
6601     hw_breakpoint_update(cpu, i);
6602 }
6603 
6604 static void define_debug_regs(ARMCPU *cpu)
6605 {
6606     /* Define v7 and v8 architectural debug registers.
6607      * These are just dummy implementations for now.
6608      */
6609     int i;
6610     int wrps, brps, ctx_cmps;
6611 
6612     /*
6613      * The Arm ARM says DBGDIDR is optional and deprecated if EL1 cannot
6614      * use AArch32.  Given that bit 15 is RES1, if the value is 0 then
6615      * the register must not exist for this cpu.
6616      */
6617     if (cpu->isar.dbgdidr != 0) {
6618         ARMCPRegInfo dbgdidr = {
6619             .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0,
6620             .opc1 = 0, .opc2 = 0,
6621             .access = PL0_R, .accessfn = access_tda,
6622             .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6623         };
6624         define_one_arm_cp_reg(cpu, &dbgdidr);
6625     }
6626 
6627     /* Note that all these register fields hold "number of Xs minus 1". */
6628     brps = arm_num_brps(cpu);
6629     wrps = arm_num_wrps(cpu);
6630     ctx_cmps = arm_num_ctx_cmps(cpu);
6631 
6632     assert(ctx_cmps <= brps);
6633 
6634     define_arm_cp_regs(cpu, debug_cp_reginfo);
6635 
6636     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6637         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6638     }
6639 
6640     for (i = 0; i < brps; i++) {
6641         ARMCPRegInfo dbgregs[] = {
6642             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6643               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6644               .access = PL1_RW, .accessfn = access_tda,
6645               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6646               .writefn = dbgbvr_write, .raw_writefn = raw_write
6647             },
6648             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6649               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6650               .access = PL1_RW, .accessfn = access_tda,
6651               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6652               .writefn = dbgbcr_write, .raw_writefn = raw_write
6653             },
6654             REGINFO_SENTINEL
6655         };
6656         define_arm_cp_regs(cpu, dbgregs);
6657     }
6658 
6659     for (i = 0; i < wrps; i++) {
6660         ARMCPRegInfo dbgregs[] = {
6661             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6662               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6663               .access = PL1_RW, .accessfn = access_tda,
6664               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6665               .writefn = dbgwvr_write, .raw_writefn = raw_write
6666             },
6667             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6668               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6669               .access = PL1_RW, .accessfn = access_tda,
6670               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6671               .writefn = dbgwcr_write, .raw_writefn = raw_write
6672             },
6673             REGINFO_SENTINEL
6674         };
6675         define_arm_cp_regs(cpu, dbgregs);
6676     }
6677 }
6678 
6679 static void define_pmu_regs(ARMCPU *cpu)
6680 {
6681     /*
6682      * v7 performance monitor control register: same implementor
6683      * field as main ID register, and we implement four counters in
6684      * addition to the cycle count register.
6685      */
6686     unsigned int i, pmcrn = pmu_num_counters(&cpu->env);
6687     ARMCPRegInfo pmcr = {
6688         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6689         .access = PL0_RW,
6690         .type = ARM_CP_IO | ARM_CP_ALIAS,
6691         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6692         .accessfn = pmreg_access, .writefn = pmcr_write,
6693         .raw_writefn = raw_write,
6694     };
6695     ARMCPRegInfo pmcr64 = {
6696         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6697         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6698         .access = PL0_RW, .accessfn = pmreg_access,
6699         .type = ARM_CP_IO,
6700         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6701         .resetvalue = cpu->isar.reset_pmcr_el0,
6702         .writefn = pmcr_write, .raw_writefn = raw_write,
6703     };
6704 
6705     define_one_arm_cp_reg(cpu, &pmcr);
6706     define_one_arm_cp_reg(cpu, &pmcr64);
6707     for (i = 0; i < pmcrn; i++) {
6708         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6709         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6710         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6711         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6712         ARMCPRegInfo pmev_regs[] = {
6713             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6714               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6715               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6716               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6717               .accessfn = pmreg_access },
6718             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6719               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6720               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6721               .type = ARM_CP_IO,
6722               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6723               .raw_readfn = pmevcntr_rawread,
6724               .raw_writefn = pmevcntr_rawwrite },
6725             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6726               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6727               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6728               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6729               .accessfn = pmreg_access },
6730             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6731               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6732               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6733               .type = ARM_CP_IO,
6734               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6735               .raw_writefn = pmevtyper_rawwrite },
6736             REGINFO_SENTINEL
6737         };
6738         define_arm_cp_regs(cpu, pmev_regs);
6739         g_free(pmevcntr_name);
6740         g_free(pmevcntr_el0_name);
6741         g_free(pmevtyper_name);
6742         g_free(pmevtyper_el0_name);
6743     }
6744     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6745         ARMCPRegInfo v81_pmu_regs[] = {
6746             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6747               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6748               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6749               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6750             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6751               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6752               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6753               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6754             REGINFO_SENTINEL
6755         };
6756         define_arm_cp_regs(cpu, v81_pmu_regs);
6757     }
6758     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6759         static const ARMCPRegInfo v84_pmmir = {
6760             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6761             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6762             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6763             .resetvalue = 0
6764         };
6765         define_one_arm_cp_reg(cpu, &v84_pmmir);
6766     }
6767 }
6768 
6769 /* We don't know until after realize whether there's a GICv3
6770  * attached, and that is what registers the gicv3 sysregs.
6771  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6772  * at runtime.
6773  */
6774 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6775 {
6776     ARMCPU *cpu = env_archcpu(env);
6777     uint64_t pfr1 = cpu->isar.id_pfr1;
6778 
6779     if (env->gicv3state) {
6780         pfr1 |= 1 << 28;
6781     }
6782     return pfr1;
6783 }
6784 
6785 #ifndef CONFIG_USER_ONLY
6786 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6787 {
6788     ARMCPU *cpu = env_archcpu(env);
6789     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6790 
6791     if (env->gicv3state) {
6792         pfr0 |= 1 << 24;
6793     }
6794     return pfr0;
6795 }
6796 #endif
6797 
6798 /* Shared logic between LORID and the rest of the LOR* registers.
6799  * Secure state exclusion has already been dealt with.
6800  */
6801 static CPAccessResult access_lor_ns(CPUARMState *env,
6802                                     const ARMCPRegInfo *ri, bool isread)
6803 {
6804     int el = arm_current_el(env);
6805 
6806     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6807         return CP_ACCESS_TRAP_EL2;
6808     }
6809     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6810         return CP_ACCESS_TRAP_EL3;
6811     }
6812     return CP_ACCESS_OK;
6813 }
6814 
6815 static CPAccessResult access_lor_other(CPUARMState *env,
6816                                        const ARMCPRegInfo *ri, bool isread)
6817 {
6818     if (arm_is_secure_below_el3(env)) {
6819         /* Access denied in secure mode.  */
6820         return CP_ACCESS_TRAP;
6821     }
6822     return access_lor_ns(env, ri, isread);
6823 }
6824 
6825 /*
6826  * A trivial implementation of ARMv8.1-LOR leaves all of these
6827  * registers fixed at 0, which indicates that there are zero
6828  * supported Limited Ordering regions.
6829  */
6830 static const ARMCPRegInfo lor_reginfo[] = {
6831     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6832       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6833       .access = PL1_RW, .accessfn = access_lor_other,
6834       .type = ARM_CP_CONST, .resetvalue = 0 },
6835     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6836       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6837       .access = PL1_RW, .accessfn = access_lor_other,
6838       .type = ARM_CP_CONST, .resetvalue = 0 },
6839     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6840       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6841       .access = PL1_RW, .accessfn = access_lor_other,
6842       .type = ARM_CP_CONST, .resetvalue = 0 },
6843     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
6844       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
6845       .access = PL1_RW, .accessfn = access_lor_other,
6846       .type = ARM_CP_CONST, .resetvalue = 0 },
6847     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
6848       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
6849       .access = PL1_R, .accessfn = access_lor_ns,
6850       .type = ARM_CP_CONST, .resetvalue = 0 },
6851     REGINFO_SENTINEL
6852 };
6853 
6854 #ifdef TARGET_AARCH64
6855 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
6856                                    bool isread)
6857 {
6858     int el = arm_current_el(env);
6859 
6860     if (el < 2 &&
6861         arm_feature(env, ARM_FEATURE_EL2) &&
6862         !(arm_hcr_el2_eff(env) & HCR_APK)) {
6863         return CP_ACCESS_TRAP_EL2;
6864     }
6865     if (el < 3 &&
6866         arm_feature(env, ARM_FEATURE_EL3) &&
6867         !(env->cp15.scr_el3 & SCR_APK)) {
6868         return CP_ACCESS_TRAP_EL3;
6869     }
6870     return CP_ACCESS_OK;
6871 }
6872 
6873 static const ARMCPRegInfo pauth_reginfo[] = {
6874     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6875       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
6876       .access = PL1_RW, .accessfn = access_pauth,
6877       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
6878     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6879       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
6880       .access = PL1_RW, .accessfn = access_pauth,
6881       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
6882     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6883       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
6884       .access = PL1_RW, .accessfn = access_pauth,
6885       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
6886     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6887       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
6888       .access = PL1_RW, .accessfn = access_pauth,
6889       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
6890     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6891       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
6892       .access = PL1_RW, .accessfn = access_pauth,
6893       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
6894     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6895       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
6896       .access = PL1_RW, .accessfn = access_pauth,
6897       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
6898     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6899       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
6900       .access = PL1_RW, .accessfn = access_pauth,
6901       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
6902     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6903       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
6904       .access = PL1_RW, .accessfn = access_pauth,
6905       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
6906     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
6907       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
6908       .access = PL1_RW, .accessfn = access_pauth,
6909       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
6910     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
6911       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
6912       .access = PL1_RW, .accessfn = access_pauth,
6913       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
6914     REGINFO_SENTINEL
6915 };
6916 
6917 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
6918 {
6919     Error *err = NULL;
6920     uint64_t ret;
6921 
6922     /* Success sets NZCV = 0000.  */
6923     env->NF = env->CF = env->VF = 0, env->ZF = 1;
6924 
6925     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
6926         /*
6927          * ??? Failed, for unknown reasons in the crypto subsystem.
6928          * The best we can do is log the reason and return the
6929          * timed-out indication to the guest.  There is no reason
6930          * we know to expect this failure to be transitory, so the
6931          * guest may well hang retrying the operation.
6932          */
6933         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
6934                       ri->name, error_get_pretty(err));
6935         error_free(err);
6936 
6937         env->ZF = 0; /* NZCF = 0100 */
6938         return 0;
6939     }
6940     return ret;
6941 }
6942 
6943 /* We do not support re-seeding, so the two registers operate the same.  */
6944 static const ARMCPRegInfo rndr_reginfo[] = {
6945     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
6946       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6947       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
6948       .access = PL0_R, .readfn = rndr_readfn },
6949     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
6950       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
6951       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
6952       .access = PL0_R, .readfn = rndr_readfn },
6953     REGINFO_SENTINEL
6954 };
6955 
6956 #ifndef CONFIG_USER_ONLY
6957 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
6958                           uint64_t value)
6959 {
6960     ARMCPU *cpu = env_archcpu(env);
6961     /* CTR_EL0 System register -> DminLine, bits [19:16] */
6962     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
6963     uint64_t vaddr_in = (uint64_t) value;
6964     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
6965     void *haddr;
6966     int mem_idx = cpu_mmu_index(env, false);
6967 
6968     /* This won't be crossing page boundaries */
6969     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
6970     if (haddr) {
6971 
6972         ram_addr_t offset;
6973         MemoryRegion *mr;
6974 
6975         /* RCU lock is already being held */
6976         mr = memory_region_from_host(haddr, &offset);
6977 
6978         if (mr) {
6979             memory_region_writeback(mr, offset, dline_size);
6980         }
6981     }
6982 }
6983 
6984 static const ARMCPRegInfo dcpop_reg[] = {
6985     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
6986       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
6987       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6988       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6989     REGINFO_SENTINEL
6990 };
6991 
6992 static const ARMCPRegInfo dcpodp_reg[] = {
6993     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
6994       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
6995       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
6996       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
6997     REGINFO_SENTINEL
6998 };
6999 #endif /*CONFIG_USER_ONLY*/
7000 
7001 static CPAccessResult access_aa64_tid5(CPUARMState *env, const ARMCPRegInfo *ri,
7002                                        bool isread)
7003 {
7004     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID5)) {
7005         return CP_ACCESS_TRAP_EL2;
7006     }
7007 
7008     return CP_ACCESS_OK;
7009 }
7010 
7011 static CPAccessResult access_mte(CPUARMState *env, const ARMCPRegInfo *ri,
7012                                  bool isread)
7013 {
7014     int el = arm_current_el(env);
7015 
7016     if (el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
7017         uint64_t hcr = arm_hcr_el2_eff(env);
7018         if (!(hcr & HCR_ATA) && (!(hcr & HCR_E2H) || !(hcr & HCR_TGE))) {
7019             return CP_ACCESS_TRAP_EL2;
7020         }
7021     }
7022     if (el < 3 &&
7023         arm_feature(env, ARM_FEATURE_EL3) &&
7024         !(env->cp15.scr_el3 & SCR_ATA)) {
7025         return CP_ACCESS_TRAP_EL3;
7026     }
7027     return CP_ACCESS_OK;
7028 }
7029 
7030 static uint64_t tco_read(CPUARMState *env, const ARMCPRegInfo *ri)
7031 {
7032     return env->pstate & PSTATE_TCO;
7033 }
7034 
7035 static void tco_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
7036 {
7037     env->pstate = (env->pstate & ~PSTATE_TCO) | (val & PSTATE_TCO);
7038 }
7039 
7040 static const ARMCPRegInfo mte_reginfo[] = {
7041     { .name = "TFSRE0_EL1", .state = ARM_CP_STATE_AA64,
7042       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 1,
7043       .access = PL1_RW, .accessfn = access_mte,
7044       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[0]) },
7045     { .name = "TFSR_EL1", .state = ARM_CP_STATE_AA64,
7046       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 0,
7047       .access = PL1_RW, .accessfn = access_mte,
7048       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[1]) },
7049     { .name = "TFSR_EL2", .state = ARM_CP_STATE_AA64,
7050       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 6, .opc2 = 0,
7051       .access = PL2_RW, .accessfn = access_mte,
7052       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[2]) },
7053     { .name = "TFSR_EL3", .state = ARM_CP_STATE_AA64,
7054       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 6, .opc2 = 0,
7055       .access = PL3_RW,
7056       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[3]) },
7057     { .name = "RGSR_EL1", .state = ARM_CP_STATE_AA64,
7058       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 5,
7059       .access = PL1_RW, .accessfn = access_mte,
7060       .fieldoffset = offsetof(CPUARMState, cp15.rgsr_el1) },
7061     { .name = "GCR_EL1", .state = ARM_CP_STATE_AA64,
7062       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 6,
7063       .access = PL1_RW, .accessfn = access_mte,
7064       .fieldoffset = offsetof(CPUARMState, cp15.gcr_el1) },
7065     { .name = "GMID_EL1", .state = ARM_CP_STATE_AA64,
7066       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 4,
7067       .access = PL1_R, .accessfn = access_aa64_tid5,
7068       .type = ARM_CP_CONST, .resetvalue = GMID_EL1_BS },
7069     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7070       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7071       .type = ARM_CP_NO_RAW,
7072       .access = PL0_RW, .readfn = tco_read, .writefn = tco_write },
7073     { .name = "DC_IGVAC", .state = ARM_CP_STATE_AA64,
7074       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 3,
7075       .type = ARM_CP_NOP, .access = PL1_W,
7076       .accessfn = aa64_cacheop_poc_access },
7077     { .name = "DC_IGSW", .state = ARM_CP_STATE_AA64,
7078       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 4,
7079       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7080     { .name = "DC_IGDVAC", .state = ARM_CP_STATE_AA64,
7081       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 5,
7082       .type = ARM_CP_NOP, .access = PL1_W,
7083       .accessfn = aa64_cacheop_poc_access },
7084     { .name = "DC_IGDSW", .state = ARM_CP_STATE_AA64,
7085       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 6,
7086       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7087     { .name = "DC_CGSW", .state = ARM_CP_STATE_AA64,
7088       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 4,
7089       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7090     { .name = "DC_CGDSW", .state = ARM_CP_STATE_AA64,
7091       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 6,
7092       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7093     { .name = "DC_CIGSW", .state = ARM_CP_STATE_AA64,
7094       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 4,
7095       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7096     { .name = "DC_CIGDSW", .state = ARM_CP_STATE_AA64,
7097       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 6,
7098       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7099     REGINFO_SENTINEL
7100 };
7101 
7102 static const ARMCPRegInfo mte_tco_ro_reginfo[] = {
7103     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7104       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7105       .type = ARM_CP_CONST, .access = PL0_RW, },
7106     REGINFO_SENTINEL
7107 };
7108 
7109 static const ARMCPRegInfo mte_el0_cacheop_reginfo[] = {
7110     { .name = "DC_CGVAC", .state = ARM_CP_STATE_AA64,
7111       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 3,
7112       .type = ARM_CP_NOP, .access = PL0_W,
7113       .accessfn = aa64_cacheop_poc_access },
7114     { .name = "DC_CGDVAC", .state = ARM_CP_STATE_AA64,
7115       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 5,
7116       .type = ARM_CP_NOP, .access = PL0_W,
7117       .accessfn = aa64_cacheop_poc_access },
7118     { .name = "DC_CGVAP", .state = ARM_CP_STATE_AA64,
7119       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 3,
7120       .type = ARM_CP_NOP, .access = PL0_W,
7121       .accessfn = aa64_cacheop_poc_access },
7122     { .name = "DC_CGDVAP", .state = ARM_CP_STATE_AA64,
7123       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 5,
7124       .type = ARM_CP_NOP, .access = PL0_W,
7125       .accessfn = aa64_cacheop_poc_access },
7126     { .name = "DC_CGVADP", .state = ARM_CP_STATE_AA64,
7127       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 3,
7128       .type = ARM_CP_NOP, .access = PL0_W,
7129       .accessfn = aa64_cacheop_poc_access },
7130     { .name = "DC_CGDVADP", .state = ARM_CP_STATE_AA64,
7131       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 5,
7132       .type = ARM_CP_NOP, .access = PL0_W,
7133       .accessfn = aa64_cacheop_poc_access },
7134     { .name = "DC_CIGVAC", .state = ARM_CP_STATE_AA64,
7135       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 3,
7136       .type = ARM_CP_NOP, .access = PL0_W,
7137       .accessfn = aa64_cacheop_poc_access },
7138     { .name = "DC_CIGDVAC", .state = ARM_CP_STATE_AA64,
7139       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 5,
7140       .type = ARM_CP_NOP, .access = PL0_W,
7141       .accessfn = aa64_cacheop_poc_access },
7142     { .name = "DC_GVA", .state = ARM_CP_STATE_AA64,
7143       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 3,
7144       .access = PL0_W, .type = ARM_CP_DC_GVA,
7145 #ifndef CONFIG_USER_ONLY
7146       /* Avoid overhead of an access check that always passes in user-mode */
7147       .accessfn = aa64_zva_access,
7148 #endif
7149     },
7150     { .name = "DC_GZVA", .state = ARM_CP_STATE_AA64,
7151       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 4,
7152       .access = PL0_W, .type = ARM_CP_DC_GZVA,
7153 #ifndef CONFIG_USER_ONLY
7154       /* Avoid overhead of an access check that always passes in user-mode */
7155       .accessfn = aa64_zva_access,
7156 #endif
7157     },
7158     REGINFO_SENTINEL
7159 };
7160 
7161 #endif
7162 
7163 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
7164                                      bool isread)
7165 {
7166     int el = arm_current_el(env);
7167 
7168     if (el == 0) {
7169         uint64_t sctlr = arm_sctlr(env, el);
7170         if (!(sctlr & SCTLR_EnRCTX)) {
7171             return CP_ACCESS_TRAP;
7172         }
7173     } else if (el == 1) {
7174         uint64_t hcr = arm_hcr_el2_eff(env);
7175         if (hcr & HCR_NV) {
7176             return CP_ACCESS_TRAP_EL2;
7177         }
7178     }
7179     return CP_ACCESS_OK;
7180 }
7181 
7182 static const ARMCPRegInfo predinv_reginfo[] = {
7183     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
7184       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
7185       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7186     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
7187       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
7188       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7189     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
7190       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
7191       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7192     /*
7193      * Note the AArch32 opcodes have a different OPC1.
7194      */
7195     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
7196       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
7197       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7198     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
7199       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
7200       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7201     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
7202       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
7203       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7204     REGINFO_SENTINEL
7205 };
7206 
7207 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
7208 {
7209     /* Read the high 32 bits of the current CCSIDR */
7210     return extract64(ccsidr_read(env, ri), 32, 32);
7211 }
7212 
7213 static const ARMCPRegInfo ccsidr2_reginfo[] = {
7214     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
7215       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
7216       .access = PL1_R,
7217       .accessfn = access_aa64_tid2,
7218       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7219     REGINFO_SENTINEL
7220 };
7221 
7222 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7223                                        bool isread)
7224 {
7225     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7226         return CP_ACCESS_TRAP_EL2;
7227     }
7228 
7229     return CP_ACCESS_OK;
7230 }
7231 
7232 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7233                                        bool isread)
7234 {
7235     if (arm_feature(env, ARM_FEATURE_V8)) {
7236         return access_aa64_tid3(env, ri, isread);
7237     }
7238 
7239     return CP_ACCESS_OK;
7240 }
7241 
7242 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7243                                      bool isread)
7244 {
7245     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7246         return CP_ACCESS_TRAP_EL2;
7247     }
7248 
7249     return CP_ACCESS_OK;
7250 }
7251 
7252 static const ARMCPRegInfo jazelle_regs[] = {
7253     { .name = "JIDR",
7254       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7255       .access = PL1_R, .accessfn = access_jazelle,
7256       .type = ARM_CP_CONST, .resetvalue = 0 },
7257     { .name = "JOSCR",
7258       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7259       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7260     { .name = "JMCR",
7261       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7262       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7263     REGINFO_SENTINEL
7264 };
7265 
7266 static const ARMCPRegInfo vhe_reginfo[] = {
7267     { .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7268       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7269       .access = PL2_RW,
7270       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2]) },
7271     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7272       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7273       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7274       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7275 #ifndef CONFIG_USER_ONLY
7276     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7277       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7278       .fieldoffset =
7279         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7280       .type = ARM_CP_IO, .access = PL2_RW,
7281       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7282     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7283       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7284       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7285       .resetfn = gt_hv_timer_reset,
7286       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7287     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7288       .type = ARM_CP_IO,
7289       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7290       .access = PL2_RW,
7291       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7292       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7293     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7294       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7295       .type = ARM_CP_IO | ARM_CP_ALIAS,
7296       .access = PL2_RW, .accessfn = e2h_access,
7297       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7298       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7299     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7300       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7301       .type = ARM_CP_IO | ARM_CP_ALIAS,
7302       .access = PL2_RW, .accessfn = e2h_access,
7303       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7304       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7305     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7306       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7307       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7308       .access = PL2_RW, .accessfn = e2h_access,
7309       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7310     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7311       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7312       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7313       .access = PL2_RW, .accessfn = e2h_access,
7314       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7315     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7316       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7317       .type = ARM_CP_IO | ARM_CP_ALIAS,
7318       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7319       .access = PL2_RW, .accessfn = e2h_access,
7320       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7321     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7322       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7323       .type = ARM_CP_IO | ARM_CP_ALIAS,
7324       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7325       .access = PL2_RW, .accessfn = e2h_access,
7326       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7327 #endif
7328     REGINFO_SENTINEL
7329 };
7330 
7331 #ifndef CONFIG_USER_ONLY
7332 static const ARMCPRegInfo ats1e1_reginfo[] = {
7333     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7334       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7335       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7336       .writefn = ats_write64 },
7337     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7338       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7339       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7340       .writefn = ats_write64 },
7341     REGINFO_SENTINEL
7342 };
7343 
7344 static const ARMCPRegInfo ats1cp_reginfo[] = {
7345     { .name = "ATS1CPRP",
7346       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7347       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7348       .writefn = ats_write },
7349     { .name = "ATS1CPWP",
7350       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7351       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7352       .writefn = ats_write },
7353     REGINFO_SENTINEL
7354 };
7355 #endif
7356 
7357 /*
7358  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7359  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7360  * is non-zero, which is never for ARMv7, optionally in ARMv8
7361  * and mandatorily for ARMv8.2 and up.
7362  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7363  * implementation is RAZ/WI we can ignore this detail, as we
7364  * do for ACTLR.
7365  */
7366 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7367     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7368       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7369       .access = PL1_RW, .accessfn = access_tacr,
7370       .type = ARM_CP_CONST, .resetvalue = 0 },
7371     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7372       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7373       .access = PL2_RW, .type = ARM_CP_CONST,
7374       .resetvalue = 0 },
7375     REGINFO_SENTINEL
7376 };
7377 
7378 void register_cp_regs_for_features(ARMCPU *cpu)
7379 {
7380     /* Register all the coprocessor registers based on feature bits */
7381     CPUARMState *env = &cpu->env;
7382     if (arm_feature(env, ARM_FEATURE_M)) {
7383         /* M profile has no coprocessor registers */
7384         return;
7385     }
7386 
7387     define_arm_cp_regs(cpu, cp_reginfo);
7388     if (!arm_feature(env, ARM_FEATURE_V8)) {
7389         /* Must go early as it is full of wildcards that may be
7390          * overridden by later definitions.
7391          */
7392         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7393     }
7394 
7395     if (arm_feature(env, ARM_FEATURE_V6)) {
7396         /* The ID registers all have impdef reset values */
7397         ARMCPRegInfo v6_idregs[] = {
7398             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7399               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7400               .access = PL1_R, .type = ARM_CP_CONST,
7401               .accessfn = access_aa32_tid3,
7402               .resetvalue = cpu->isar.id_pfr0 },
7403             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7404              * the value of the GIC field until after we define these regs.
7405              */
7406             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7407               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7408               .access = PL1_R, .type = ARM_CP_NO_RAW,
7409               .accessfn = access_aa32_tid3,
7410               .readfn = id_pfr1_read,
7411               .writefn = arm_cp_write_ignore },
7412             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7413               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7414               .access = PL1_R, .type = ARM_CP_CONST,
7415               .accessfn = access_aa32_tid3,
7416               .resetvalue = cpu->isar.id_dfr0 },
7417             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7418               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7419               .access = PL1_R, .type = ARM_CP_CONST,
7420               .accessfn = access_aa32_tid3,
7421               .resetvalue = cpu->id_afr0 },
7422             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7423               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7424               .access = PL1_R, .type = ARM_CP_CONST,
7425               .accessfn = access_aa32_tid3,
7426               .resetvalue = cpu->isar.id_mmfr0 },
7427             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7428               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7429               .access = PL1_R, .type = ARM_CP_CONST,
7430               .accessfn = access_aa32_tid3,
7431               .resetvalue = cpu->isar.id_mmfr1 },
7432             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7433               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7434               .access = PL1_R, .type = ARM_CP_CONST,
7435               .accessfn = access_aa32_tid3,
7436               .resetvalue = cpu->isar.id_mmfr2 },
7437             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7438               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7439               .access = PL1_R, .type = ARM_CP_CONST,
7440               .accessfn = access_aa32_tid3,
7441               .resetvalue = cpu->isar.id_mmfr3 },
7442             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7443               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7444               .access = PL1_R, .type = ARM_CP_CONST,
7445               .accessfn = access_aa32_tid3,
7446               .resetvalue = cpu->isar.id_isar0 },
7447             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7448               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7449               .access = PL1_R, .type = ARM_CP_CONST,
7450               .accessfn = access_aa32_tid3,
7451               .resetvalue = cpu->isar.id_isar1 },
7452             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7453               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7454               .access = PL1_R, .type = ARM_CP_CONST,
7455               .accessfn = access_aa32_tid3,
7456               .resetvalue = cpu->isar.id_isar2 },
7457             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7458               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7459               .access = PL1_R, .type = ARM_CP_CONST,
7460               .accessfn = access_aa32_tid3,
7461               .resetvalue = cpu->isar.id_isar3 },
7462             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7463               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7464               .access = PL1_R, .type = ARM_CP_CONST,
7465               .accessfn = access_aa32_tid3,
7466               .resetvalue = cpu->isar.id_isar4 },
7467             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7468               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7469               .access = PL1_R, .type = ARM_CP_CONST,
7470               .accessfn = access_aa32_tid3,
7471               .resetvalue = cpu->isar.id_isar5 },
7472             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7473               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7474               .access = PL1_R, .type = ARM_CP_CONST,
7475               .accessfn = access_aa32_tid3,
7476               .resetvalue = cpu->isar.id_mmfr4 },
7477             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7478               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7479               .access = PL1_R, .type = ARM_CP_CONST,
7480               .accessfn = access_aa32_tid3,
7481               .resetvalue = cpu->isar.id_isar6 },
7482             REGINFO_SENTINEL
7483         };
7484         define_arm_cp_regs(cpu, v6_idregs);
7485         define_arm_cp_regs(cpu, v6_cp_reginfo);
7486     } else {
7487         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7488     }
7489     if (arm_feature(env, ARM_FEATURE_V6K)) {
7490         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7491     }
7492     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7493         !arm_feature(env, ARM_FEATURE_PMSA)) {
7494         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7495     }
7496     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7497         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7498     }
7499     if (arm_feature(env, ARM_FEATURE_V7)) {
7500         ARMCPRegInfo clidr = {
7501             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7502             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7503             .access = PL1_R, .type = ARM_CP_CONST,
7504             .accessfn = access_aa64_tid2,
7505             .resetvalue = cpu->clidr
7506         };
7507         define_one_arm_cp_reg(cpu, &clidr);
7508         define_arm_cp_regs(cpu, v7_cp_reginfo);
7509         define_debug_regs(cpu);
7510         define_pmu_regs(cpu);
7511     } else {
7512         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7513     }
7514     if (arm_feature(env, ARM_FEATURE_V8)) {
7515         /* AArch64 ID registers, which all have impdef reset values.
7516          * Note that within the ID register ranges the unused slots
7517          * must all RAZ, not UNDEF; future architecture versions may
7518          * define new registers here.
7519          */
7520         ARMCPRegInfo v8_idregs[] = {
7521             /*
7522              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7523              * emulation because we don't know the right value for the
7524              * GIC field until after we define these regs.
7525              */
7526             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7527               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7528               .access = PL1_R,
7529 #ifdef CONFIG_USER_ONLY
7530               .type = ARM_CP_CONST,
7531               .resetvalue = cpu->isar.id_aa64pfr0
7532 #else
7533               .type = ARM_CP_NO_RAW,
7534               .accessfn = access_aa64_tid3,
7535               .readfn = id_aa64pfr0_read,
7536               .writefn = arm_cp_write_ignore
7537 #endif
7538             },
7539             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7540               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7541               .access = PL1_R, .type = ARM_CP_CONST,
7542               .accessfn = access_aa64_tid3,
7543               .resetvalue = cpu->isar.id_aa64pfr1},
7544             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7545               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7546               .access = PL1_R, .type = ARM_CP_CONST,
7547               .accessfn = access_aa64_tid3,
7548               .resetvalue = 0 },
7549             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7550               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7551               .access = PL1_R, .type = ARM_CP_CONST,
7552               .accessfn = access_aa64_tid3,
7553               .resetvalue = 0 },
7554             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7555               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7556               .access = PL1_R, .type = ARM_CP_CONST,
7557               .accessfn = access_aa64_tid3,
7558               /* At present, only SVEver == 0 is defined anyway.  */
7559               .resetvalue = 0 },
7560             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7561               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7562               .access = PL1_R, .type = ARM_CP_CONST,
7563               .accessfn = access_aa64_tid3,
7564               .resetvalue = 0 },
7565             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7566               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7567               .access = PL1_R, .type = ARM_CP_CONST,
7568               .accessfn = access_aa64_tid3,
7569               .resetvalue = 0 },
7570             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7571               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7572               .access = PL1_R, .type = ARM_CP_CONST,
7573               .accessfn = access_aa64_tid3,
7574               .resetvalue = 0 },
7575             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7576               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7577               .access = PL1_R, .type = ARM_CP_CONST,
7578               .accessfn = access_aa64_tid3,
7579               .resetvalue = cpu->isar.id_aa64dfr0 },
7580             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7581               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7582               .access = PL1_R, .type = ARM_CP_CONST,
7583               .accessfn = access_aa64_tid3,
7584               .resetvalue = cpu->isar.id_aa64dfr1 },
7585             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7586               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7587               .access = PL1_R, .type = ARM_CP_CONST,
7588               .accessfn = access_aa64_tid3,
7589               .resetvalue = 0 },
7590             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7591               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7592               .access = PL1_R, .type = ARM_CP_CONST,
7593               .accessfn = access_aa64_tid3,
7594               .resetvalue = 0 },
7595             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7596               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7597               .access = PL1_R, .type = ARM_CP_CONST,
7598               .accessfn = access_aa64_tid3,
7599               .resetvalue = cpu->id_aa64afr0 },
7600             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7601               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7602               .access = PL1_R, .type = ARM_CP_CONST,
7603               .accessfn = access_aa64_tid3,
7604               .resetvalue = cpu->id_aa64afr1 },
7605             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7606               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7607               .access = PL1_R, .type = ARM_CP_CONST,
7608               .accessfn = access_aa64_tid3,
7609               .resetvalue = 0 },
7610             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7611               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7612               .access = PL1_R, .type = ARM_CP_CONST,
7613               .accessfn = access_aa64_tid3,
7614               .resetvalue = 0 },
7615             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7616               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7617               .access = PL1_R, .type = ARM_CP_CONST,
7618               .accessfn = access_aa64_tid3,
7619               .resetvalue = cpu->isar.id_aa64isar0 },
7620             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7621               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7622               .access = PL1_R, .type = ARM_CP_CONST,
7623               .accessfn = access_aa64_tid3,
7624               .resetvalue = cpu->isar.id_aa64isar1 },
7625             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7626               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7627               .access = PL1_R, .type = ARM_CP_CONST,
7628               .accessfn = access_aa64_tid3,
7629               .resetvalue = 0 },
7630             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7631               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7632               .access = PL1_R, .type = ARM_CP_CONST,
7633               .accessfn = access_aa64_tid3,
7634               .resetvalue = 0 },
7635             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7636               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7637               .access = PL1_R, .type = ARM_CP_CONST,
7638               .accessfn = access_aa64_tid3,
7639               .resetvalue = 0 },
7640             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7641               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7642               .access = PL1_R, .type = ARM_CP_CONST,
7643               .accessfn = access_aa64_tid3,
7644               .resetvalue = 0 },
7645             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7646               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7647               .access = PL1_R, .type = ARM_CP_CONST,
7648               .accessfn = access_aa64_tid3,
7649               .resetvalue = 0 },
7650             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7651               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7652               .access = PL1_R, .type = ARM_CP_CONST,
7653               .accessfn = access_aa64_tid3,
7654               .resetvalue = 0 },
7655             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7656               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7657               .access = PL1_R, .type = ARM_CP_CONST,
7658               .accessfn = access_aa64_tid3,
7659               .resetvalue = cpu->isar.id_aa64mmfr0 },
7660             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7661               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7662               .access = PL1_R, .type = ARM_CP_CONST,
7663               .accessfn = access_aa64_tid3,
7664               .resetvalue = cpu->isar.id_aa64mmfr1 },
7665             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7666               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7667               .access = PL1_R, .type = ARM_CP_CONST,
7668               .accessfn = access_aa64_tid3,
7669               .resetvalue = cpu->isar.id_aa64mmfr2 },
7670             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7671               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7672               .access = PL1_R, .type = ARM_CP_CONST,
7673               .accessfn = access_aa64_tid3,
7674               .resetvalue = 0 },
7675             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7676               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
7677               .access = PL1_R, .type = ARM_CP_CONST,
7678               .accessfn = access_aa64_tid3,
7679               .resetvalue = 0 },
7680             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7681               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
7682               .access = PL1_R, .type = ARM_CP_CONST,
7683               .accessfn = access_aa64_tid3,
7684               .resetvalue = 0 },
7685             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7686               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
7687               .access = PL1_R, .type = ARM_CP_CONST,
7688               .accessfn = access_aa64_tid3,
7689               .resetvalue = 0 },
7690             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7691               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
7692               .access = PL1_R, .type = ARM_CP_CONST,
7693               .accessfn = access_aa64_tid3,
7694               .resetvalue = 0 },
7695             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
7696               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
7697               .access = PL1_R, .type = ARM_CP_CONST,
7698               .accessfn = access_aa64_tid3,
7699               .resetvalue = cpu->isar.mvfr0 },
7700             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
7701               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
7702               .access = PL1_R, .type = ARM_CP_CONST,
7703               .accessfn = access_aa64_tid3,
7704               .resetvalue = cpu->isar.mvfr1 },
7705             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
7706               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
7707               .access = PL1_R, .type = ARM_CP_CONST,
7708               .accessfn = access_aa64_tid3,
7709               .resetvalue = cpu->isar.mvfr2 },
7710             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7711               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
7712               .access = PL1_R, .type = ARM_CP_CONST,
7713               .accessfn = access_aa64_tid3,
7714               .resetvalue = 0 },
7715             { .name = "ID_PFR2", .state = ARM_CP_STATE_BOTH,
7716               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
7717               .access = PL1_R, .type = ARM_CP_CONST,
7718               .accessfn = access_aa64_tid3,
7719               .resetvalue = cpu->isar.id_pfr2 },
7720             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7721               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
7722               .access = PL1_R, .type = ARM_CP_CONST,
7723               .accessfn = access_aa64_tid3,
7724               .resetvalue = 0 },
7725             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7726               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
7727               .access = PL1_R, .type = ARM_CP_CONST,
7728               .accessfn = access_aa64_tid3,
7729               .resetvalue = 0 },
7730             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7731               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
7732               .access = PL1_R, .type = ARM_CP_CONST,
7733               .accessfn = access_aa64_tid3,
7734               .resetvalue = 0 },
7735             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
7736               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
7737               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7738               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
7739             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
7740               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
7741               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7742               .resetvalue = cpu->pmceid0 },
7743             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
7744               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
7745               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7746               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
7747             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
7748               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
7749               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
7750               .resetvalue = cpu->pmceid1 },
7751             REGINFO_SENTINEL
7752         };
7753 #ifdef CONFIG_USER_ONLY
7754         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
7755             { .name = "ID_AA64PFR0_EL1",
7756               .exported_bits = 0x000f000f00ff0000,
7757               .fixed_bits    = 0x0000000000000011 },
7758             { .name = "ID_AA64PFR1_EL1",
7759               .exported_bits = 0x00000000000000f0 },
7760             { .name = "ID_AA64PFR*_EL1_RESERVED",
7761               .is_glob = true                     },
7762             { .name = "ID_AA64ZFR0_EL1"           },
7763             { .name = "ID_AA64MMFR0_EL1",
7764               .fixed_bits    = 0x00000000ff000000 },
7765             { .name = "ID_AA64MMFR1_EL1"          },
7766             { .name = "ID_AA64MMFR*_EL1_RESERVED",
7767               .is_glob = true                     },
7768             { .name = "ID_AA64DFR0_EL1",
7769               .fixed_bits    = 0x0000000000000006 },
7770             { .name = "ID_AA64DFR1_EL1"           },
7771             { .name = "ID_AA64DFR*_EL1_RESERVED",
7772               .is_glob = true                     },
7773             { .name = "ID_AA64AFR*",
7774               .is_glob = true                     },
7775             { .name = "ID_AA64ISAR0_EL1",
7776               .exported_bits = 0x00fffffff0fffff0 },
7777             { .name = "ID_AA64ISAR1_EL1",
7778               .exported_bits = 0x000000f0ffffffff },
7779             { .name = "ID_AA64ISAR*_EL1_RESERVED",
7780               .is_glob = true                     },
7781             REGUSERINFO_SENTINEL
7782         };
7783         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
7784 #endif
7785         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
7786         if (!arm_feature(env, ARM_FEATURE_EL3) &&
7787             !arm_feature(env, ARM_FEATURE_EL2)) {
7788             ARMCPRegInfo rvbar = {
7789                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
7790                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
7791                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
7792             };
7793             define_one_arm_cp_reg(cpu, &rvbar);
7794         }
7795         define_arm_cp_regs(cpu, v8_idregs);
7796         define_arm_cp_regs(cpu, v8_cp_reginfo);
7797     }
7798     if (arm_feature(env, ARM_FEATURE_EL2)) {
7799         uint64_t vmpidr_def = mpidr_read_val(env);
7800         ARMCPRegInfo vpidr_regs[] = {
7801             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
7802               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7803               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7804               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
7805               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
7806             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
7807               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7808               .access = PL2_RW, .resetvalue = cpu->midr,
7809               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7810             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
7811               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7812               .access = PL2_RW, .accessfn = access_el3_aa32ns,
7813               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
7814               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
7815             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
7816               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7817               .access = PL2_RW,
7818               .resetvalue = vmpidr_def,
7819               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
7820             REGINFO_SENTINEL
7821         };
7822         /*
7823          * The only field of MDCR_EL2 that has a defined architectural reset
7824          * value is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N.
7825          */
7826         ARMCPRegInfo mdcr_el2 = {
7827             .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
7828             .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
7829             .access = PL2_RW, .resetvalue = pmu_num_counters(env),
7830             .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2),
7831         };
7832         define_one_arm_cp_reg(cpu, &mdcr_el2);
7833         define_arm_cp_regs(cpu, vpidr_regs);
7834         define_arm_cp_regs(cpu, el2_cp_reginfo);
7835         if (arm_feature(env, ARM_FEATURE_V8)) {
7836             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
7837         }
7838         if (cpu_isar_feature(aa64_sel2, cpu)) {
7839             define_arm_cp_regs(cpu, el2_sec_cp_reginfo);
7840         }
7841         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
7842         if (!arm_feature(env, ARM_FEATURE_EL3)) {
7843             ARMCPRegInfo rvbar = {
7844                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
7845                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
7846                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
7847             };
7848             define_one_arm_cp_reg(cpu, &rvbar);
7849         }
7850     } else {
7851         /* If EL2 is missing but higher ELs are enabled, we need to
7852          * register the no_el2 reginfos.
7853          */
7854         if (arm_feature(env, ARM_FEATURE_EL3)) {
7855             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
7856              * of MIDR_EL1 and MPIDR_EL1.
7857              */
7858             ARMCPRegInfo vpidr_regs[] = {
7859                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7860                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
7861                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
7862                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
7863                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
7864                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
7865                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
7866                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
7867                   .type = ARM_CP_NO_RAW,
7868                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
7869                 REGINFO_SENTINEL
7870             };
7871             define_arm_cp_regs(cpu, vpidr_regs);
7872             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
7873             if (arm_feature(env, ARM_FEATURE_V8)) {
7874                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
7875             }
7876         }
7877     }
7878     if (arm_feature(env, ARM_FEATURE_EL3)) {
7879         define_arm_cp_regs(cpu, el3_cp_reginfo);
7880         ARMCPRegInfo el3_regs[] = {
7881             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
7882               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
7883               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
7884             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
7885               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
7886               .access = PL3_RW,
7887               .raw_writefn = raw_write, .writefn = sctlr_write,
7888               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
7889               .resetvalue = cpu->reset_sctlr },
7890             REGINFO_SENTINEL
7891         };
7892 
7893         define_arm_cp_regs(cpu, el3_regs);
7894     }
7895     /* The behaviour of NSACR is sufficiently various that we don't
7896      * try to describe it in a single reginfo:
7897      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
7898      *     reads as constant 0xc00 from NS EL1 and NS EL2
7899      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
7900      *  if v7 without EL3, register doesn't exist
7901      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
7902      */
7903     if (arm_feature(env, ARM_FEATURE_EL3)) {
7904         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
7905             ARMCPRegInfo nsacr = {
7906                 .name = "NSACR", .type = ARM_CP_CONST,
7907                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7908                 .access = PL1_RW, .accessfn = nsacr_access,
7909                 .resetvalue = 0xc00
7910             };
7911             define_one_arm_cp_reg(cpu, &nsacr);
7912         } else {
7913             ARMCPRegInfo nsacr = {
7914                 .name = "NSACR",
7915                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7916                 .access = PL3_RW | PL1_R,
7917                 .resetvalue = 0,
7918                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
7919             };
7920             define_one_arm_cp_reg(cpu, &nsacr);
7921         }
7922     } else {
7923         if (arm_feature(env, ARM_FEATURE_V8)) {
7924             ARMCPRegInfo nsacr = {
7925                 .name = "NSACR", .type = ARM_CP_CONST,
7926                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
7927                 .access = PL1_R,
7928                 .resetvalue = 0xc00
7929             };
7930             define_one_arm_cp_reg(cpu, &nsacr);
7931         }
7932     }
7933 
7934     if (arm_feature(env, ARM_FEATURE_PMSA)) {
7935         if (arm_feature(env, ARM_FEATURE_V6)) {
7936             /* PMSAv6 not implemented */
7937             assert(arm_feature(env, ARM_FEATURE_V7));
7938             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7939             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
7940         } else {
7941             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
7942         }
7943     } else {
7944         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
7945         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
7946         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
7947         if (cpu_isar_feature(aa32_hpd, cpu)) {
7948             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
7949         }
7950     }
7951     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
7952         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
7953     }
7954     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
7955         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
7956     }
7957     if (arm_feature(env, ARM_FEATURE_VAPA)) {
7958         define_arm_cp_regs(cpu, vapa_cp_reginfo);
7959     }
7960     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
7961         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
7962     }
7963     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
7964         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
7965     }
7966     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
7967         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
7968     }
7969     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
7970         define_arm_cp_regs(cpu, omap_cp_reginfo);
7971     }
7972     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
7973         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
7974     }
7975     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
7976         define_arm_cp_regs(cpu, xscale_cp_reginfo);
7977     }
7978     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
7979         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
7980     }
7981     if (arm_feature(env, ARM_FEATURE_LPAE)) {
7982         define_arm_cp_regs(cpu, lpae_cp_reginfo);
7983     }
7984     if (cpu_isar_feature(aa32_jazelle, cpu)) {
7985         define_arm_cp_regs(cpu, jazelle_regs);
7986     }
7987     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
7988      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
7989      * be read-only (ie write causes UNDEF exception).
7990      */
7991     {
7992         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
7993             /* Pre-v8 MIDR space.
7994              * Note that the MIDR isn't a simple constant register because
7995              * of the TI925 behaviour where writes to another register can
7996              * cause the MIDR value to change.
7997              *
7998              * Unimplemented registers in the c15 0 0 0 space default to
7999              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
8000              * and friends override accordingly.
8001              */
8002             { .name = "MIDR",
8003               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
8004               .access = PL1_R, .resetvalue = cpu->midr,
8005               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
8006               .readfn = midr_read,
8007               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8008               .type = ARM_CP_OVERRIDE },
8009             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
8010             { .name = "DUMMY",
8011               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
8012               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8013             { .name = "DUMMY",
8014               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
8015               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8016             { .name = "DUMMY",
8017               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
8018               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8019             { .name = "DUMMY",
8020               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
8021               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8022             { .name = "DUMMY",
8023               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
8024               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8025             REGINFO_SENTINEL
8026         };
8027         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
8028             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
8029               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
8030               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
8031               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8032               .readfn = midr_read },
8033             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
8034             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8035               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8036               .access = PL1_R, .resetvalue = cpu->midr },
8037             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8038               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
8039               .access = PL1_R, .resetvalue = cpu->midr },
8040             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
8041               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
8042               .access = PL1_R,
8043               .accessfn = access_aa64_tid1,
8044               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
8045             REGINFO_SENTINEL
8046         };
8047         ARMCPRegInfo id_cp_reginfo[] = {
8048             /* These are common to v8 and pre-v8 */
8049             { .name = "CTR",
8050               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
8051               .access = PL1_R, .accessfn = ctr_el0_access,
8052               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8053             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
8054               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
8055               .access = PL0_R, .accessfn = ctr_el0_access,
8056               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8057             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
8058             { .name = "TCMTR",
8059               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
8060               .access = PL1_R,
8061               .accessfn = access_aa32_tid1,
8062               .type = ARM_CP_CONST, .resetvalue = 0 },
8063             REGINFO_SENTINEL
8064         };
8065         /* TLBTR is specific to VMSA */
8066         ARMCPRegInfo id_tlbtr_reginfo = {
8067               .name = "TLBTR",
8068               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
8069               .access = PL1_R,
8070               .accessfn = access_aa32_tid1,
8071               .type = ARM_CP_CONST, .resetvalue = 0,
8072         };
8073         /* MPUIR is specific to PMSA V6+ */
8074         ARMCPRegInfo id_mpuir_reginfo = {
8075               .name = "MPUIR",
8076               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8077               .access = PL1_R, .type = ARM_CP_CONST,
8078               .resetvalue = cpu->pmsav7_dregion << 8
8079         };
8080         ARMCPRegInfo crn0_wi_reginfo = {
8081             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
8082             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
8083             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
8084         };
8085 #ifdef CONFIG_USER_ONLY
8086         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
8087             { .name = "MIDR_EL1",
8088               .exported_bits = 0x00000000ffffffff },
8089             { .name = "REVIDR_EL1"                },
8090             REGUSERINFO_SENTINEL
8091         };
8092         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
8093 #endif
8094         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
8095             arm_feature(env, ARM_FEATURE_STRONGARM)) {
8096             ARMCPRegInfo *r;
8097             /* Register the blanket "writes ignored" value first to cover the
8098              * whole space. Then update the specific ID registers to allow write
8099              * access, so that they ignore writes rather than causing them to
8100              * UNDEF.
8101              */
8102             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
8103             for (r = id_pre_v8_midr_cp_reginfo;
8104                  r->type != ARM_CP_SENTINEL; r++) {
8105                 r->access = PL1_RW;
8106             }
8107             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
8108                 r->access = PL1_RW;
8109             }
8110             id_mpuir_reginfo.access = PL1_RW;
8111             id_tlbtr_reginfo.access = PL1_RW;
8112         }
8113         if (arm_feature(env, ARM_FEATURE_V8)) {
8114             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
8115         } else {
8116             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
8117         }
8118         define_arm_cp_regs(cpu, id_cp_reginfo);
8119         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
8120             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
8121         } else if (arm_feature(env, ARM_FEATURE_V7)) {
8122             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
8123         }
8124     }
8125 
8126     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
8127         ARMCPRegInfo mpidr_cp_reginfo[] = {
8128             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
8129               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
8130               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
8131             REGINFO_SENTINEL
8132         };
8133 #ifdef CONFIG_USER_ONLY
8134         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
8135             { .name = "MPIDR_EL1",
8136               .fixed_bits = 0x0000000080000000 },
8137             REGUSERINFO_SENTINEL
8138         };
8139         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
8140 #endif
8141         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
8142     }
8143 
8144     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
8145         ARMCPRegInfo auxcr_reginfo[] = {
8146             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
8147               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
8148               .access = PL1_RW, .accessfn = access_tacr,
8149               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
8150             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
8151               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
8152               .access = PL2_RW, .type = ARM_CP_CONST,
8153               .resetvalue = 0 },
8154             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
8155               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
8156               .access = PL3_RW, .type = ARM_CP_CONST,
8157               .resetvalue = 0 },
8158             REGINFO_SENTINEL
8159         };
8160         define_arm_cp_regs(cpu, auxcr_reginfo);
8161         if (cpu_isar_feature(aa32_ac2, cpu)) {
8162             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
8163         }
8164     }
8165 
8166     if (arm_feature(env, ARM_FEATURE_CBAR)) {
8167         /*
8168          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
8169          * There are two flavours:
8170          *  (1) older 32-bit only cores have a simple 32-bit CBAR
8171          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
8172          *      32-bit register visible to AArch32 at a different encoding
8173          *      to the "flavour 1" register and with the bits rearranged to
8174          *      be able to squash a 64-bit address into the 32-bit view.
8175          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
8176          * in future if we support AArch32-only configs of some of the
8177          * AArch64 cores we might need to add a specific feature flag
8178          * to indicate cores with "flavour 2" CBAR.
8179          */
8180         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8181             /* 32 bit view is [31:18] 0...0 [43:32]. */
8182             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
8183                 | extract64(cpu->reset_cbar, 32, 12);
8184             ARMCPRegInfo cbar_reginfo[] = {
8185                 { .name = "CBAR",
8186                   .type = ARM_CP_CONST,
8187                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
8188                   .access = PL1_R, .resetvalue = cbar32 },
8189                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
8190                   .type = ARM_CP_CONST,
8191                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
8192                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
8193                 REGINFO_SENTINEL
8194             };
8195             /* We don't implement a r/w 64 bit CBAR currently */
8196             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
8197             define_arm_cp_regs(cpu, cbar_reginfo);
8198         } else {
8199             ARMCPRegInfo cbar = {
8200                 .name = "CBAR",
8201                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
8202                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
8203                 .fieldoffset = offsetof(CPUARMState,
8204                                         cp15.c15_config_base_address)
8205             };
8206             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
8207                 cbar.access = PL1_R;
8208                 cbar.fieldoffset = 0;
8209                 cbar.type = ARM_CP_CONST;
8210             }
8211             define_one_arm_cp_reg(cpu, &cbar);
8212         }
8213     }
8214 
8215     if (arm_feature(env, ARM_FEATURE_VBAR)) {
8216         ARMCPRegInfo vbar_cp_reginfo[] = {
8217             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
8218               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
8219               .access = PL1_RW, .writefn = vbar_write,
8220               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
8221                                      offsetof(CPUARMState, cp15.vbar_ns) },
8222               .resetvalue = 0 },
8223             REGINFO_SENTINEL
8224         };
8225         define_arm_cp_regs(cpu, vbar_cp_reginfo);
8226     }
8227 
8228     /* Generic registers whose values depend on the implementation */
8229     {
8230         ARMCPRegInfo sctlr = {
8231             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8232             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8233             .access = PL1_RW, .accessfn = access_tvm_trvm,
8234             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8235                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8236             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8237             .raw_writefn = raw_write,
8238         };
8239         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8240             /* Normally we would always end the TB on an SCTLR write, but Linux
8241              * arch/arm/mach-pxa/sleep.S expects two instructions following
8242              * an MMU enable to execute from cache.  Imitate this behaviour.
8243              */
8244             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8245         }
8246         define_one_arm_cp_reg(cpu, &sctlr);
8247     }
8248 
8249     if (cpu_isar_feature(aa64_lor, cpu)) {
8250         define_arm_cp_regs(cpu, lor_reginfo);
8251     }
8252     if (cpu_isar_feature(aa64_pan, cpu)) {
8253         define_one_arm_cp_reg(cpu, &pan_reginfo);
8254     }
8255 #ifndef CONFIG_USER_ONLY
8256     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8257         define_arm_cp_regs(cpu, ats1e1_reginfo);
8258     }
8259     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8260         define_arm_cp_regs(cpu, ats1cp_reginfo);
8261     }
8262 #endif
8263     if (cpu_isar_feature(aa64_uao, cpu)) {
8264         define_one_arm_cp_reg(cpu, &uao_reginfo);
8265     }
8266 
8267     if (cpu_isar_feature(aa64_dit, cpu)) {
8268         define_one_arm_cp_reg(cpu, &dit_reginfo);
8269     }
8270     if (cpu_isar_feature(aa64_ssbs, cpu)) {
8271         define_one_arm_cp_reg(cpu, &ssbs_reginfo);
8272     }
8273 
8274     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8275         define_arm_cp_regs(cpu, vhe_reginfo);
8276     }
8277 
8278     if (cpu_isar_feature(aa64_sve, cpu)) {
8279         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
8280         if (arm_feature(env, ARM_FEATURE_EL2)) {
8281             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
8282         } else {
8283             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
8284         }
8285         if (arm_feature(env, ARM_FEATURE_EL3)) {
8286             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
8287         }
8288     }
8289 
8290 #ifdef TARGET_AARCH64
8291     if (cpu_isar_feature(aa64_pauth, cpu)) {
8292         define_arm_cp_regs(cpu, pauth_reginfo);
8293     }
8294     if (cpu_isar_feature(aa64_rndr, cpu)) {
8295         define_arm_cp_regs(cpu, rndr_reginfo);
8296     }
8297 #ifndef CONFIG_USER_ONLY
8298     /* Data Cache clean instructions up to PoP */
8299     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8300         define_one_arm_cp_reg(cpu, dcpop_reg);
8301 
8302         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8303             define_one_arm_cp_reg(cpu, dcpodp_reg);
8304         }
8305     }
8306 #endif /*CONFIG_USER_ONLY*/
8307 
8308     /*
8309      * If full MTE is enabled, add all of the system registers.
8310      * If only "instructions available at EL0" are enabled,
8311      * then define only a RAZ/WI version of PSTATE.TCO.
8312      */
8313     if (cpu_isar_feature(aa64_mte, cpu)) {
8314         define_arm_cp_regs(cpu, mte_reginfo);
8315         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8316     } else if (cpu_isar_feature(aa64_mte_insn_reg, cpu)) {
8317         define_arm_cp_regs(cpu, mte_tco_ro_reginfo);
8318         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8319     }
8320 #endif
8321 
8322     if (cpu_isar_feature(any_predinv, cpu)) {
8323         define_arm_cp_regs(cpu, predinv_reginfo);
8324     }
8325 
8326     if (cpu_isar_feature(any_ccidx, cpu)) {
8327         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8328     }
8329 
8330 #ifndef CONFIG_USER_ONLY
8331     /*
8332      * Register redirections and aliases must be done last,
8333      * after the registers from the other extensions have been defined.
8334      */
8335     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8336         define_arm_vh_e2h_redirects_aliases(cpu);
8337     }
8338 #endif
8339 }
8340 
8341 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
8342 {
8343     CPUState *cs = CPU(cpu);
8344     CPUARMState *env = &cpu->env;
8345 
8346     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8347         /*
8348          * The lower part of each SVE register aliases to the FPU
8349          * registers so we don't need to include both.
8350          */
8351 #ifdef TARGET_AARCH64
8352         if (isar_feature_aa64_sve(&cpu->isar)) {
8353             gdb_register_coprocessor(cs, arm_gdb_get_svereg, arm_gdb_set_svereg,
8354                                      arm_gen_dynamic_svereg_xml(cs, cs->gdb_num_regs),
8355                                      "sve-registers.xml", 0);
8356         } else
8357 #endif
8358         {
8359             gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
8360                                      aarch64_fpu_gdb_set_reg,
8361                                      34, "aarch64-fpu.xml", 0);
8362         }
8363     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
8364         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8365                                  51, "arm-neon.xml", 0);
8366     } else if (cpu_isar_feature(aa32_simd_r32, cpu)) {
8367         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8368                                  35, "arm-vfp3.xml", 0);
8369     } else if (cpu_isar_feature(aa32_vfp_simd, cpu)) {
8370         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8371                                  19, "arm-vfp.xml", 0);
8372     }
8373     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
8374                              arm_gen_dynamic_sysreg_xml(cs, cs->gdb_num_regs),
8375                              "system-registers.xml", 0);
8376 
8377 }
8378 
8379 /* Sort alphabetically by type name, except for "any". */
8380 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8381 {
8382     ObjectClass *class_a = (ObjectClass *)a;
8383     ObjectClass *class_b = (ObjectClass *)b;
8384     const char *name_a, *name_b;
8385 
8386     name_a = object_class_get_name(class_a);
8387     name_b = object_class_get_name(class_b);
8388     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8389         return 1;
8390     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8391         return -1;
8392     } else {
8393         return strcmp(name_a, name_b);
8394     }
8395 }
8396 
8397 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8398 {
8399     ObjectClass *oc = data;
8400     const char *typename;
8401     char *name;
8402 
8403     typename = object_class_get_name(oc);
8404     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8405     qemu_printf("  %s\n", name);
8406     g_free(name);
8407 }
8408 
8409 void arm_cpu_list(void)
8410 {
8411     GSList *list;
8412 
8413     list = object_class_get_list(TYPE_ARM_CPU, false);
8414     list = g_slist_sort(list, arm_cpu_list_compare);
8415     qemu_printf("Available CPUs:\n");
8416     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8417     g_slist_free(list);
8418 }
8419 
8420 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8421 {
8422     ObjectClass *oc = data;
8423     CpuDefinitionInfoList **cpu_list = user_data;
8424     CpuDefinitionInfo *info;
8425     const char *typename;
8426 
8427     typename = object_class_get_name(oc);
8428     info = g_malloc0(sizeof(*info));
8429     info->name = g_strndup(typename,
8430                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8431     info->q_typename = g_strdup(typename);
8432 
8433     QAPI_LIST_PREPEND(*cpu_list, info);
8434 }
8435 
8436 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8437 {
8438     CpuDefinitionInfoList *cpu_list = NULL;
8439     GSList *list;
8440 
8441     list = object_class_get_list(TYPE_ARM_CPU, false);
8442     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8443     g_slist_free(list);
8444 
8445     return cpu_list;
8446 }
8447 
8448 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8449                                    void *opaque, int state, int secstate,
8450                                    int crm, int opc1, int opc2,
8451                                    const char *name)
8452 {
8453     /* Private utility function for define_one_arm_cp_reg_with_opaque():
8454      * add a single reginfo struct to the hash table.
8455      */
8456     uint32_t *key = g_new(uint32_t, 1);
8457     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
8458     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
8459     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
8460 
8461     r2->name = g_strdup(name);
8462     /* Reset the secure state to the specific incoming state.  This is
8463      * necessary as the register may have been defined with both states.
8464      */
8465     r2->secure = secstate;
8466 
8467     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8468         /* Register is banked (using both entries in array).
8469          * Overwriting fieldoffset as the array is only used to define
8470          * banked registers but later only fieldoffset is used.
8471          */
8472         r2->fieldoffset = r->bank_fieldoffsets[ns];
8473     }
8474 
8475     if (state == ARM_CP_STATE_AA32) {
8476         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8477             /* If the register is banked then we don't need to migrate or
8478              * reset the 32-bit instance in certain cases:
8479              *
8480              * 1) If the register has both 32-bit and 64-bit instances then we
8481              *    can count on the 64-bit instance taking care of the
8482              *    non-secure bank.
8483              * 2) If ARMv8 is enabled then we can count on a 64-bit version
8484              *    taking care of the secure bank.  This requires that separate
8485              *    32 and 64-bit definitions are provided.
8486              */
8487             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8488                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
8489                 r2->type |= ARM_CP_ALIAS;
8490             }
8491         } else if ((secstate != r->secure) && !ns) {
8492             /* The register is not banked so we only want to allow migration of
8493              * the non-secure instance.
8494              */
8495             r2->type |= ARM_CP_ALIAS;
8496         }
8497 
8498         if (r->state == ARM_CP_STATE_BOTH) {
8499             /* We assume it is a cp15 register if the .cp field is left unset.
8500              */
8501             if (r2->cp == 0) {
8502                 r2->cp = 15;
8503             }
8504 
8505 #ifdef HOST_WORDS_BIGENDIAN
8506             if (r2->fieldoffset) {
8507                 r2->fieldoffset += sizeof(uint32_t);
8508             }
8509 #endif
8510         }
8511     }
8512     if (state == ARM_CP_STATE_AA64) {
8513         /* To allow abbreviation of ARMCPRegInfo
8514          * definitions, we treat cp == 0 as equivalent to
8515          * the value for "standard guest-visible sysreg".
8516          * STATE_BOTH definitions are also always "standard
8517          * sysreg" in their AArch64 view (the .cp value may
8518          * be non-zero for the benefit of the AArch32 view).
8519          */
8520         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8521             r2->cp = CP_REG_ARM64_SYSREG_CP;
8522         }
8523         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
8524                                   r2->opc0, opc1, opc2);
8525     } else {
8526         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
8527     }
8528     if (opaque) {
8529         r2->opaque = opaque;
8530     }
8531     /* reginfo passed to helpers is correct for the actual access,
8532      * and is never ARM_CP_STATE_BOTH:
8533      */
8534     r2->state = state;
8535     /* Make sure reginfo passed to helpers for wildcarded regs
8536      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
8537      */
8538     r2->crm = crm;
8539     r2->opc1 = opc1;
8540     r2->opc2 = opc2;
8541     /* By convention, for wildcarded registers only the first
8542      * entry is used for migration; the others are marked as
8543      * ALIAS so we don't try to transfer the register
8544      * multiple times. Special registers (ie NOP/WFI) are
8545      * never migratable and not even raw-accessible.
8546      */
8547     if ((r->type & ARM_CP_SPECIAL)) {
8548         r2->type |= ARM_CP_NO_RAW;
8549     }
8550     if (((r->crm == CP_ANY) && crm != 0) ||
8551         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8552         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8553         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8554     }
8555 
8556     /* Check that raw accesses are either forbidden or handled. Note that
8557      * we can't assert this earlier because the setup of fieldoffset for
8558      * banked registers has to be done first.
8559      */
8560     if (!(r2->type & ARM_CP_NO_RAW)) {
8561         assert(!raw_accessors_invalid(r2));
8562     }
8563 
8564     /* Overriding of an existing definition must be explicitly
8565      * requested.
8566      */
8567     if (!(r->type & ARM_CP_OVERRIDE)) {
8568         ARMCPRegInfo *oldreg;
8569         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
8570         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
8571             fprintf(stderr, "Register redefined: cp=%d %d bit "
8572                     "crn=%d crm=%d opc1=%d opc2=%d, "
8573                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
8574                     r2->crn, r2->crm, r2->opc1, r2->opc2,
8575                     oldreg->name, r2->name);
8576             g_assert_not_reached();
8577         }
8578     }
8579     g_hash_table_insert(cpu->cp_regs, key, r2);
8580 }
8581 
8582 
8583 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8584                                        const ARMCPRegInfo *r, void *opaque)
8585 {
8586     /* Define implementations of coprocessor registers.
8587      * We store these in a hashtable because typically
8588      * there are less than 150 registers in a space which
8589      * is 16*16*16*8*8 = 262144 in size.
8590      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8591      * If a register is defined twice then the second definition is
8592      * used, so this can be used to define some generic registers and
8593      * then override them with implementation specific variations.
8594      * At least one of the original and the second definition should
8595      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8596      * against accidental use.
8597      *
8598      * The state field defines whether the register is to be
8599      * visible in the AArch32 or AArch64 execution state. If the
8600      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8601      * reginfo structure for the AArch32 view, which sees the lower
8602      * 32 bits of the 64 bit register.
8603      *
8604      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8605      * be wildcarded. AArch64 registers are always considered to be 64
8606      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8607      * the register, if any.
8608      */
8609     int crm, opc1, opc2, state;
8610     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8611     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8612     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8613     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8614     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8615     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8616     /* 64 bit registers have only CRm and Opc1 fields */
8617     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8618     /* op0 only exists in the AArch64 encodings */
8619     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8620     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8621     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8622     /*
8623      * This API is only for Arm's system coprocessors (14 and 15) or
8624      * (M-profile or v7A-and-earlier only) for implementation defined
8625      * coprocessors in the range 0..7.  Our decode assumes this, since
8626      * 8..13 can be used for other insns including VFP and Neon. See
8627      * valid_cp() in translate.c.  Assert here that we haven't tried
8628      * to use an invalid coprocessor number.
8629      */
8630     switch (r->state) {
8631     case ARM_CP_STATE_BOTH:
8632         /* 0 has a special meaning, but otherwise the same rules as AA32. */
8633         if (r->cp == 0) {
8634             break;
8635         }
8636         /* fall through */
8637     case ARM_CP_STATE_AA32:
8638         if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
8639             !arm_feature(&cpu->env, ARM_FEATURE_M)) {
8640             assert(r->cp >= 14 && r->cp <= 15);
8641         } else {
8642             assert(r->cp < 8 || (r->cp >= 14 && r->cp <= 15));
8643         }
8644         break;
8645     case ARM_CP_STATE_AA64:
8646         assert(r->cp == 0 || r->cp == CP_REG_ARM64_SYSREG_CP);
8647         break;
8648     default:
8649         g_assert_not_reached();
8650     }
8651     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8652      * encodes a minimum access level for the register. We roll this
8653      * runtime check into our general permission check code, so check
8654      * here that the reginfo's specified permissions are strict enough
8655      * to encompass the generic architectural permission check.
8656      */
8657     if (r->state != ARM_CP_STATE_AA32) {
8658         int mask = 0;
8659         switch (r->opc1) {
8660         case 0:
8661             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8662             mask = PL0U_R | PL1_RW;
8663             break;
8664         case 1: case 2:
8665             /* min_EL EL1 */
8666             mask = PL1_RW;
8667             break;
8668         case 3:
8669             /* min_EL EL0 */
8670             mask = PL0_RW;
8671             break;
8672         case 4:
8673         case 5:
8674             /* min_EL EL2 */
8675             mask = PL2_RW;
8676             break;
8677         case 6:
8678             /* min_EL EL3 */
8679             mask = PL3_RW;
8680             break;
8681         case 7:
8682             /* min_EL EL1, secure mode only (we don't check the latter) */
8683             mask = PL1_RW;
8684             break;
8685         default:
8686             /* broken reginfo with out-of-range opc1 */
8687             assert(false);
8688             break;
8689         }
8690         /* assert our permissions are not too lax (stricter is fine) */
8691         assert((r->access & ~mask) == 0);
8692     }
8693 
8694     /* Check that the register definition has enough info to handle
8695      * reads and writes if they are permitted.
8696      */
8697     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
8698         if (r->access & PL3_R) {
8699             assert((r->fieldoffset ||
8700                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8701                    r->readfn);
8702         }
8703         if (r->access & PL3_W) {
8704             assert((r->fieldoffset ||
8705                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
8706                    r->writefn);
8707         }
8708     }
8709     /* Bad type field probably means missing sentinel at end of reg list */
8710     assert(cptype_valid(r->type));
8711     for (crm = crmmin; crm <= crmmax; crm++) {
8712         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
8713             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
8714                 for (state = ARM_CP_STATE_AA32;
8715                      state <= ARM_CP_STATE_AA64; state++) {
8716                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
8717                         continue;
8718                     }
8719                     if (state == ARM_CP_STATE_AA32) {
8720                         /* Under AArch32 CP registers can be common
8721                          * (same for secure and non-secure world) or banked.
8722                          */
8723                         char *name;
8724 
8725                         switch (r->secure) {
8726                         case ARM_CP_SECSTATE_S:
8727                         case ARM_CP_SECSTATE_NS:
8728                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8729                                                    r->secure, crm, opc1, opc2,
8730                                                    r->name);
8731                             break;
8732                         default:
8733                             name = g_strdup_printf("%s_S", r->name);
8734                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8735                                                    ARM_CP_SECSTATE_S,
8736                                                    crm, opc1, opc2, name);
8737                             g_free(name);
8738                             add_cpreg_to_hashtable(cpu, r, opaque, state,
8739                                                    ARM_CP_SECSTATE_NS,
8740                                                    crm, opc1, opc2, r->name);
8741                             break;
8742                         }
8743                     } else {
8744                         /* AArch64 registers get mapped to non-secure instance
8745                          * of AArch32 */
8746                         add_cpreg_to_hashtable(cpu, r, opaque, state,
8747                                                ARM_CP_SECSTATE_NS,
8748                                                crm, opc1, opc2, r->name);
8749                     }
8750                 }
8751             }
8752         }
8753     }
8754 }
8755 
8756 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
8757                                     const ARMCPRegInfo *regs, void *opaque)
8758 {
8759     /* Define a whole list of registers */
8760     const ARMCPRegInfo *r;
8761     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8762         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
8763     }
8764 }
8765 
8766 /*
8767  * Modify ARMCPRegInfo for access from userspace.
8768  *
8769  * This is a data driven modification directed by
8770  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
8771  * user-space cannot alter any values and dynamic values pertaining to
8772  * execution state are hidden from user space view anyway.
8773  */
8774 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
8775 {
8776     const ARMCPRegUserSpaceInfo *m;
8777     ARMCPRegInfo *r;
8778 
8779     for (m = mods; m->name; m++) {
8780         GPatternSpec *pat = NULL;
8781         if (m->is_glob) {
8782             pat = g_pattern_spec_new(m->name);
8783         }
8784         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
8785             if (pat && g_pattern_match_string(pat, r->name)) {
8786                 r->type = ARM_CP_CONST;
8787                 r->access = PL0U_R;
8788                 r->resetvalue = 0;
8789                 /* continue */
8790             } else if (strcmp(r->name, m->name) == 0) {
8791                 r->type = ARM_CP_CONST;
8792                 r->access = PL0U_R;
8793                 r->resetvalue &= m->exported_bits;
8794                 r->resetvalue |= m->fixed_bits;
8795                 break;
8796             }
8797         }
8798         if (pat) {
8799             g_pattern_spec_free(pat);
8800         }
8801     }
8802 }
8803 
8804 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
8805 {
8806     return g_hash_table_lookup(cpregs, &encoded_cp);
8807 }
8808 
8809 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
8810                          uint64_t value)
8811 {
8812     /* Helper coprocessor write function for write-ignore registers */
8813 }
8814 
8815 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
8816 {
8817     /* Helper coprocessor write function for read-as-zero registers */
8818     return 0;
8819 }
8820 
8821 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
8822 {
8823     /* Helper coprocessor reset function for do-nothing-on-reset registers */
8824 }
8825 
8826 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
8827 {
8828     /* Return true if it is not valid for us to switch to
8829      * this CPU mode (ie all the UNPREDICTABLE cases in
8830      * the ARM ARM CPSRWriteByInstr pseudocode).
8831      */
8832 
8833     /* Changes to or from Hyp via MSR and CPS are illegal. */
8834     if (write_type == CPSRWriteByInstr &&
8835         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
8836          mode == ARM_CPU_MODE_HYP)) {
8837         return 1;
8838     }
8839 
8840     switch (mode) {
8841     case ARM_CPU_MODE_USR:
8842         return 0;
8843     case ARM_CPU_MODE_SYS:
8844     case ARM_CPU_MODE_SVC:
8845     case ARM_CPU_MODE_ABT:
8846     case ARM_CPU_MODE_UND:
8847     case ARM_CPU_MODE_IRQ:
8848     case ARM_CPU_MODE_FIQ:
8849         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
8850          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
8851          */
8852         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
8853          * and CPS are treated as illegal mode changes.
8854          */
8855         if (write_type == CPSRWriteByInstr &&
8856             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
8857             (arm_hcr_el2_eff(env) & HCR_TGE)) {
8858             return 1;
8859         }
8860         return 0;
8861     case ARM_CPU_MODE_HYP:
8862         return !arm_is_el2_enabled(env) || arm_current_el(env) < 2;
8863     case ARM_CPU_MODE_MON:
8864         return arm_current_el(env) < 3;
8865     default:
8866         return 1;
8867     }
8868 }
8869 
8870 uint32_t cpsr_read(CPUARMState *env)
8871 {
8872     int ZF;
8873     ZF = (env->ZF == 0);
8874     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
8875         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
8876         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
8877         | ((env->condexec_bits & 0xfc) << 8)
8878         | (env->GE << 16) | (env->daif & CPSR_AIF);
8879 }
8880 
8881 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
8882                 CPSRWriteType write_type)
8883 {
8884     uint32_t changed_daif;
8885 
8886     if (mask & CPSR_NZCV) {
8887         env->ZF = (~val) & CPSR_Z;
8888         env->NF = val;
8889         env->CF = (val >> 29) & 1;
8890         env->VF = (val << 3) & 0x80000000;
8891     }
8892     if (mask & CPSR_Q)
8893         env->QF = ((val & CPSR_Q) != 0);
8894     if (mask & CPSR_T)
8895         env->thumb = ((val & CPSR_T) != 0);
8896     if (mask & CPSR_IT_0_1) {
8897         env->condexec_bits &= ~3;
8898         env->condexec_bits |= (val >> 25) & 3;
8899     }
8900     if (mask & CPSR_IT_2_7) {
8901         env->condexec_bits &= 3;
8902         env->condexec_bits |= (val >> 8) & 0xfc;
8903     }
8904     if (mask & CPSR_GE) {
8905         env->GE = (val >> 16) & 0xf;
8906     }
8907 
8908     /* In a V7 implementation that includes the security extensions but does
8909      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
8910      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
8911      * bits respectively.
8912      *
8913      * In a V8 implementation, it is permitted for privileged software to
8914      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
8915      */
8916     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
8917         arm_feature(env, ARM_FEATURE_EL3) &&
8918         !arm_feature(env, ARM_FEATURE_EL2) &&
8919         !arm_is_secure(env)) {
8920 
8921         changed_daif = (env->daif ^ val) & mask;
8922 
8923         if (changed_daif & CPSR_A) {
8924             /* Check to see if we are allowed to change the masking of async
8925              * abort exceptions from a non-secure state.
8926              */
8927             if (!(env->cp15.scr_el3 & SCR_AW)) {
8928                 qemu_log_mask(LOG_GUEST_ERROR,
8929                               "Ignoring attempt to switch CPSR_A flag from "
8930                               "non-secure world with SCR.AW bit clear\n");
8931                 mask &= ~CPSR_A;
8932             }
8933         }
8934 
8935         if (changed_daif & CPSR_F) {
8936             /* Check to see if we are allowed to change the masking of FIQ
8937              * exceptions from a non-secure state.
8938              */
8939             if (!(env->cp15.scr_el3 & SCR_FW)) {
8940                 qemu_log_mask(LOG_GUEST_ERROR,
8941                               "Ignoring attempt to switch CPSR_F flag from "
8942                               "non-secure world with SCR.FW bit clear\n");
8943                 mask &= ~CPSR_F;
8944             }
8945 
8946             /* Check whether non-maskable FIQ (NMFI) support is enabled.
8947              * If this bit is set software is not allowed to mask
8948              * FIQs, but is allowed to set CPSR_F to 0.
8949              */
8950             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
8951                 (val & CPSR_F)) {
8952                 qemu_log_mask(LOG_GUEST_ERROR,
8953                               "Ignoring attempt to enable CPSR_F flag "
8954                               "(non-maskable FIQ [NMFI] support enabled)\n");
8955                 mask &= ~CPSR_F;
8956             }
8957         }
8958     }
8959 
8960     env->daif &= ~(CPSR_AIF & mask);
8961     env->daif |= val & CPSR_AIF & mask;
8962 
8963     if (write_type != CPSRWriteRaw &&
8964         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
8965         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
8966             /* Note that we can only get here in USR mode if this is a
8967              * gdb stub write; for this case we follow the architectural
8968              * behaviour for guest writes in USR mode of ignoring an attempt
8969              * to switch mode. (Those are caught by translate.c for writes
8970              * triggered by guest instructions.)
8971              */
8972             mask &= ~CPSR_M;
8973         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
8974             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
8975              * v7, and has defined behaviour in v8:
8976              *  + leave CPSR.M untouched
8977              *  + allow changes to the other CPSR fields
8978              *  + set PSTATE.IL
8979              * For user changes via the GDB stub, we don't set PSTATE.IL,
8980              * as this would be unnecessarily harsh for a user error.
8981              */
8982             mask &= ~CPSR_M;
8983             if (write_type != CPSRWriteByGDBStub &&
8984                 arm_feature(env, ARM_FEATURE_V8)) {
8985                 mask |= CPSR_IL;
8986                 val |= CPSR_IL;
8987             }
8988             qemu_log_mask(LOG_GUEST_ERROR,
8989                           "Illegal AArch32 mode switch attempt from %s to %s\n",
8990                           aarch32_mode_name(env->uncached_cpsr),
8991                           aarch32_mode_name(val));
8992         } else {
8993             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
8994                           write_type == CPSRWriteExceptionReturn ?
8995                           "Exception return from AArch32" :
8996                           "AArch32 mode switch from",
8997                           aarch32_mode_name(env->uncached_cpsr),
8998                           aarch32_mode_name(val), env->regs[15]);
8999             switch_mode(env, val & CPSR_M);
9000         }
9001     }
9002     mask &= ~CACHED_CPSR_BITS;
9003     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
9004 }
9005 
9006 /* Sign/zero extend */
9007 uint32_t HELPER(sxtb16)(uint32_t x)
9008 {
9009     uint32_t res;
9010     res = (uint16_t)(int8_t)x;
9011     res |= (uint32_t)(int8_t)(x >> 16) << 16;
9012     return res;
9013 }
9014 
9015 uint32_t HELPER(uxtb16)(uint32_t x)
9016 {
9017     uint32_t res;
9018     res = (uint16_t)(uint8_t)x;
9019     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
9020     return res;
9021 }
9022 
9023 int32_t HELPER(sdiv)(int32_t num, int32_t den)
9024 {
9025     if (den == 0)
9026       return 0;
9027     if (num == INT_MIN && den == -1)
9028       return INT_MIN;
9029     return num / den;
9030 }
9031 
9032 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
9033 {
9034     if (den == 0)
9035       return 0;
9036     return num / den;
9037 }
9038 
9039 uint32_t HELPER(rbit)(uint32_t x)
9040 {
9041     return revbit32(x);
9042 }
9043 
9044 #ifdef CONFIG_USER_ONLY
9045 
9046 static void switch_mode(CPUARMState *env, int mode)
9047 {
9048     ARMCPU *cpu = env_archcpu(env);
9049 
9050     if (mode != ARM_CPU_MODE_USR) {
9051         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
9052     }
9053 }
9054 
9055 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9056                                  uint32_t cur_el, bool secure)
9057 {
9058     return 1;
9059 }
9060 
9061 void aarch64_sync_64_to_32(CPUARMState *env)
9062 {
9063     g_assert_not_reached();
9064 }
9065 
9066 #else
9067 
9068 static void switch_mode(CPUARMState *env, int mode)
9069 {
9070     int old_mode;
9071     int i;
9072 
9073     old_mode = env->uncached_cpsr & CPSR_M;
9074     if (mode == old_mode)
9075         return;
9076 
9077     if (old_mode == ARM_CPU_MODE_FIQ) {
9078         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
9079         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
9080     } else if (mode == ARM_CPU_MODE_FIQ) {
9081         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
9082         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
9083     }
9084 
9085     i = bank_number(old_mode);
9086     env->banked_r13[i] = env->regs[13];
9087     env->banked_spsr[i] = env->spsr;
9088 
9089     i = bank_number(mode);
9090     env->regs[13] = env->banked_r13[i];
9091     env->spsr = env->banked_spsr[i];
9092 
9093     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
9094     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
9095 }
9096 
9097 /* Physical Interrupt Target EL Lookup Table
9098  *
9099  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
9100  *
9101  * The below multi-dimensional table is used for looking up the target
9102  * exception level given numerous condition criteria.  Specifically, the
9103  * target EL is based on SCR and HCR routing controls as well as the
9104  * currently executing EL and secure state.
9105  *
9106  *    Dimensions:
9107  *    target_el_table[2][2][2][2][2][4]
9108  *                    |  |  |  |  |  +--- Current EL
9109  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
9110  *                    |  |  |  +--------- HCR mask override
9111  *                    |  |  +------------ SCR exec state control
9112  *                    |  +--------------- SCR mask override
9113  *                    +------------------ 32-bit(0)/64-bit(1) EL3
9114  *
9115  *    The table values are as such:
9116  *    0-3 = EL0-EL3
9117  *     -1 = Cannot occur
9118  *
9119  * The ARM ARM target EL table includes entries indicating that an "exception
9120  * is not taken".  The two cases where this is applicable are:
9121  *    1) An exception is taken from EL3 but the SCR does not have the exception
9122  *    routed to EL3.
9123  *    2) An exception is taken from EL2 but the HCR does not have the exception
9124  *    routed to EL2.
9125  * In these two cases, the below table contain a target of EL1.  This value is
9126  * returned as it is expected that the consumer of the table data will check
9127  * for "target EL >= current EL" to ensure the exception is not taken.
9128  *
9129  *            SCR     HCR
9130  *         64  EA     AMO                 From
9131  *        BIT IRQ     IMO      Non-secure         Secure
9132  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
9133  */
9134 static const int8_t target_el_table[2][2][2][2][2][4] = {
9135     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9136        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
9137       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9138        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
9139      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9140        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
9141       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9142        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
9143     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
9144        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 2,  2, -1,  1 },},},
9145       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1,  1,  1 },},
9146        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 2,  2,  2,  1 },},},},
9147      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
9148        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
9149       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},
9150        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},},},},
9151 };
9152 
9153 /*
9154  * Determine the target EL for physical exceptions
9155  */
9156 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9157                                  uint32_t cur_el, bool secure)
9158 {
9159     CPUARMState *env = cs->env_ptr;
9160     bool rw;
9161     bool scr;
9162     bool hcr;
9163     int target_el;
9164     /* Is the highest EL AArch64? */
9165     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
9166     uint64_t hcr_el2;
9167 
9168     if (arm_feature(env, ARM_FEATURE_EL3)) {
9169         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
9170     } else {
9171         /* Either EL2 is the highest EL (and so the EL2 register width
9172          * is given by is64); or there is no EL2 or EL3, in which case
9173          * the value of 'rw' does not affect the table lookup anyway.
9174          */
9175         rw = is64;
9176     }
9177 
9178     hcr_el2 = arm_hcr_el2_eff(env);
9179     switch (excp_idx) {
9180     case EXCP_IRQ:
9181         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
9182         hcr = hcr_el2 & HCR_IMO;
9183         break;
9184     case EXCP_FIQ:
9185         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
9186         hcr = hcr_el2 & HCR_FMO;
9187         break;
9188     default:
9189         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
9190         hcr = hcr_el2 & HCR_AMO;
9191         break;
9192     };
9193 
9194     /*
9195      * For these purposes, TGE and AMO/IMO/FMO both force the
9196      * interrupt to EL2.  Fold TGE into the bit extracted above.
9197      */
9198     hcr |= (hcr_el2 & HCR_TGE) != 0;
9199 
9200     /* Perform a table-lookup for the target EL given the current state */
9201     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
9202 
9203     assert(target_el > 0);
9204 
9205     return target_el;
9206 }
9207 
9208 void arm_log_exception(int idx)
9209 {
9210     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9211         const char *exc = NULL;
9212         static const char * const excnames[] = {
9213             [EXCP_UDEF] = "Undefined Instruction",
9214             [EXCP_SWI] = "SVC",
9215             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9216             [EXCP_DATA_ABORT] = "Data Abort",
9217             [EXCP_IRQ] = "IRQ",
9218             [EXCP_FIQ] = "FIQ",
9219             [EXCP_BKPT] = "Breakpoint",
9220             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9221             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9222             [EXCP_HVC] = "Hypervisor Call",
9223             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9224             [EXCP_SMC] = "Secure Monitor Call",
9225             [EXCP_VIRQ] = "Virtual IRQ",
9226             [EXCP_VFIQ] = "Virtual FIQ",
9227             [EXCP_SEMIHOST] = "Semihosting call",
9228             [EXCP_NOCP] = "v7M NOCP UsageFault",
9229             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9230             [EXCP_STKOF] = "v8M STKOF UsageFault",
9231             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9232             [EXCP_LSERR] = "v8M LSERR UsageFault",
9233             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9234         };
9235 
9236         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9237             exc = excnames[idx];
9238         }
9239         if (!exc) {
9240             exc = "unknown";
9241         }
9242         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
9243     }
9244 }
9245 
9246 /*
9247  * Function used to synchronize QEMU's AArch64 register set with AArch32
9248  * register set.  This is necessary when switching between AArch32 and AArch64
9249  * execution state.
9250  */
9251 void aarch64_sync_32_to_64(CPUARMState *env)
9252 {
9253     int i;
9254     uint32_t mode = env->uncached_cpsr & CPSR_M;
9255 
9256     /* We can blanket copy R[0:7] to X[0:7] */
9257     for (i = 0; i < 8; i++) {
9258         env->xregs[i] = env->regs[i];
9259     }
9260 
9261     /*
9262      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9263      * Otherwise, they come from the banked user regs.
9264      */
9265     if (mode == ARM_CPU_MODE_FIQ) {
9266         for (i = 8; i < 13; i++) {
9267             env->xregs[i] = env->usr_regs[i - 8];
9268         }
9269     } else {
9270         for (i = 8; i < 13; i++) {
9271             env->xregs[i] = env->regs[i];
9272         }
9273     }
9274 
9275     /*
9276      * Registers x13-x23 are the various mode SP and FP registers. Registers
9277      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9278      * from the mode banked register.
9279      */
9280     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9281         env->xregs[13] = env->regs[13];
9282         env->xregs[14] = env->regs[14];
9283     } else {
9284         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9285         /* HYP is an exception in that it is copied from r14 */
9286         if (mode == ARM_CPU_MODE_HYP) {
9287             env->xregs[14] = env->regs[14];
9288         } else {
9289             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9290         }
9291     }
9292 
9293     if (mode == ARM_CPU_MODE_HYP) {
9294         env->xregs[15] = env->regs[13];
9295     } else {
9296         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9297     }
9298 
9299     if (mode == ARM_CPU_MODE_IRQ) {
9300         env->xregs[16] = env->regs[14];
9301         env->xregs[17] = env->regs[13];
9302     } else {
9303         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9304         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9305     }
9306 
9307     if (mode == ARM_CPU_MODE_SVC) {
9308         env->xregs[18] = env->regs[14];
9309         env->xregs[19] = env->regs[13];
9310     } else {
9311         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9312         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9313     }
9314 
9315     if (mode == ARM_CPU_MODE_ABT) {
9316         env->xregs[20] = env->regs[14];
9317         env->xregs[21] = env->regs[13];
9318     } else {
9319         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9320         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9321     }
9322 
9323     if (mode == ARM_CPU_MODE_UND) {
9324         env->xregs[22] = env->regs[14];
9325         env->xregs[23] = env->regs[13];
9326     } else {
9327         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9328         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9329     }
9330 
9331     /*
9332      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9333      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9334      * FIQ bank for r8-r14.
9335      */
9336     if (mode == ARM_CPU_MODE_FIQ) {
9337         for (i = 24; i < 31; i++) {
9338             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9339         }
9340     } else {
9341         for (i = 24; i < 29; i++) {
9342             env->xregs[i] = env->fiq_regs[i - 24];
9343         }
9344         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9345         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9346     }
9347 
9348     env->pc = env->regs[15];
9349 }
9350 
9351 /*
9352  * Function used to synchronize QEMU's AArch32 register set with AArch64
9353  * register set.  This is necessary when switching between AArch32 and AArch64
9354  * execution state.
9355  */
9356 void aarch64_sync_64_to_32(CPUARMState *env)
9357 {
9358     int i;
9359     uint32_t mode = env->uncached_cpsr & CPSR_M;
9360 
9361     /* We can blanket copy X[0:7] to R[0:7] */
9362     for (i = 0; i < 8; i++) {
9363         env->regs[i] = env->xregs[i];
9364     }
9365 
9366     /*
9367      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9368      * Otherwise, we copy x8-x12 into the banked user regs.
9369      */
9370     if (mode == ARM_CPU_MODE_FIQ) {
9371         for (i = 8; i < 13; i++) {
9372             env->usr_regs[i - 8] = env->xregs[i];
9373         }
9374     } else {
9375         for (i = 8; i < 13; i++) {
9376             env->regs[i] = env->xregs[i];
9377         }
9378     }
9379 
9380     /*
9381      * Registers r13 & r14 depend on the current mode.
9382      * If we are in a given mode, we copy the corresponding x registers to r13
9383      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9384      * for the mode.
9385      */
9386     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9387         env->regs[13] = env->xregs[13];
9388         env->regs[14] = env->xregs[14];
9389     } else {
9390         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9391 
9392         /*
9393          * HYP is an exception in that it does not have its own banked r14 but
9394          * shares the USR r14
9395          */
9396         if (mode == ARM_CPU_MODE_HYP) {
9397             env->regs[14] = env->xregs[14];
9398         } else {
9399             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9400         }
9401     }
9402 
9403     if (mode == ARM_CPU_MODE_HYP) {
9404         env->regs[13] = env->xregs[15];
9405     } else {
9406         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9407     }
9408 
9409     if (mode == ARM_CPU_MODE_IRQ) {
9410         env->regs[14] = env->xregs[16];
9411         env->regs[13] = env->xregs[17];
9412     } else {
9413         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9414         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9415     }
9416 
9417     if (mode == ARM_CPU_MODE_SVC) {
9418         env->regs[14] = env->xregs[18];
9419         env->regs[13] = env->xregs[19];
9420     } else {
9421         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9422         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9423     }
9424 
9425     if (mode == ARM_CPU_MODE_ABT) {
9426         env->regs[14] = env->xregs[20];
9427         env->regs[13] = env->xregs[21];
9428     } else {
9429         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9430         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9431     }
9432 
9433     if (mode == ARM_CPU_MODE_UND) {
9434         env->regs[14] = env->xregs[22];
9435         env->regs[13] = env->xregs[23];
9436     } else {
9437         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9438         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9439     }
9440 
9441     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9442      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9443      * FIQ bank for r8-r14.
9444      */
9445     if (mode == ARM_CPU_MODE_FIQ) {
9446         for (i = 24; i < 31; i++) {
9447             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9448         }
9449     } else {
9450         for (i = 24; i < 29; i++) {
9451             env->fiq_regs[i - 24] = env->xregs[i];
9452         }
9453         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9454         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9455     }
9456 
9457     env->regs[15] = env->pc;
9458 }
9459 
9460 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9461                                    uint32_t mask, uint32_t offset,
9462                                    uint32_t newpc)
9463 {
9464     int new_el;
9465 
9466     /* Change the CPU state so as to actually take the exception. */
9467     switch_mode(env, new_mode);
9468 
9469     /*
9470      * For exceptions taken to AArch32 we must clear the SS bit in both
9471      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9472      */
9473     env->pstate &= ~PSTATE_SS;
9474     env->spsr = cpsr_read(env);
9475     /* Clear IT bits.  */
9476     env->condexec_bits = 0;
9477     /* Switch to the new mode, and to the correct instruction set.  */
9478     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9479 
9480     /* This must be after mode switching. */
9481     new_el = arm_current_el(env);
9482 
9483     /* Set new mode endianness */
9484     env->uncached_cpsr &= ~CPSR_E;
9485     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9486         env->uncached_cpsr |= CPSR_E;
9487     }
9488     /* J and IL must always be cleared for exception entry */
9489     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9490     env->daif |= mask;
9491 
9492     if (cpu_isar_feature(aa32_ssbs, env_archcpu(env))) {
9493         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_32) {
9494             env->uncached_cpsr |= CPSR_SSBS;
9495         } else {
9496             env->uncached_cpsr &= ~CPSR_SSBS;
9497         }
9498     }
9499 
9500     if (new_mode == ARM_CPU_MODE_HYP) {
9501         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9502         env->elr_el[2] = env->regs[15];
9503     } else {
9504         /* CPSR.PAN is normally preserved preserved unless...  */
9505         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9506             switch (new_el) {
9507             case 3:
9508                 if (!arm_is_secure_below_el3(env)) {
9509                     /* ... the target is EL3, from non-secure state.  */
9510                     env->uncached_cpsr &= ~CPSR_PAN;
9511                     break;
9512                 }
9513                 /* ... the target is EL3, from secure state ... */
9514                 /* fall through */
9515             case 1:
9516                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9517                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9518                     env->uncached_cpsr |= CPSR_PAN;
9519                 }
9520                 break;
9521             }
9522         }
9523         /*
9524          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9525          * and we should just guard the thumb mode on V4
9526          */
9527         if (arm_feature(env, ARM_FEATURE_V4T)) {
9528             env->thumb =
9529                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9530         }
9531         env->regs[14] = env->regs[15] + offset;
9532     }
9533     env->regs[15] = newpc;
9534     arm_rebuild_hflags(env);
9535 }
9536 
9537 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9538 {
9539     /*
9540      * Handle exception entry to Hyp mode; this is sufficiently
9541      * different to entry to other AArch32 modes that we handle it
9542      * separately here.
9543      *
9544      * The vector table entry used is always the 0x14 Hyp mode entry point,
9545      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
9546      * The offset applied to the preferred return address is always zero
9547      * (see DDI0487C.a section G1.12.3).
9548      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9549      */
9550     uint32_t addr, mask;
9551     ARMCPU *cpu = ARM_CPU(cs);
9552     CPUARMState *env = &cpu->env;
9553 
9554     switch (cs->exception_index) {
9555     case EXCP_UDEF:
9556         addr = 0x04;
9557         break;
9558     case EXCP_SWI:
9559         addr = 0x14;
9560         break;
9561     case EXCP_BKPT:
9562         /* Fall through to prefetch abort.  */
9563     case EXCP_PREFETCH_ABORT:
9564         env->cp15.ifar_s = env->exception.vaddress;
9565         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9566                       (uint32_t)env->exception.vaddress);
9567         addr = 0x0c;
9568         break;
9569     case EXCP_DATA_ABORT:
9570         env->cp15.dfar_s = env->exception.vaddress;
9571         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9572                       (uint32_t)env->exception.vaddress);
9573         addr = 0x10;
9574         break;
9575     case EXCP_IRQ:
9576         addr = 0x18;
9577         break;
9578     case EXCP_FIQ:
9579         addr = 0x1c;
9580         break;
9581     case EXCP_HVC:
9582         addr = 0x08;
9583         break;
9584     case EXCP_HYP_TRAP:
9585         addr = 0x14;
9586         break;
9587     default:
9588         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9589     }
9590 
9591     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9592         if (!arm_feature(env, ARM_FEATURE_V8)) {
9593             /*
9594              * QEMU syndrome values are v8-style. v7 has the IL bit
9595              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9596              * If this is a v7 CPU, squash the IL bit in those cases.
9597              */
9598             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9599                 (cs->exception_index == EXCP_DATA_ABORT &&
9600                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9601                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9602                 env->exception.syndrome &= ~ARM_EL_IL;
9603             }
9604         }
9605         env->cp15.esr_el[2] = env->exception.syndrome;
9606     }
9607 
9608     if (arm_current_el(env) != 2 && addr < 0x14) {
9609         addr = 0x14;
9610     }
9611 
9612     mask = 0;
9613     if (!(env->cp15.scr_el3 & SCR_EA)) {
9614         mask |= CPSR_A;
9615     }
9616     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9617         mask |= CPSR_I;
9618     }
9619     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9620         mask |= CPSR_F;
9621     }
9622 
9623     addr += env->cp15.hvbar;
9624 
9625     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9626 }
9627 
9628 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9629 {
9630     ARMCPU *cpu = ARM_CPU(cs);
9631     CPUARMState *env = &cpu->env;
9632     uint32_t addr;
9633     uint32_t mask;
9634     int new_mode;
9635     uint32_t offset;
9636     uint32_t moe;
9637 
9638     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9639     switch (syn_get_ec(env->exception.syndrome)) {
9640     case EC_BREAKPOINT:
9641     case EC_BREAKPOINT_SAME_EL:
9642         moe = 1;
9643         break;
9644     case EC_WATCHPOINT:
9645     case EC_WATCHPOINT_SAME_EL:
9646         moe = 10;
9647         break;
9648     case EC_AA32_BKPT:
9649         moe = 3;
9650         break;
9651     case EC_VECTORCATCH:
9652         moe = 5;
9653         break;
9654     default:
9655         moe = 0;
9656         break;
9657     }
9658 
9659     if (moe) {
9660         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9661     }
9662 
9663     if (env->exception.target_el == 2) {
9664         arm_cpu_do_interrupt_aarch32_hyp(cs);
9665         return;
9666     }
9667 
9668     switch (cs->exception_index) {
9669     case EXCP_UDEF:
9670         new_mode = ARM_CPU_MODE_UND;
9671         addr = 0x04;
9672         mask = CPSR_I;
9673         if (env->thumb)
9674             offset = 2;
9675         else
9676             offset = 4;
9677         break;
9678     case EXCP_SWI:
9679         new_mode = ARM_CPU_MODE_SVC;
9680         addr = 0x08;
9681         mask = CPSR_I;
9682         /* The PC already points to the next instruction.  */
9683         offset = 0;
9684         break;
9685     case EXCP_BKPT:
9686         /* Fall through to prefetch abort.  */
9687     case EXCP_PREFETCH_ABORT:
9688         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
9689         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
9690         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
9691                       env->exception.fsr, (uint32_t)env->exception.vaddress);
9692         new_mode = ARM_CPU_MODE_ABT;
9693         addr = 0x0c;
9694         mask = CPSR_A | CPSR_I;
9695         offset = 4;
9696         break;
9697     case EXCP_DATA_ABORT:
9698         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
9699         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
9700         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
9701                       env->exception.fsr,
9702                       (uint32_t)env->exception.vaddress);
9703         new_mode = ARM_CPU_MODE_ABT;
9704         addr = 0x10;
9705         mask = CPSR_A | CPSR_I;
9706         offset = 8;
9707         break;
9708     case EXCP_IRQ:
9709         new_mode = ARM_CPU_MODE_IRQ;
9710         addr = 0x18;
9711         /* Disable IRQ and imprecise data aborts.  */
9712         mask = CPSR_A | CPSR_I;
9713         offset = 4;
9714         if (env->cp15.scr_el3 & SCR_IRQ) {
9715             /* IRQ routed to monitor mode */
9716             new_mode = ARM_CPU_MODE_MON;
9717             mask |= CPSR_F;
9718         }
9719         break;
9720     case EXCP_FIQ:
9721         new_mode = ARM_CPU_MODE_FIQ;
9722         addr = 0x1c;
9723         /* Disable FIQ, IRQ and imprecise data aborts.  */
9724         mask = CPSR_A | CPSR_I | CPSR_F;
9725         if (env->cp15.scr_el3 & SCR_FIQ) {
9726             /* FIQ routed to monitor mode */
9727             new_mode = ARM_CPU_MODE_MON;
9728         }
9729         offset = 4;
9730         break;
9731     case EXCP_VIRQ:
9732         new_mode = ARM_CPU_MODE_IRQ;
9733         addr = 0x18;
9734         /* Disable IRQ and imprecise data aborts.  */
9735         mask = CPSR_A | CPSR_I;
9736         offset = 4;
9737         break;
9738     case EXCP_VFIQ:
9739         new_mode = ARM_CPU_MODE_FIQ;
9740         addr = 0x1c;
9741         /* Disable FIQ, IRQ and imprecise data aborts.  */
9742         mask = CPSR_A | CPSR_I | CPSR_F;
9743         offset = 4;
9744         break;
9745     case EXCP_SMC:
9746         new_mode = ARM_CPU_MODE_MON;
9747         addr = 0x08;
9748         mask = CPSR_A | CPSR_I | CPSR_F;
9749         offset = 0;
9750         break;
9751     default:
9752         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9753         return; /* Never happens.  Keep compiler happy.  */
9754     }
9755 
9756     if (new_mode == ARM_CPU_MODE_MON) {
9757         addr += env->cp15.mvbar;
9758     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
9759         /* High vectors. When enabled, base address cannot be remapped. */
9760         addr += 0xffff0000;
9761     } else {
9762         /* ARM v7 architectures provide a vector base address register to remap
9763          * the interrupt vector table.
9764          * This register is only followed in non-monitor mode, and is banked.
9765          * Note: only bits 31:5 are valid.
9766          */
9767         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
9768     }
9769 
9770     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
9771         env->cp15.scr_el3 &= ~SCR_NS;
9772     }
9773 
9774     take_aarch32_exception(env, new_mode, mask, offset, addr);
9775 }
9776 
9777 static int aarch64_regnum(CPUARMState *env, int aarch32_reg)
9778 {
9779     /*
9780      * Return the register number of the AArch64 view of the AArch32
9781      * register @aarch32_reg. The CPUARMState CPSR is assumed to still
9782      * be that of the AArch32 mode the exception came from.
9783      */
9784     int mode = env->uncached_cpsr & CPSR_M;
9785 
9786     switch (aarch32_reg) {
9787     case 0 ... 7:
9788         return aarch32_reg;
9789     case 8 ... 12:
9790         return mode == ARM_CPU_MODE_FIQ ? aarch32_reg + 16 : aarch32_reg;
9791     case 13:
9792         switch (mode) {
9793         case ARM_CPU_MODE_USR:
9794         case ARM_CPU_MODE_SYS:
9795             return 13;
9796         case ARM_CPU_MODE_HYP:
9797             return 15;
9798         case ARM_CPU_MODE_IRQ:
9799             return 17;
9800         case ARM_CPU_MODE_SVC:
9801             return 19;
9802         case ARM_CPU_MODE_ABT:
9803             return 21;
9804         case ARM_CPU_MODE_UND:
9805             return 23;
9806         case ARM_CPU_MODE_FIQ:
9807             return 29;
9808         default:
9809             g_assert_not_reached();
9810         }
9811     case 14:
9812         switch (mode) {
9813         case ARM_CPU_MODE_USR:
9814         case ARM_CPU_MODE_SYS:
9815         case ARM_CPU_MODE_HYP:
9816             return 14;
9817         case ARM_CPU_MODE_IRQ:
9818             return 16;
9819         case ARM_CPU_MODE_SVC:
9820             return 18;
9821         case ARM_CPU_MODE_ABT:
9822             return 20;
9823         case ARM_CPU_MODE_UND:
9824             return 22;
9825         case ARM_CPU_MODE_FIQ:
9826             return 30;
9827         default:
9828             g_assert_not_reached();
9829         }
9830     case 15:
9831         return 31;
9832     default:
9833         g_assert_not_reached();
9834     }
9835 }
9836 
9837 static uint32_t cpsr_read_for_spsr_elx(CPUARMState *env)
9838 {
9839     uint32_t ret = cpsr_read(env);
9840 
9841     /* Move DIT to the correct location for SPSR_ELx */
9842     if (ret & CPSR_DIT) {
9843         ret &= ~CPSR_DIT;
9844         ret |= PSTATE_DIT;
9845     }
9846     /* Merge PSTATE.SS into SPSR_ELx */
9847     ret |= env->pstate & PSTATE_SS;
9848 
9849     return ret;
9850 }
9851 
9852 /* Handle exception entry to a target EL which is using AArch64 */
9853 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
9854 {
9855     ARMCPU *cpu = ARM_CPU(cs);
9856     CPUARMState *env = &cpu->env;
9857     unsigned int new_el = env->exception.target_el;
9858     target_ulong addr = env->cp15.vbar_el[new_el];
9859     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
9860     unsigned int old_mode;
9861     unsigned int cur_el = arm_current_el(env);
9862     int rt;
9863 
9864     /*
9865      * Note that new_el can never be 0.  If cur_el is 0, then
9866      * el0_a64 is is_a64(), else el0_a64 is ignored.
9867      */
9868     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
9869 
9870     if (cur_el < new_el) {
9871         /* Entry vector offset depends on whether the implemented EL
9872          * immediately lower than the target level is using AArch32 or AArch64
9873          */
9874         bool is_aa64;
9875         uint64_t hcr;
9876 
9877         switch (new_el) {
9878         case 3:
9879             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
9880             break;
9881         case 2:
9882             hcr = arm_hcr_el2_eff(env);
9883             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
9884                 is_aa64 = (hcr & HCR_RW) != 0;
9885                 break;
9886             }
9887             /* fall through */
9888         case 1:
9889             is_aa64 = is_a64(env);
9890             break;
9891         default:
9892             g_assert_not_reached();
9893         }
9894 
9895         if (is_aa64) {
9896             addr += 0x400;
9897         } else {
9898             addr += 0x600;
9899         }
9900     } else if (pstate_read(env) & PSTATE_SP) {
9901         addr += 0x200;
9902     }
9903 
9904     switch (cs->exception_index) {
9905     case EXCP_PREFETCH_ABORT:
9906     case EXCP_DATA_ABORT:
9907         env->cp15.far_el[new_el] = env->exception.vaddress;
9908         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
9909                       env->cp15.far_el[new_el]);
9910         /* fall through */
9911     case EXCP_BKPT:
9912     case EXCP_UDEF:
9913     case EXCP_SWI:
9914     case EXCP_HVC:
9915     case EXCP_HYP_TRAP:
9916     case EXCP_SMC:
9917         switch (syn_get_ec(env->exception.syndrome)) {
9918         case EC_ADVSIMDFPACCESSTRAP:
9919             /*
9920              * QEMU internal FP/SIMD syndromes from AArch32 include the
9921              * TA and coproc fields which are only exposed if the exception
9922              * is taken to AArch32 Hyp mode. Mask them out to get a valid
9923              * AArch64 format syndrome.
9924              */
9925             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
9926             break;
9927         case EC_CP14RTTRAP:
9928         case EC_CP15RTTRAP:
9929         case EC_CP14DTTRAP:
9930             /*
9931              * For a trap on AArch32 MRC/MCR/LDC/STC the Rt field is currently
9932              * the raw register field from the insn; when taking this to
9933              * AArch64 we must convert it to the AArch64 view of the register
9934              * number. Notice that we read a 4-bit AArch32 register number and
9935              * write back a 5-bit AArch64 one.
9936              */
9937             rt = extract32(env->exception.syndrome, 5, 4);
9938             rt = aarch64_regnum(env, rt);
9939             env->exception.syndrome = deposit32(env->exception.syndrome,
9940                                                 5, 5, rt);
9941             break;
9942         case EC_CP15RRTTRAP:
9943         case EC_CP14RRTTRAP:
9944             /* Similarly for MRRC/MCRR traps for Rt and Rt2 fields */
9945             rt = extract32(env->exception.syndrome, 5, 4);
9946             rt = aarch64_regnum(env, rt);
9947             env->exception.syndrome = deposit32(env->exception.syndrome,
9948                                                 5, 5, rt);
9949             rt = extract32(env->exception.syndrome, 10, 4);
9950             rt = aarch64_regnum(env, rt);
9951             env->exception.syndrome = deposit32(env->exception.syndrome,
9952                                                 10, 5, rt);
9953             break;
9954         }
9955         env->cp15.esr_el[new_el] = env->exception.syndrome;
9956         break;
9957     case EXCP_IRQ:
9958     case EXCP_VIRQ:
9959         addr += 0x80;
9960         break;
9961     case EXCP_FIQ:
9962     case EXCP_VFIQ:
9963         addr += 0x100;
9964         break;
9965     default:
9966         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9967     }
9968 
9969     if (is_a64(env)) {
9970         old_mode = pstate_read(env);
9971         aarch64_save_sp(env, arm_current_el(env));
9972         env->elr_el[new_el] = env->pc;
9973     } else {
9974         old_mode = cpsr_read_for_spsr_elx(env);
9975         env->elr_el[new_el] = env->regs[15];
9976 
9977         aarch64_sync_32_to_64(env);
9978 
9979         env->condexec_bits = 0;
9980     }
9981     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
9982 
9983     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
9984                   env->elr_el[new_el]);
9985 
9986     if (cpu_isar_feature(aa64_pan, cpu)) {
9987         /* The value of PSTATE.PAN is normally preserved, except when ... */
9988         new_mode |= old_mode & PSTATE_PAN;
9989         switch (new_el) {
9990         case 2:
9991             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
9992             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
9993                 != (HCR_E2H | HCR_TGE)) {
9994                 break;
9995             }
9996             /* fall through */
9997         case 1:
9998             /* ... the target is EL1 ... */
9999             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
10000             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
10001                 new_mode |= PSTATE_PAN;
10002             }
10003             break;
10004         }
10005     }
10006     if (cpu_isar_feature(aa64_mte, cpu)) {
10007         new_mode |= PSTATE_TCO;
10008     }
10009 
10010     if (cpu_isar_feature(aa64_ssbs, cpu)) {
10011         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_64) {
10012             new_mode |= PSTATE_SSBS;
10013         } else {
10014             new_mode &= ~PSTATE_SSBS;
10015         }
10016     }
10017 
10018     pstate_write(env, PSTATE_DAIF | new_mode);
10019     env->aarch64 = 1;
10020     aarch64_restore_sp(env, new_el);
10021     helper_rebuild_hflags_a64(env, new_el);
10022 
10023     env->pc = addr;
10024 
10025     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10026                   new_el, env->pc, pstate_read(env));
10027 }
10028 
10029 /*
10030  * Do semihosting call and set the appropriate return value. All the
10031  * permission and validity checks have been done at translate time.
10032  *
10033  * We only see semihosting exceptions in TCG only as they are not
10034  * trapped to the hypervisor in KVM.
10035  */
10036 #ifdef CONFIG_TCG
10037 static void handle_semihosting(CPUState *cs)
10038 {
10039     ARMCPU *cpu = ARM_CPU(cs);
10040     CPUARMState *env = &cpu->env;
10041 
10042     if (is_a64(env)) {
10043         qemu_log_mask(CPU_LOG_INT,
10044                       "...handling as semihosting call 0x%" PRIx64 "\n",
10045                       env->xregs[0]);
10046         env->xregs[0] = do_common_semihosting(cs);
10047         env->pc += 4;
10048     } else {
10049         qemu_log_mask(CPU_LOG_INT,
10050                       "...handling as semihosting call 0x%x\n",
10051                       env->regs[0]);
10052         env->regs[0] = do_common_semihosting(cs);
10053         env->regs[15] += env->thumb ? 2 : 4;
10054     }
10055 }
10056 #endif
10057 
10058 /* Handle a CPU exception for A and R profile CPUs.
10059  * Do any appropriate logging, handle PSCI calls, and then hand off
10060  * to the AArch64-entry or AArch32-entry function depending on the
10061  * target exception level's register width.
10062  *
10063  * Note: this is used for both TCG (as the do_interrupt tcg op),
10064  *       and KVM to re-inject guest debug exceptions, and to
10065  *       inject a Synchronous-External-Abort.
10066  */
10067 void arm_cpu_do_interrupt(CPUState *cs)
10068 {
10069     ARMCPU *cpu = ARM_CPU(cs);
10070     CPUARMState *env = &cpu->env;
10071     unsigned int new_el = env->exception.target_el;
10072 
10073     assert(!arm_feature(env, ARM_FEATURE_M));
10074 
10075     arm_log_exception(cs->exception_index);
10076     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10077                   new_el);
10078     if (qemu_loglevel_mask(CPU_LOG_INT)
10079         && !excp_is_internal(cs->exception_index)) {
10080         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10081                       syn_get_ec(env->exception.syndrome),
10082                       env->exception.syndrome);
10083     }
10084 
10085     if (arm_is_psci_call(cpu, cs->exception_index)) {
10086         arm_handle_psci_call(cpu);
10087         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10088         return;
10089     }
10090 
10091     /*
10092      * Semihosting semantics depend on the register width of the code
10093      * that caused the exception, not the target exception level, so
10094      * must be handled here.
10095      */
10096 #ifdef CONFIG_TCG
10097     if (cs->exception_index == EXCP_SEMIHOST) {
10098         handle_semihosting(cs);
10099         return;
10100     }
10101 #endif
10102 
10103     /* Hooks may change global state so BQL should be held, also the
10104      * BQL needs to be held for any modification of
10105      * cs->interrupt_request.
10106      */
10107     g_assert(qemu_mutex_iothread_locked());
10108 
10109     arm_call_pre_el_change_hook(cpu);
10110 
10111     assert(!excp_is_internal(cs->exception_index));
10112     if (arm_el_is_aa64(env, new_el)) {
10113         arm_cpu_do_interrupt_aarch64(cs);
10114     } else {
10115         arm_cpu_do_interrupt_aarch32(cs);
10116     }
10117 
10118     arm_call_el_change_hook(cpu);
10119 
10120     if (!kvm_enabled()) {
10121         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10122     }
10123 }
10124 #endif /* !CONFIG_USER_ONLY */
10125 
10126 uint64_t arm_sctlr(CPUARMState *env, int el)
10127 {
10128     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
10129     if (el == 0) {
10130         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
10131         el = (mmu_idx == ARMMMUIdx_E20_0 || mmu_idx == ARMMMUIdx_SE20_0)
10132              ? 2 : 1;
10133     }
10134     return env->cp15.sctlr_el[el];
10135 }
10136 
10137 /* Return the SCTLR value which controls this address translation regime */
10138 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10139 {
10140     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10141 }
10142 
10143 #ifndef CONFIG_USER_ONLY
10144 
10145 /* Return true if the specified stage of address translation is disabled */
10146 static inline bool regime_translation_disabled(CPUARMState *env,
10147                                                ARMMMUIdx mmu_idx)
10148 {
10149     uint64_t hcr_el2;
10150 
10151     if (arm_feature(env, ARM_FEATURE_M)) {
10152         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10153                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10154         case R_V7M_MPU_CTRL_ENABLE_MASK:
10155             /* Enabled, but not for HardFault and NMI */
10156             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10157         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10158             /* Enabled for all cases */
10159             return false;
10160         case 0:
10161         default:
10162             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10163              * we warned about that in armv7m_nvic.c when the guest set it.
10164              */
10165             return true;
10166         }
10167     }
10168 
10169     hcr_el2 = arm_hcr_el2_eff(env);
10170 
10171     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10172         /* HCR.DC means HCR.VM behaves as 1 */
10173         return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10174     }
10175 
10176     if (hcr_el2 & HCR_TGE) {
10177         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10178         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10179             return true;
10180         }
10181     }
10182 
10183     if ((hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
10184         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10185         return true;
10186     }
10187 
10188     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10189 }
10190 
10191 static inline bool regime_translation_big_endian(CPUARMState *env,
10192                                                  ARMMMUIdx mmu_idx)
10193 {
10194     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10195 }
10196 
10197 /* Return the TTBR associated with this translation regime */
10198 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10199                                    int ttbrn)
10200 {
10201     if (mmu_idx == ARMMMUIdx_Stage2) {
10202         return env->cp15.vttbr_el2;
10203     }
10204     if (mmu_idx == ARMMMUIdx_Stage2_S) {
10205         return env->cp15.vsttbr_el2;
10206     }
10207     if (ttbrn == 0) {
10208         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10209     } else {
10210         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10211     }
10212 }
10213 
10214 #endif /* !CONFIG_USER_ONLY */
10215 
10216 /* Convert a possible stage1+2 MMU index into the appropriate
10217  * stage 1 MMU index
10218  */
10219 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10220 {
10221     switch (mmu_idx) {
10222     case ARMMMUIdx_SE10_0:
10223         return ARMMMUIdx_Stage1_SE0;
10224     case ARMMMUIdx_SE10_1:
10225         return ARMMMUIdx_Stage1_SE1;
10226     case ARMMMUIdx_SE10_1_PAN:
10227         return ARMMMUIdx_Stage1_SE1_PAN;
10228     case ARMMMUIdx_E10_0:
10229         return ARMMMUIdx_Stage1_E0;
10230     case ARMMMUIdx_E10_1:
10231         return ARMMMUIdx_Stage1_E1;
10232     case ARMMMUIdx_E10_1_PAN:
10233         return ARMMMUIdx_Stage1_E1_PAN;
10234     default:
10235         return mmu_idx;
10236     }
10237 }
10238 
10239 /* Return true if the translation regime is using LPAE format page tables */
10240 static inline bool regime_using_lpae_format(CPUARMState *env,
10241                                             ARMMMUIdx mmu_idx)
10242 {
10243     int el = regime_el(env, mmu_idx);
10244     if (el == 2 || arm_el_is_aa64(env, el)) {
10245         return true;
10246     }
10247     if (arm_feature(env, ARM_FEATURE_LPAE)
10248         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10249         return true;
10250     }
10251     return false;
10252 }
10253 
10254 /* Returns true if the stage 1 translation regime is using LPAE format page
10255  * tables. Used when raising alignment exceptions, whose FSR changes depending
10256  * on whether the long or short descriptor format is in use. */
10257 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10258 {
10259     mmu_idx = stage_1_mmu_idx(mmu_idx);
10260 
10261     return regime_using_lpae_format(env, mmu_idx);
10262 }
10263 
10264 #ifndef CONFIG_USER_ONLY
10265 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10266 {
10267     switch (mmu_idx) {
10268     case ARMMMUIdx_SE10_0:
10269     case ARMMMUIdx_E20_0:
10270     case ARMMMUIdx_SE20_0:
10271     case ARMMMUIdx_Stage1_E0:
10272     case ARMMMUIdx_Stage1_SE0:
10273     case ARMMMUIdx_MUser:
10274     case ARMMMUIdx_MSUser:
10275     case ARMMMUIdx_MUserNegPri:
10276     case ARMMMUIdx_MSUserNegPri:
10277         return true;
10278     default:
10279         return false;
10280     case ARMMMUIdx_E10_0:
10281     case ARMMMUIdx_E10_1:
10282     case ARMMMUIdx_E10_1_PAN:
10283         g_assert_not_reached();
10284     }
10285 }
10286 
10287 /* Translate section/page access permissions to page
10288  * R/W protection flags
10289  *
10290  * @env:         CPUARMState
10291  * @mmu_idx:     MMU index indicating required translation regime
10292  * @ap:          The 3-bit access permissions (AP[2:0])
10293  * @domain_prot: The 2-bit domain access permissions
10294  */
10295 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10296                                 int ap, int domain_prot)
10297 {
10298     bool is_user = regime_is_user(env, mmu_idx);
10299 
10300     if (domain_prot == 3) {
10301         return PAGE_READ | PAGE_WRITE;
10302     }
10303 
10304     switch (ap) {
10305     case 0:
10306         if (arm_feature(env, ARM_FEATURE_V7)) {
10307             return 0;
10308         }
10309         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10310         case SCTLR_S:
10311             return is_user ? 0 : PAGE_READ;
10312         case SCTLR_R:
10313             return PAGE_READ;
10314         default:
10315             return 0;
10316         }
10317     case 1:
10318         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10319     case 2:
10320         if (is_user) {
10321             return PAGE_READ;
10322         } else {
10323             return PAGE_READ | PAGE_WRITE;
10324         }
10325     case 3:
10326         return PAGE_READ | PAGE_WRITE;
10327     case 4: /* Reserved.  */
10328         return 0;
10329     case 5:
10330         return is_user ? 0 : PAGE_READ;
10331     case 6:
10332         return PAGE_READ;
10333     case 7:
10334         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10335             return 0;
10336         }
10337         return PAGE_READ;
10338     default:
10339         g_assert_not_reached();
10340     }
10341 }
10342 
10343 /* Translate section/page access permissions to page
10344  * R/W protection flags.
10345  *
10346  * @ap:      The 2-bit simple AP (AP[2:1])
10347  * @is_user: TRUE if accessing from PL0
10348  */
10349 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10350 {
10351     switch (ap) {
10352     case 0:
10353         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10354     case 1:
10355         return PAGE_READ | PAGE_WRITE;
10356     case 2:
10357         return is_user ? 0 : PAGE_READ;
10358     case 3:
10359         return PAGE_READ;
10360     default:
10361         g_assert_not_reached();
10362     }
10363 }
10364 
10365 static inline int
10366 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10367 {
10368     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10369 }
10370 
10371 /* Translate S2 section/page access permissions to protection flags
10372  *
10373  * @env:     CPUARMState
10374  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10375  * @xn:      XN (execute-never) bits
10376  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
10377  */
10378 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
10379 {
10380     int prot = 0;
10381 
10382     if (s2ap & 1) {
10383         prot |= PAGE_READ;
10384     }
10385     if (s2ap & 2) {
10386         prot |= PAGE_WRITE;
10387     }
10388 
10389     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
10390         switch (xn) {
10391         case 0:
10392             prot |= PAGE_EXEC;
10393             break;
10394         case 1:
10395             if (s1_is_el0) {
10396                 prot |= PAGE_EXEC;
10397             }
10398             break;
10399         case 2:
10400             break;
10401         case 3:
10402             if (!s1_is_el0) {
10403                 prot |= PAGE_EXEC;
10404             }
10405             break;
10406         default:
10407             g_assert_not_reached();
10408         }
10409     } else {
10410         if (!extract32(xn, 1, 1)) {
10411             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10412                 prot |= PAGE_EXEC;
10413             }
10414         }
10415     }
10416     return prot;
10417 }
10418 
10419 /* Translate section/page access permissions to protection flags
10420  *
10421  * @env:     CPUARMState
10422  * @mmu_idx: MMU index indicating required translation regime
10423  * @is_aa64: TRUE if AArch64
10424  * @ap:      The 2-bit simple AP (AP[2:1])
10425  * @ns:      NS (non-secure) bit
10426  * @xn:      XN (execute-never) bit
10427  * @pxn:     PXN (privileged execute-never) bit
10428  */
10429 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10430                       int ap, int ns, int xn, int pxn)
10431 {
10432     bool is_user = regime_is_user(env, mmu_idx);
10433     int prot_rw, user_rw;
10434     bool have_wxn;
10435     int wxn = 0;
10436 
10437     assert(mmu_idx != ARMMMUIdx_Stage2);
10438     assert(mmu_idx != ARMMMUIdx_Stage2_S);
10439 
10440     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10441     if (is_user) {
10442         prot_rw = user_rw;
10443     } else {
10444         if (user_rw && regime_is_pan(env, mmu_idx)) {
10445             /* PAN forbids data accesses but doesn't affect insn fetch */
10446             prot_rw = 0;
10447         } else {
10448             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10449         }
10450     }
10451 
10452     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10453         return prot_rw;
10454     }
10455 
10456     /* TODO have_wxn should be replaced with
10457      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10458      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10459      * compatible processors have EL2, which is required for [U]WXN.
10460      */
10461     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10462 
10463     if (have_wxn) {
10464         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10465     }
10466 
10467     if (is_aa64) {
10468         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10469             xn = pxn || (user_rw & PAGE_WRITE);
10470         }
10471     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10472         switch (regime_el(env, mmu_idx)) {
10473         case 1:
10474         case 3:
10475             if (is_user) {
10476                 xn = xn || !(user_rw & PAGE_READ);
10477             } else {
10478                 int uwxn = 0;
10479                 if (have_wxn) {
10480                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10481                 }
10482                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10483                      (uwxn && (user_rw & PAGE_WRITE));
10484             }
10485             break;
10486         case 2:
10487             break;
10488         }
10489     } else {
10490         xn = wxn = 0;
10491     }
10492 
10493     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10494         return prot_rw;
10495     }
10496     return prot_rw | PAGE_EXEC;
10497 }
10498 
10499 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10500                                      uint32_t *table, uint32_t address)
10501 {
10502     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10503     TCR *tcr = regime_tcr(env, mmu_idx);
10504 
10505     if (address & tcr->mask) {
10506         if (tcr->raw_tcr & TTBCR_PD1) {
10507             /* Translation table walk disabled for TTBR1 */
10508             return false;
10509         }
10510         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10511     } else {
10512         if (tcr->raw_tcr & TTBCR_PD0) {
10513             /* Translation table walk disabled for TTBR0 */
10514             return false;
10515         }
10516         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10517     }
10518     *table |= (address >> 18) & 0x3ffc;
10519     return true;
10520 }
10521 
10522 /* Translate a S1 pagetable walk through S2 if needed.  */
10523 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10524                                hwaddr addr, bool *is_secure,
10525                                ARMMMUFaultInfo *fi)
10526 {
10527     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10528         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10529         target_ulong s2size;
10530         hwaddr s2pa;
10531         int s2prot;
10532         int ret;
10533         ARMMMUIdx s2_mmu_idx = *is_secure ? ARMMMUIdx_Stage2_S
10534                                           : ARMMMUIdx_Stage2;
10535         ARMCacheAttrs cacheattrs = {};
10536         MemTxAttrs txattrs = {};
10537 
10538         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, s2_mmu_idx, false,
10539                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10540                                  &cacheattrs);
10541         if (ret) {
10542             assert(fi->type != ARMFault_None);
10543             fi->s2addr = addr;
10544             fi->stage2 = true;
10545             fi->s1ptw = true;
10546             fi->s1ns = !*is_secure;
10547             return ~0;
10548         }
10549         if ((arm_hcr_el2_eff(env) & HCR_PTW) &&
10550             (cacheattrs.attrs & 0xf0) == 0) {
10551             /*
10552              * PTW set and S1 walk touched S2 Device memory:
10553              * generate Permission fault.
10554              */
10555             fi->type = ARMFault_Permission;
10556             fi->s2addr = addr;
10557             fi->stage2 = true;
10558             fi->s1ptw = true;
10559             fi->s1ns = !*is_secure;
10560             return ~0;
10561         }
10562 
10563         if (arm_is_secure_below_el3(env)) {
10564             /* Check if page table walk is to secure or non-secure PA space. */
10565             if (*is_secure) {
10566                 *is_secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
10567             } else {
10568                 *is_secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
10569             }
10570         } else {
10571             assert(!*is_secure);
10572         }
10573 
10574         addr = s2pa;
10575     }
10576     return addr;
10577 }
10578 
10579 /* All loads done in the course of a page table walk go through here. */
10580 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10581                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10582 {
10583     ARMCPU *cpu = ARM_CPU(cs);
10584     CPUARMState *env = &cpu->env;
10585     MemTxAttrs attrs = {};
10586     MemTxResult result = MEMTX_OK;
10587     AddressSpace *as;
10588     uint32_t data;
10589 
10590     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10591     attrs.secure = is_secure;
10592     as = arm_addressspace(cs, attrs);
10593     if (fi->s1ptw) {
10594         return 0;
10595     }
10596     if (regime_translation_big_endian(env, mmu_idx)) {
10597         data = address_space_ldl_be(as, addr, attrs, &result);
10598     } else {
10599         data = address_space_ldl_le(as, addr, attrs, &result);
10600     }
10601     if (result == MEMTX_OK) {
10602         return data;
10603     }
10604     fi->type = ARMFault_SyncExternalOnWalk;
10605     fi->ea = arm_extabort_type(result);
10606     return 0;
10607 }
10608 
10609 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10610                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10611 {
10612     ARMCPU *cpu = ARM_CPU(cs);
10613     CPUARMState *env = &cpu->env;
10614     MemTxAttrs attrs = {};
10615     MemTxResult result = MEMTX_OK;
10616     AddressSpace *as;
10617     uint64_t data;
10618 
10619     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10620     attrs.secure = is_secure;
10621     as = arm_addressspace(cs, attrs);
10622     if (fi->s1ptw) {
10623         return 0;
10624     }
10625     if (regime_translation_big_endian(env, mmu_idx)) {
10626         data = address_space_ldq_be(as, addr, attrs, &result);
10627     } else {
10628         data = address_space_ldq_le(as, addr, attrs, &result);
10629     }
10630     if (result == MEMTX_OK) {
10631         return data;
10632     }
10633     fi->type = ARMFault_SyncExternalOnWalk;
10634     fi->ea = arm_extabort_type(result);
10635     return 0;
10636 }
10637 
10638 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10639                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10640                              hwaddr *phys_ptr, int *prot,
10641                              target_ulong *page_size,
10642                              ARMMMUFaultInfo *fi)
10643 {
10644     CPUState *cs = env_cpu(env);
10645     int level = 1;
10646     uint32_t table;
10647     uint32_t desc;
10648     int type;
10649     int ap;
10650     int domain = 0;
10651     int domain_prot;
10652     hwaddr phys_addr;
10653     uint32_t dacr;
10654 
10655     /* Pagetable walk.  */
10656     /* Lookup l1 descriptor.  */
10657     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10658         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10659         fi->type = ARMFault_Translation;
10660         goto do_fault;
10661     }
10662     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10663                        mmu_idx, fi);
10664     if (fi->type != ARMFault_None) {
10665         goto do_fault;
10666     }
10667     type = (desc & 3);
10668     domain = (desc >> 5) & 0x0f;
10669     if (regime_el(env, mmu_idx) == 1) {
10670         dacr = env->cp15.dacr_ns;
10671     } else {
10672         dacr = env->cp15.dacr_s;
10673     }
10674     domain_prot = (dacr >> (domain * 2)) & 3;
10675     if (type == 0) {
10676         /* Section translation fault.  */
10677         fi->type = ARMFault_Translation;
10678         goto do_fault;
10679     }
10680     if (type != 2) {
10681         level = 2;
10682     }
10683     if (domain_prot == 0 || domain_prot == 2) {
10684         fi->type = ARMFault_Domain;
10685         goto do_fault;
10686     }
10687     if (type == 2) {
10688         /* 1Mb section.  */
10689         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10690         ap = (desc >> 10) & 3;
10691         *page_size = 1024 * 1024;
10692     } else {
10693         /* Lookup l2 entry.  */
10694         if (type == 1) {
10695             /* Coarse pagetable.  */
10696             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10697         } else {
10698             /* Fine pagetable.  */
10699             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
10700         }
10701         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10702                            mmu_idx, fi);
10703         if (fi->type != ARMFault_None) {
10704             goto do_fault;
10705         }
10706         switch (desc & 3) {
10707         case 0: /* Page translation fault.  */
10708             fi->type = ARMFault_Translation;
10709             goto do_fault;
10710         case 1: /* 64k page.  */
10711             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10712             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
10713             *page_size = 0x10000;
10714             break;
10715         case 2: /* 4k page.  */
10716             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10717             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
10718             *page_size = 0x1000;
10719             break;
10720         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
10721             if (type == 1) {
10722                 /* ARMv6/XScale extended small page format */
10723                 if (arm_feature(env, ARM_FEATURE_XSCALE)
10724                     || arm_feature(env, ARM_FEATURE_V6)) {
10725                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10726                     *page_size = 0x1000;
10727                 } else {
10728                     /* UNPREDICTABLE in ARMv5; we choose to take a
10729                      * page translation fault.
10730                      */
10731                     fi->type = ARMFault_Translation;
10732                     goto do_fault;
10733                 }
10734             } else {
10735                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
10736                 *page_size = 0x400;
10737             }
10738             ap = (desc >> 4) & 3;
10739             break;
10740         default:
10741             /* Never happens, but compiler isn't smart enough to tell.  */
10742             abort();
10743         }
10744     }
10745     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10746     *prot |= *prot ? PAGE_EXEC : 0;
10747     if (!(*prot & (1 << access_type))) {
10748         /* Access permission fault.  */
10749         fi->type = ARMFault_Permission;
10750         goto do_fault;
10751     }
10752     *phys_ptr = phys_addr;
10753     return false;
10754 do_fault:
10755     fi->domain = domain;
10756     fi->level = level;
10757     return true;
10758 }
10759 
10760 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
10761                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10762                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
10763                              target_ulong *page_size, ARMMMUFaultInfo *fi)
10764 {
10765     CPUState *cs = env_cpu(env);
10766     ARMCPU *cpu = env_archcpu(env);
10767     int level = 1;
10768     uint32_t table;
10769     uint32_t desc;
10770     uint32_t xn;
10771     uint32_t pxn = 0;
10772     int type;
10773     int ap;
10774     int domain = 0;
10775     int domain_prot;
10776     hwaddr phys_addr;
10777     uint32_t dacr;
10778     bool ns;
10779 
10780     /* Pagetable walk.  */
10781     /* Lookup l1 descriptor.  */
10782     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10783         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10784         fi->type = ARMFault_Translation;
10785         goto do_fault;
10786     }
10787     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10788                        mmu_idx, fi);
10789     if (fi->type != ARMFault_None) {
10790         goto do_fault;
10791     }
10792     type = (desc & 3);
10793     if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
10794         /* Section translation fault, or attempt to use the encoding
10795          * which is Reserved on implementations without PXN.
10796          */
10797         fi->type = ARMFault_Translation;
10798         goto do_fault;
10799     }
10800     if ((type == 1) || !(desc & (1 << 18))) {
10801         /* Page or Section.  */
10802         domain = (desc >> 5) & 0x0f;
10803     }
10804     if (regime_el(env, mmu_idx) == 1) {
10805         dacr = env->cp15.dacr_ns;
10806     } else {
10807         dacr = env->cp15.dacr_s;
10808     }
10809     if (type == 1) {
10810         level = 2;
10811     }
10812     domain_prot = (dacr >> (domain * 2)) & 3;
10813     if (domain_prot == 0 || domain_prot == 2) {
10814         /* Section or Page domain fault */
10815         fi->type = ARMFault_Domain;
10816         goto do_fault;
10817     }
10818     if (type != 1) {
10819         if (desc & (1 << 18)) {
10820             /* Supersection.  */
10821             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
10822             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
10823             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
10824             *page_size = 0x1000000;
10825         } else {
10826             /* Section.  */
10827             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
10828             *page_size = 0x100000;
10829         }
10830         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
10831         xn = desc & (1 << 4);
10832         pxn = desc & 1;
10833         ns = extract32(desc, 19, 1);
10834     } else {
10835         if (cpu_isar_feature(aa32_pxn, cpu)) {
10836             pxn = (desc >> 2) & 1;
10837         }
10838         ns = extract32(desc, 3, 1);
10839         /* Lookup l2 entry.  */
10840         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
10841         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10842                            mmu_idx, fi);
10843         if (fi->type != ARMFault_None) {
10844             goto do_fault;
10845         }
10846         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
10847         switch (desc & 3) {
10848         case 0: /* Page translation fault.  */
10849             fi->type = ARMFault_Translation;
10850             goto do_fault;
10851         case 1: /* 64k page.  */
10852             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
10853             xn = desc & (1 << 15);
10854             *page_size = 0x10000;
10855             break;
10856         case 2: case 3: /* 4k page.  */
10857             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
10858             xn = desc & 1;
10859             *page_size = 0x1000;
10860             break;
10861         default:
10862             /* Never happens, but compiler isn't smart enough to tell.  */
10863             abort();
10864         }
10865     }
10866     if (domain_prot == 3) {
10867         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
10868     } else {
10869         if (pxn && !regime_is_user(env, mmu_idx)) {
10870             xn = 1;
10871         }
10872         if (xn && access_type == MMU_INST_FETCH) {
10873             fi->type = ARMFault_Permission;
10874             goto do_fault;
10875         }
10876 
10877         if (arm_feature(env, ARM_FEATURE_V6K) &&
10878                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
10879             /* The simplified model uses AP[0] as an access control bit.  */
10880             if ((ap & 1) == 0) {
10881                 /* Access flag fault.  */
10882                 fi->type = ARMFault_AccessFlag;
10883                 goto do_fault;
10884             }
10885             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
10886         } else {
10887             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
10888         }
10889         if (*prot && !xn) {
10890             *prot |= PAGE_EXEC;
10891         }
10892         if (!(*prot & (1 << access_type))) {
10893             /* Access permission fault.  */
10894             fi->type = ARMFault_Permission;
10895             goto do_fault;
10896         }
10897     }
10898     if (ns) {
10899         /* The NS bit will (as required by the architecture) have no effect if
10900          * the CPU doesn't support TZ or this is a non-secure translation
10901          * regime, because the attribute will already be non-secure.
10902          */
10903         attrs->secure = false;
10904     }
10905     *phys_ptr = phys_addr;
10906     return false;
10907 do_fault:
10908     fi->domain = domain;
10909     fi->level = level;
10910     return true;
10911 }
10912 
10913 /*
10914  * check_s2_mmu_setup
10915  * @cpu:        ARMCPU
10916  * @is_aa64:    True if the translation regime is in AArch64 state
10917  * @startlevel: Suggested starting level
10918  * @inputsize:  Bitsize of IPAs
10919  * @stride:     Page-table stride (See the ARM ARM)
10920  *
10921  * Returns true if the suggested S2 translation parameters are OK and
10922  * false otherwise.
10923  */
10924 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
10925                                int inputsize, int stride)
10926 {
10927     const int grainsize = stride + 3;
10928     int startsizecheck;
10929 
10930     /* Negative levels are never allowed.  */
10931     if (level < 0) {
10932         return false;
10933     }
10934 
10935     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
10936     if (startsizecheck < 1 || startsizecheck > stride + 4) {
10937         return false;
10938     }
10939 
10940     if (is_aa64) {
10941         CPUARMState *env = &cpu->env;
10942         unsigned int pamax = arm_pamax(cpu);
10943 
10944         switch (stride) {
10945         case 13: /* 64KB Pages.  */
10946             if (level == 0 || (level == 1 && pamax <= 42)) {
10947                 return false;
10948             }
10949             break;
10950         case 11: /* 16KB Pages.  */
10951             if (level == 0 || (level == 1 && pamax <= 40)) {
10952                 return false;
10953             }
10954             break;
10955         case 9: /* 4KB Pages.  */
10956             if (level == 0 && pamax <= 42) {
10957                 return false;
10958             }
10959             break;
10960         default:
10961             g_assert_not_reached();
10962         }
10963 
10964         /* Inputsize checks.  */
10965         if (inputsize > pamax &&
10966             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
10967             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
10968             return false;
10969         }
10970     } else {
10971         /* AArch32 only supports 4KB pages. Assert on that.  */
10972         assert(stride == 9);
10973 
10974         if (level == 0) {
10975             return false;
10976         }
10977     }
10978     return true;
10979 }
10980 
10981 /* Translate from the 4-bit stage 2 representation of
10982  * memory attributes (without cache-allocation hints) to
10983  * the 8-bit representation of the stage 1 MAIR registers
10984  * (which includes allocation hints).
10985  *
10986  * ref: shared/translation/attrs/S2AttrDecode()
10987  *      .../S2ConvertAttrsHints()
10988  */
10989 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
10990 {
10991     uint8_t hiattr = extract32(s2attrs, 2, 2);
10992     uint8_t loattr = extract32(s2attrs, 0, 2);
10993     uint8_t hihint = 0, lohint = 0;
10994 
10995     if (hiattr != 0) { /* normal memory */
10996         if (arm_hcr_el2_eff(env) & HCR_CD) { /* cache disabled */
10997             hiattr = loattr = 1; /* non-cacheable */
10998         } else {
10999             if (hiattr != 1) { /* Write-through or write-back */
11000                 hihint = 3; /* RW allocate */
11001             }
11002             if (loattr != 1) { /* Write-through or write-back */
11003                 lohint = 3; /* RW allocate */
11004             }
11005         }
11006     }
11007 
11008     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11009 }
11010 #endif /* !CONFIG_USER_ONLY */
11011 
11012 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
11013 {
11014     if (regime_has_2_ranges(mmu_idx)) {
11015         return extract64(tcr, 37, 2);
11016     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11017         return 0; /* VTCR_EL2 */
11018     } else {
11019         /* Replicate the single TBI bit so we always have 2 bits.  */
11020         return extract32(tcr, 20, 1) * 3;
11021     }
11022 }
11023 
11024 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
11025 {
11026     if (regime_has_2_ranges(mmu_idx)) {
11027         return extract64(tcr, 51, 2);
11028     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11029         return 0; /* VTCR_EL2 */
11030     } else {
11031         /* Replicate the single TBID bit so we always have 2 bits.  */
11032         return extract32(tcr, 29, 1) * 3;
11033     }
11034 }
11035 
11036 static int aa64_va_parameter_tcma(uint64_t tcr, ARMMMUIdx mmu_idx)
11037 {
11038     if (regime_has_2_ranges(mmu_idx)) {
11039         return extract64(tcr, 57, 2);
11040     } else {
11041         /* Replicate the single TCMA bit so we always have 2 bits.  */
11042         return extract32(tcr, 30, 1) * 3;
11043     }
11044 }
11045 
11046 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11047                                    ARMMMUIdx mmu_idx, bool data)
11048 {
11049     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11050     bool epd, hpd, using16k, using64k;
11051     int select, tsz, tbi, max_tsz;
11052 
11053     if (!regime_has_2_ranges(mmu_idx)) {
11054         select = 0;
11055         tsz = extract32(tcr, 0, 6);
11056         using64k = extract32(tcr, 14, 1);
11057         using16k = extract32(tcr, 15, 1);
11058         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11059             /* VTCR_EL2 */
11060             hpd = false;
11061         } else {
11062             hpd = extract32(tcr, 24, 1);
11063         }
11064         epd = false;
11065     } else {
11066         /*
11067          * Bit 55 is always between the two regions, and is canonical for
11068          * determining if address tagging is enabled.
11069          */
11070         select = extract64(va, 55, 1);
11071         if (!select) {
11072             tsz = extract32(tcr, 0, 6);
11073             epd = extract32(tcr, 7, 1);
11074             using64k = extract32(tcr, 14, 1);
11075             using16k = extract32(tcr, 15, 1);
11076             hpd = extract64(tcr, 41, 1);
11077         } else {
11078             int tg = extract32(tcr, 30, 2);
11079             using16k = tg == 1;
11080             using64k = tg == 3;
11081             tsz = extract32(tcr, 16, 6);
11082             epd = extract32(tcr, 23, 1);
11083             hpd = extract64(tcr, 42, 1);
11084         }
11085     }
11086 
11087     if (cpu_isar_feature(aa64_st, env_archcpu(env))) {
11088         max_tsz = 48 - using64k;
11089     } else {
11090         max_tsz = 39;
11091     }
11092 
11093     tsz = MIN(tsz, max_tsz);
11094     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
11095 
11096     /* Present TBI as a composite with TBID.  */
11097     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11098     if (!data) {
11099         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11100     }
11101     tbi = (tbi >> select) & 1;
11102 
11103     return (ARMVAParameters) {
11104         .tsz = tsz,
11105         .select = select,
11106         .tbi = tbi,
11107         .epd = epd,
11108         .hpd = hpd,
11109         .using16k = using16k,
11110         .using64k = using64k,
11111     };
11112 }
11113 
11114 #ifndef CONFIG_USER_ONLY
11115 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11116                                           ARMMMUIdx mmu_idx)
11117 {
11118     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11119     uint32_t el = regime_el(env, mmu_idx);
11120     int select, tsz;
11121     bool epd, hpd;
11122 
11123     assert(mmu_idx != ARMMMUIdx_Stage2_S);
11124 
11125     if (mmu_idx == ARMMMUIdx_Stage2) {
11126         /* VTCR */
11127         bool sext = extract32(tcr, 4, 1);
11128         bool sign = extract32(tcr, 3, 1);
11129 
11130         /*
11131          * If the sign-extend bit is not the same as t0sz[3], the result
11132          * is unpredictable. Flag this as a guest error.
11133          */
11134         if (sign != sext) {
11135             qemu_log_mask(LOG_GUEST_ERROR,
11136                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11137         }
11138         tsz = sextract32(tcr, 0, 4) + 8;
11139         select = 0;
11140         hpd = false;
11141         epd = false;
11142     } else if (el == 2) {
11143         /* HTCR */
11144         tsz = extract32(tcr, 0, 3);
11145         select = 0;
11146         hpd = extract64(tcr, 24, 1);
11147         epd = false;
11148     } else {
11149         int t0sz = extract32(tcr, 0, 3);
11150         int t1sz = extract32(tcr, 16, 3);
11151 
11152         if (t1sz == 0) {
11153             select = va > (0xffffffffu >> t0sz);
11154         } else {
11155             /* Note that we will detect errors later.  */
11156             select = va >= ~(0xffffffffu >> t1sz);
11157         }
11158         if (!select) {
11159             tsz = t0sz;
11160             epd = extract32(tcr, 7, 1);
11161             hpd = extract64(tcr, 41, 1);
11162         } else {
11163             tsz = t1sz;
11164             epd = extract32(tcr, 23, 1);
11165             hpd = extract64(tcr, 42, 1);
11166         }
11167         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11168         hpd &= extract32(tcr, 6, 1);
11169     }
11170 
11171     return (ARMVAParameters) {
11172         .tsz = tsz,
11173         .select = select,
11174         .epd = epd,
11175         .hpd = hpd,
11176     };
11177 }
11178 
11179 /**
11180  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
11181  *
11182  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11183  * prot and page_size may not be filled in, and the populated fsr value provides
11184  * information on why the translation aborted, in the format of a long-format
11185  * DFSR/IFSR fault register, with the following caveats:
11186  *  * the WnR bit is never set (the caller must do this).
11187  *
11188  * @env: CPUARMState
11189  * @address: virtual address to get physical address for
11190  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
11191  * @mmu_idx: MMU index indicating required translation regime
11192  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
11193  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
11194  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
11195  * @phys_ptr: set to the physical address corresponding to the virtual address
11196  * @attrs: set to the memory transaction attributes to use
11197  * @prot: set to the permissions for the page containing phys_ptr
11198  * @page_size_ptr: set to the size of the page containing phys_ptr
11199  * @fi: set to fault info if the translation fails
11200  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11201  */
11202 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
11203                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11204                                bool s1_is_el0,
11205                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11206                                target_ulong *page_size_ptr,
11207                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11208 {
11209     ARMCPU *cpu = env_archcpu(env);
11210     CPUState *cs = CPU(cpu);
11211     /* Read an LPAE long-descriptor translation table. */
11212     ARMFaultType fault_type = ARMFault_Translation;
11213     uint32_t level;
11214     ARMVAParameters param;
11215     uint64_t ttbr;
11216     hwaddr descaddr, indexmask, indexmask_grainsize;
11217     uint32_t tableattrs;
11218     target_ulong page_size;
11219     uint32_t attrs;
11220     int32_t stride;
11221     int addrsize, inputsize;
11222     TCR *tcr = regime_tcr(env, mmu_idx);
11223     int ap, ns, xn, pxn;
11224     uint32_t el = regime_el(env, mmu_idx);
11225     uint64_t descaddrmask;
11226     bool aarch64 = arm_el_is_aa64(env, el);
11227     bool guarded = false;
11228 
11229     /* TODO: This code does not support shareability levels. */
11230     if (aarch64) {
11231         param = aa64_va_parameters(env, address, mmu_idx,
11232                                    access_type != MMU_INST_FETCH);
11233         level = 0;
11234         addrsize = 64 - 8 * param.tbi;
11235         inputsize = 64 - param.tsz;
11236     } else {
11237         param = aa32_va_parameters(env, address, mmu_idx);
11238         level = 1;
11239         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
11240         inputsize = addrsize - param.tsz;
11241     }
11242 
11243     /*
11244      * We determined the region when collecting the parameters, but we
11245      * have not yet validated that the address is valid for the region.
11246      * Extract the top bits and verify that they all match select.
11247      *
11248      * For aa32, if inputsize == addrsize, then we have selected the
11249      * region by exclusion in aa32_va_parameters and there is no more
11250      * validation to do here.
11251      */
11252     if (inputsize < addrsize) {
11253         target_ulong top_bits = sextract64(address, inputsize,
11254                                            addrsize - inputsize);
11255         if (-top_bits != param.select) {
11256             /* The gap between the two regions is a Translation fault */
11257             fault_type = ARMFault_Translation;
11258             goto do_fault;
11259         }
11260     }
11261 
11262     if (param.using64k) {
11263         stride = 13;
11264     } else if (param.using16k) {
11265         stride = 11;
11266     } else {
11267         stride = 9;
11268     }
11269 
11270     /* Note that QEMU ignores shareability and cacheability attributes,
11271      * so we don't need to do anything with the SH, ORGN, IRGN fields
11272      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11273      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11274      * implement any ASID-like capability so we can ignore it (instead
11275      * we will always flush the TLB any time the ASID is changed).
11276      */
11277     ttbr = regime_ttbr(env, mmu_idx, param.select);
11278 
11279     /* Here we should have set up all the parameters for the translation:
11280      * inputsize, ttbr, epd, stride, tbi
11281      */
11282 
11283     if (param.epd) {
11284         /* Translation table walk disabled => Translation fault on TLB miss
11285          * Note: This is always 0 on 64-bit EL2 and EL3.
11286          */
11287         goto do_fault;
11288     }
11289 
11290     if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
11291         /* The starting level depends on the virtual address size (which can
11292          * be up to 48 bits) and the translation granule size. It indicates
11293          * the number of strides (stride bits at a time) needed to
11294          * consume the bits of the input address. In the pseudocode this is:
11295          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11296          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11297          * our 'stride + 3' and 'stride' is our 'stride'.
11298          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11299          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11300          * = 4 - (inputsize - 4) / stride;
11301          */
11302         level = 4 - (inputsize - 4) / stride;
11303     } else {
11304         /* For stage 2 translations the starting level is specified by the
11305          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11306          */
11307         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11308         uint32_t startlevel;
11309         bool ok;
11310 
11311         if (!aarch64 || stride == 9) {
11312             /* AArch32 or 4KB pages */
11313             startlevel = 2 - sl0;
11314 
11315             if (cpu_isar_feature(aa64_st, cpu)) {
11316                 startlevel &= 3;
11317             }
11318         } else {
11319             /* 16KB or 64KB pages */
11320             startlevel = 3 - sl0;
11321         }
11322 
11323         /* Check that the starting level is valid. */
11324         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11325                                 inputsize, stride);
11326         if (!ok) {
11327             fault_type = ARMFault_Translation;
11328             goto do_fault;
11329         }
11330         level = startlevel;
11331     }
11332 
11333     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
11334     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
11335 
11336     /* Now we can extract the actual base address from the TTBR */
11337     descaddr = extract64(ttbr, 0, 48);
11338     /*
11339      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
11340      * and also to mask out CnP (bit 0) which could validly be non-zero.
11341      */
11342     descaddr &= ~indexmask;
11343 
11344     /* The address field in the descriptor goes up to bit 39 for ARMv7
11345      * but up to bit 47 for ARMv8, but we use the descaddrmask
11346      * up to bit 39 for AArch32, because we don't need other bits in that case
11347      * to construct next descriptor address (anyway they should be all zeroes).
11348      */
11349     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
11350                    ~indexmask_grainsize;
11351 
11352     /* Secure accesses start with the page table in secure memory and
11353      * can be downgraded to non-secure at any step. Non-secure accesses
11354      * remain non-secure. We implement this by just ORing in the NSTable/NS
11355      * bits at each step.
11356      */
11357     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11358     for (;;) {
11359         uint64_t descriptor;
11360         bool nstable;
11361 
11362         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11363         descaddr &= ~7ULL;
11364         nstable = extract32(tableattrs, 4, 1);
11365         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11366         if (fi->type != ARMFault_None) {
11367             goto do_fault;
11368         }
11369 
11370         if (!(descriptor & 1) ||
11371             (!(descriptor & 2) && (level == 3))) {
11372             /* Invalid, or the Reserved level 3 encoding */
11373             goto do_fault;
11374         }
11375         descaddr = descriptor & descaddrmask;
11376 
11377         if ((descriptor & 2) && (level < 3)) {
11378             /* Table entry. The top five bits are attributes which may
11379              * propagate down through lower levels of the table (and
11380              * which are all arranged so that 0 means "no effect", so
11381              * we can gather them up by ORing in the bits at each level).
11382              */
11383             tableattrs |= extract64(descriptor, 59, 5);
11384             level++;
11385             indexmask = indexmask_grainsize;
11386             continue;
11387         }
11388         /* Block entry at level 1 or 2, or page entry at level 3.
11389          * These are basically the same thing, although the number
11390          * of bits we pull in from the vaddr varies.
11391          */
11392         page_size = (1ULL << ((stride * (4 - level)) + 3));
11393         descaddr |= (address & (page_size - 1));
11394         /* Extract attributes from the descriptor */
11395         attrs = extract64(descriptor, 2, 10)
11396             | (extract64(descriptor, 52, 12) << 10);
11397 
11398         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11399             /* Stage 2 table descriptors do not include any attribute fields */
11400             break;
11401         }
11402         /* Merge in attributes from table descriptors */
11403         attrs |= nstable << 3; /* NS */
11404         guarded = extract64(descriptor, 50, 1);  /* GP */
11405         if (param.hpd) {
11406             /* HPD disables all the table attributes except NSTable.  */
11407             break;
11408         }
11409         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11410         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11411          * means "force PL1 access only", which means forcing AP[1] to 0.
11412          */
11413         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11414         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11415         break;
11416     }
11417     /* Here descaddr is the final physical address, and attributes
11418      * are all in attrs.
11419      */
11420     fault_type = ARMFault_AccessFlag;
11421     if ((attrs & (1 << 8)) == 0) {
11422         /* Access flag */
11423         goto do_fault;
11424     }
11425 
11426     ap = extract32(attrs, 4, 2);
11427 
11428     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11429         ns = mmu_idx == ARMMMUIdx_Stage2;
11430         xn = extract32(attrs, 11, 2);
11431         *prot = get_S2prot(env, ap, xn, s1_is_el0);
11432     } else {
11433         ns = extract32(attrs, 3, 1);
11434         xn = extract32(attrs, 12, 1);
11435         pxn = extract32(attrs, 11, 1);
11436         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11437     }
11438 
11439     fault_type = ARMFault_Permission;
11440     if (!(*prot & (1 << access_type))) {
11441         goto do_fault;
11442     }
11443 
11444     if (ns) {
11445         /* The NS bit will (as required by the architecture) have no effect if
11446          * the CPU doesn't support TZ or this is a non-secure translation
11447          * regime, because the attribute will already be non-secure.
11448          */
11449         txattrs->secure = false;
11450     }
11451     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11452     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11453         arm_tlb_bti_gp(txattrs) = true;
11454     }
11455 
11456     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11457         cacheattrs->attrs = convert_stage2_attrs(env, extract32(attrs, 0, 4));
11458     } else {
11459         /* Index into MAIR registers for cache attributes */
11460         uint8_t attrindx = extract32(attrs, 0, 3);
11461         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11462         assert(attrindx <= 7);
11463         cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11464     }
11465     cacheattrs->shareability = extract32(attrs, 6, 2);
11466 
11467     *phys_ptr = descaddr;
11468     *page_size_ptr = page_size;
11469     return false;
11470 
11471 do_fault:
11472     fi->type = fault_type;
11473     fi->level = level;
11474     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11475     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2 ||
11476                                mmu_idx == ARMMMUIdx_Stage2_S);
11477     fi->s1ns = mmu_idx == ARMMMUIdx_Stage2;
11478     return true;
11479 }
11480 
11481 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11482                                                 ARMMMUIdx mmu_idx,
11483                                                 int32_t address, int *prot)
11484 {
11485     if (!arm_feature(env, ARM_FEATURE_M)) {
11486         *prot = PAGE_READ | PAGE_WRITE;
11487         switch (address) {
11488         case 0xF0000000 ... 0xFFFFFFFF:
11489             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11490                 /* hivecs execing is ok */
11491                 *prot |= PAGE_EXEC;
11492             }
11493             break;
11494         case 0x00000000 ... 0x7FFFFFFF:
11495             *prot |= PAGE_EXEC;
11496             break;
11497         }
11498     } else {
11499         /* Default system address map for M profile cores.
11500          * The architecture specifies which regions are execute-never;
11501          * at the MPU level no other checks are defined.
11502          */
11503         switch (address) {
11504         case 0x00000000 ... 0x1fffffff: /* ROM */
11505         case 0x20000000 ... 0x3fffffff: /* SRAM */
11506         case 0x60000000 ... 0x7fffffff: /* RAM */
11507         case 0x80000000 ... 0x9fffffff: /* RAM */
11508             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11509             break;
11510         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11511         case 0xa0000000 ... 0xbfffffff: /* Device */
11512         case 0xc0000000 ... 0xdfffffff: /* Device */
11513         case 0xe0000000 ... 0xffffffff: /* System */
11514             *prot = PAGE_READ | PAGE_WRITE;
11515             break;
11516         default:
11517             g_assert_not_reached();
11518         }
11519     }
11520 }
11521 
11522 static bool pmsav7_use_background_region(ARMCPU *cpu,
11523                                          ARMMMUIdx mmu_idx, bool is_user)
11524 {
11525     /* Return true if we should use the default memory map as a
11526      * "background" region if there are no hits against any MPU regions.
11527      */
11528     CPUARMState *env = &cpu->env;
11529 
11530     if (is_user) {
11531         return false;
11532     }
11533 
11534     if (arm_feature(env, ARM_FEATURE_M)) {
11535         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11536             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11537     } else {
11538         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11539     }
11540 }
11541 
11542 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11543 {
11544     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11545     return arm_feature(env, ARM_FEATURE_M) &&
11546         extract32(address, 20, 12) == 0xe00;
11547 }
11548 
11549 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11550 {
11551     /* True if address is in the M profile system region
11552      * 0xe0000000 - 0xffffffff
11553      */
11554     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11555 }
11556 
11557 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11558                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11559                                  hwaddr *phys_ptr, int *prot,
11560                                  target_ulong *page_size,
11561                                  ARMMMUFaultInfo *fi)
11562 {
11563     ARMCPU *cpu = env_archcpu(env);
11564     int n;
11565     bool is_user = regime_is_user(env, mmu_idx);
11566 
11567     *phys_ptr = address;
11568     *page_size = TARGET_PAGE_SIZE;
11569     *prot = 0;
11570 
11571     if (regime_translation_disabled(env, mmu_idx) ||
11572         m_is_ppb_region(env, address)) {
11573         /* MPU disabled or M profile PPB access: use default memory map.
11574          * The other case which uses the default memory map in the
11575          * v7M ARM ARM pseudocode is exception vector reads from the vector
11576          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11577          * which always does a direct read using address_space_ldl(), rather
11578          * than going via this function, so we don't need to check that here.
11579          */
11580         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11581     } else { /* MPU enabled */
11582         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11583             /* region search */
11584             uint32_t base = env->pmsav7.drbar[n];
11585             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11586             uint32_t rmask;
11587             bool srdis = false;
11588 
11589             if (!(env->pmsav7.drsr[n] & 0x1)) {
11590                 continue;
11591             }
11592 
11593             if (!rsize) {
11594                 qemu_log_mask(LOG_GUEST_ERROR,
11595                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11596                 continue;
11597             }
11598             rsize++;
11599             rmask = (1ull << rsize) - 1;
11600 
11601             if (base & rmask) {
11602                 qemu_log_mask(LOG_GUEST_ERROR,
11603                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11604                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11605                               n, base, rmask);
11606                 continue;
11607             }
11608 
11609             if (address < base || address > base + rmask) {
11610                 /*
11611                  * Address not in this region. We must check whether the
11612                  * region covers addresses in the same page as our address.
11613                  * In that case we must not report a size that covers the
11614                  * whole page for a subsequent hit against a different MPU
11615                  * region or the background region, because it would result in
11616                  * incorrect TLB hits for subsequent accesses to addresses that
11617                  * are in this MPU region.
11618                  */
11619                 if (ranges_overlap(base, rmask,
11620                                    address & TARGET_PAGE_MASK,
11621                                    TARGET_PAGE_SIZE)) {
11622                     *page_size = 1;
11623                 }
11624                 continue;
11625             }
11626 
11627             /* Region matched */
11628 
11629             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11630                 int i, snd;
11631                 uint32_t srdis_mask;
11632 
11633                 rsize -= 3; /* sub region size (power of 2) */
11634                 snd = ((address - base) >> rsize) & 0x7;
11635                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11636 
11637                 srdis_mask = srdis ? 0x3 : 0x0;
11638                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11639                     /* This will check in groups of 2, 4 and then 8, whether
11640                      * the subregion bits are consistent. rsize is incremented
11641                      * back up to give the region size, considering consistent
11642                      * adjacent subregions as one region. Stop testing if rsize
11643                      * is already big enough for an entire QEMU page.
11644                      */
11645                     int snd_rounded = snd & ~(i - 1);
11646                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11647                                                      snd_rounded + 8, i);
11648                     if (srdis_mask ^ srdis_multi) {
11649                         break;
11650                     }
11651                     srdis_mask = (srdis_mask << i) | srdis_mask;
11652                     rsize++;
11653                 }
11654             }
11655             if (srdis) {
11656                 continue;
11657             }
11658             if (rsize < TARGET_PAGE_BITS) {
11659                 *page_size = 1 << rsize;
11660             }
11661             break;
11662         }
11663 
11664         if (n == -1) { /* no hits */
11665             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11666                 /* background fault */
11667                 fi->type = ARMFault_Background;
11668                 return true;
11669             }
11670             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11671         } else { /* a MPU hit! */
11672             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
11673             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
11674 
11675             if (m_is_system_region(env, address)) {
11676                 /* System space is always execute never */
11677                 xn = 1;
11678             }
11679 
11680             if (is_user) { /* User mode AP bit decoding */
11681                 switch (ap) {
11682                 case 0:
11683                 case 1:
11684                 case 5:
11685                     break; /* no access */
11686                 case 3:
11687                     *prot |= PAGE_WRITE;
11688                     /* fall through */
11689                 case 2:
11690                 case 6:
11691                     *prot |= PAGE_READ | PAGE_EXEC;
11692                     break;
11693                 case 7:
11694                     /* for v7M, same as 6; for R profile a reserved value */
11695                     if (arm_feature(env, ARM_FEATURE_M)) {
11696                         *prot |= PAGE_READ | PAGE_EXEC;
11697                         break;
11698                     }
11699                     /* fall through */
11700                 default:
11701                     qemu_log_mask(LOG_GUEST_ERROR,
11702                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11703                                   PRIx32 "\n", n, ap);
11704                 }
11705             } else { /* Priv. mode AP bits decoding */
11706                 switch (ap) {
11707                 case 0:
11708                     break; /* no access */
11709                 case 1:
11710                 case 2:
11711                 case 3:
11712                     *prot |= PAGE_WRITE;
11713                     /* fall through */
11714                 case 5:
11715                 case 6:
11716                     *prot |= PAGE_READ | PAGE_EXEC;
11717                     break;
11718                 case 7:
11719                     /* for v7M, same as 6; for R profile a reserved value */
11720                     if (arm_feature(env, ARM_FEATURE_M)) {
11721                         *prot |= PAGE_READ | PAGE_EXEC;
11722                         break;
11723                     }
11724                     /* fall through */
11725                 default:
11726                     qemu_log_mask(LOG_GUEST_ERROR,
11727                                   "DRACR[%d]: Bad value for AP bits: 0x%"
11728                                   PRIx32 "\n", n, ap);
11729                 }
11730             }
11731 
11732             /* execute never */
11733             if (xn) {
11734                 *prot &= ~PAGE_EXEC;
11735             }
11736         }
11737     }
11738 
11739     fi->type = ARMFault_Permission;
11740     fi->level = 1;
11741     return !(*prot & (1 << access_type));
11742 }
11743 
11744 static bool v8m_is_sau_exempt(CPUARMState *env,
11745                               uint32_t address, MMUAccessType access_type)
11746 {
11747     /* The architecture specifies that certain address ranges are
11748      * exempt from v8M SAU/IDAU checks.
11749      */
11750     return
11751         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
11752         (address >= 0xe0000000 && address <= 0xe0002fff) ||
11753         (address >= 0xe000e000 && address <= 0xe000efff) ||
11754         (address >= 0xe002e000 && address <= 0xe002efff) ||
11755         (address >= 0xe0040000 && address <= 0xe0041fff) ||
11756         (address >= 0xe00ff000 && address <= 0xe00fffff);
11757 }
11758 
11759 void v8m_security_lookup(CPUARMState *env, uint32_t address,
11760                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
11761                                 V8M_SAttributes *sattrs)
11762 {
11763     /* Look up the security attributes for this address. Compare the
11764      * pseudocode SecurityCheck() function.
11765      * We assume the caller has zero-initialized *sattrs.
11766      */
11767     ARMCPU *cpu = env_archcpu(env);
11768     int r;
11769     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
11770     int idau_region = IREGION_NOTVALID;
11771     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11772     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11773 
11774     if (cpu->idau) {
11775         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
11776         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
11777 
11778         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
11779                    &idau_nsc);
11780     }
11781 
11782     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
11783         /* 0xf0000000..0xffffffff is always S for insn fetches */
11784         return;
11785     }
11786 
11787     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
11788         sattrs->ns = !regime_is_secure(env, mmu_idx);
11789         return;
11790     }
11791 
11792     if (idau_region != IREGION_NOTVALID) {
11793         sattrs->irvalid = true;
11794         sattrs->iregion = idau_region;
11795     }
11796 
11797     switch (env->sau.ctrl & 3) {
11798     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
11799         break;
11800     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
11801         sattrs->ns = true;
11802         break;
11803     default: /* SAU.ENABLE == 1 */
11804         for (r = 0; r < cpu->sau_sregion; r++) {
11805             if (env->sau.rlar[r] & 1) {
11806                 uint32_t base = env->sau.rbar[r] & ~0x1f;
11807                 uint32_t limit = env->sau.rlar[r] | 0x1f;
11808 
11809                 if (base <= address && limit >= address) {
11810                     if (base > addr_page_base || limit < addr_page_limit) {
11811                         sattrs->subpage = true;
11812                     }
11813                     if (sattrs->srvalid) {
11814                         /* If we hit in more than one region then we must report
11815                          * as Secure, not NS-Callable, with no valid region
11816                          * number info.
11817                          */
11818                         sattrs->ns = false;
11819                         sattrs->nsc = false;
11820                         sattrs->sregion = 0;
11821                         sattrs->srvalid = false;
11822                         break;
11823                     } else {
11824                         if (env->sau.rlar[r] & 2) {
11825                             sattrs->nsc = true;
11826                         } else {
11827                             sattrs->ns = true;
11828                         }
11829                         sattrs->srvalid = true;
11830                         sattrs->sregion = r;
11831                     }
11832                 } else {
11833                     /*
11834                      * Address not in this region. We must check whether the
11835                      * region covers addresses in the same page as our address.
11836                      * In that case we must not report a size that covers the
11837                      * whole page for a subsequent hit against a different MPU
11838                      * region or the background region, because it would result
11839                      * in incorrect TLB hits for subsequent accesses to
11840                      * addresses that are in this MPU region.
11841                      */
11842                     if (limit >= base &&
11843                         ranges_overlap(base, limit - base + 1,
11844                                        addr_page_base,
11845                                        TARGET_PAGE_SIZE)) {
11846                         sattrs->subpage = true;
11847                     }
11848                 }
11849             }
11850         }
11851         break;
11852     }
11853 
11854     /*
11855      * The IDAU will override the SAU lookup results if it specifies
11856      * higher security than the SAU does.
11857      */
11858     if (!idau_ns) {
11859         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
11860             sattrs->ns = false;
11861             sattrs->nsc = idau_nsc;
11862         }
11863     }
11864 }
11865 
11866 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
11867                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
11868                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
11869                               int *prot, bool *is_subpage,
11870                               ARMMMUFaultInfo *fi, uint32_t *mregion)
11871 {
11872     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
11873      * that a full phys-to-virt translation does).
11874      * mregion is (if not NULL) set to the region number which matched,
11875      * or -1 if no region number is returned (MPU off, address did not
11876      * hit a region, address hit in multiple regions).
11877      * We set is_subpage to true if the region hit doesn't cover the
11878      * entire TARGET_PAGE the address is within.
11879      */
11880     ARMCPU *cpu = env_archcpu(env);
11881     bool is_user = regime_is_user(env, mmu_idx);
11882     uint32_t secure = regime_is_secure(env, mmu_idx);
11883     int n;
11884     int matchregion = -1;
11885     bool hit = false;
11886     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
11887     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
11888 
11889     *is_subpage = false;
11890     *phys_ptr = address;
11891     *prot = 0;
11892     if (mregion) {
11893         *mregion = -1;
11894     }
11895 
11896     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
11897      * was an exception vector read from the vector table (which is always
11898      * done using the default system address map), because those accesses
11899      * are done in arm_v7m_load_vector(), which always does a direct
11900      * read using address_space_ldl(), rather than going via this function.
11901      */
11902     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
11903         hit = true;
11904     } else if (m_is_ppb_region(env, address)) {
11905         hit = true;
11906     } else {
11907         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11908             hit = true;
11909         }
11910 
11911         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11912             /* region search */
11913             /* Note that the base address is bits [31:5] from the register
11914              * with bits [4:0] all zeroes, but the limit address is bits
11915              * [31:5] from the register with bits [4:0] all ones.
11916              */
11917             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
11918             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
11919 
11920             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
11921                 /* Region disabled */
11922                 continue;
11923             }
11924 
11925             if (address < base || address > limit) {
11926                 /*
11927                  * Address not in this region. We must check whether the
11928                  * region covers addresses in the same page as our address.
11929                  * In that case we must not report a size that covers the
11930                  * whole page for a subsequent hit against a different MPU
11931                  * region or the background region, because it would result in
11932                  * incorrect TLB hits for subsequent accesses to addresses that
11933                  * are in this MPU region.
11934                  */
11935                 if (limit >= base &&
11936                     ranges_overlap(base, limit - base + 1,
11937                                    addr_page_base,
11938                                    TARGET_PAGE_SIZE)) {
11939                     *is_subpage = true;
11940                 }
11941                 continue;
11942             }
11943 
11944             if (base > addr_page_base || limit < addr_page_limit) {
11945                 *is_subpage = true;
11946             }
11947 
11948             if (matchregion != -1) {
11949                 /* Multiple regions match -- always a failure (unlike
11950                  * PMSAv7 where highest-numbered-region wins)
11951                  */
11952                 fi->type = ARMFault_Permission;
11953                 fi->level = 1;
11954                 return true;
11955             }
11956 
11957             matchregion = n;
11958             hit = true;
11959         }
11960     }
11961 
11962     if (!hit) {
11963         /* background fault */
11964         fi->type = ARMFault_Background;
11965         return true;
11966     }
11967 
11968     if (matchregion == -1) {
11969         /* hit using the background region */
11970         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11971     } else {
11972         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
11973         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
11974         bool pxn = false;
11975 
11976         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
11977             pxn = extract32(env->pmsav8.rlar[secure][matchregion], 4, 1);
11978         }
11979 
11980         if (m_is_system_region(env, address)) {
11981             /* System space is always execute never */
11982             xn = 1;
11983         }
11984 
11985         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
11986         if (*prot && !xn && !(pxn && !is_user)) {
11987             *prot |= PAGE_EXEC;
11988         }
11989         /* We don't need to look the attribute up in the MAIR0/MAIR1
11990          * registers because that only tells us about cacheability.
11991          */
11992         if (mregion) {
11993             *mregion = matchregion;
11994         }
11995     }
11996 
11997     fi->type = ARMFault_Permission;
11998     fi->level = 1;
11999     return !(*prot & (1 << access_type));
12000 }
12001 
12002 
12003 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12004                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12005                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12006                                  int *prot, target_ulong *page_size,
12007                                  ARMMMUFaultInfo *fi)
12008 {
12009     uint32_t secure = regime_is_secure(env, mmu_idx);
12010     V8M_SAttributes sattrs = {};
12011     bool ret;
12012     bool mpu_is_subpage;
12013 
12014     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12015         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12016         if (access_type == MMU_INST_FETCH) {
12017             /* Instruction fetches always use the MMU bank and the
12018              * transaction attribute determined by the fetch address,
12019              * regardless of CPU state. This is painful for QEMU
12020              * to handle, because it would mean we need to encode
12021              * into the mmu_idx not just the (user, negpri) information
12022              * for the current security state but also that for the
12023              * other security state, which would balloon the number
12024              * of mmu_idx values needed alarmingly.
12025              * Fortunately we can avoid this because it's not actually
12026              * possible to arbitrarily execute code from memory with
12027              * the wrong security attribute: it will always generate
12028              * an exception of some kind or another, apart from the
12029              * special case of an NS CPU executing an SG instruction
12030              * in S&NSC memory. So we always just fail the translation
12031              * here and sort things out in the exception handler
12032              * (including possibly emulating an SG instruction).
12033              */
12034             if (sattrs.ns != !secure) {
12035                 if (sattrs.nsc) {
12036                     fi->type = ARMFault_QEMU_NSCExec;
12037                 } else {
12038                     fi->type = ARMFault_QEMU_SFault;
12039                 }
12040                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12041                 *phys_ptr = address;
12042                 *prot = 0;
12043                 return true;
12044             }
12045         } else {
12046             /* For data accesses we always use the MMU bank indicated
12047              * by the current CPU state, but the security attributes
12048              * might downgrade a secure access to nonsecure.
12049              */
12050             if (sattrs.ns) {
12051                 txattrs->secure = false;
12052             } else if (!secure) {
12053                 /* NS access to S memory must fault.
12054                  * Architecturally we should first check whether the
12055                  * MPU information for this address indicates that we
12056                  * are doing an unaligned access to Device memory, which
12057                  * should generate a UsageFault instead. QEMU does not
12058                  * currently check for that kind of unaligned access though.
12059                  * If we added it we would need to do so as a special case
12060                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12061                  */
12062                 fi->type = ARMFault_QEMU_SFault;
12063                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12064                 *phys_ptr = address;
12065                 *prot = 0;
12066                 return true;
12067             }
12068         }
12069     }
12070 
12071     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12072                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12073     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12074     return ret;
12075 }
12076 
12077 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12078                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12079                                  hwaddr *phys_ptr, int *prot,
12080                                  ARMMMUFaultInfo *fi)
12081 {
12082     int n;
12083     uint32_t mask;
12084     uint32_t base;
12085     bool is_user = regime_is_user(env, mmu_idx);
12086 
12087     if (regime_translation_disabled(env, mmu_idx)) {
12088         /* MPU disabled.  */
12089         *phys_ptr = address;
12090         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12091         return false;
12092     }
12093 
12094     *phys_ptr = address;
12095     for (n = 7; n >= 0; n--) {
12096         base = env->cp15.c6_region[n];
12097         if ((base & 1) == 0) {
12098             continue;
12099         }
12100         mask = 1 << ((base >> 1) & 0x1f);
12101         /* Keep this shift separate from the above to avoid an
12102            (undefined) << 32.  */
12103         mask = (mask << 1) - 1;
12104         if (((base ^ address) & ~mask) == 0) {
12105             break;
12106         }
12107     }
12108     if (n < 0) {
12109         fi->type = ARMFault_Background;
12110         return true;
12111     }
12112 
12113     if (access_type == MMU_INST_FETCH) {
12114         mask = env->cp15.pmsav5_insn_ap;
12115     } else {
12116         mask = env->cp15.pmsav5_data_ap;
12117     }
12118     mask = (mask >> (n * 4)) & 0xf;
12119     switch (mask) {
12120     case 0:
12121         fi->type = ARMFault_Permission;
12122         fi->level = 1;
12123         return true;
12124     case 1:
12125         if (is_user) {
12126             fi->type = ARMFault_Permission;
12127             fi->level = 1;
12128             return true;
12129         }
12130         *prot = PAGE_READ | PAGE_WRITE;
12131         break;
12132     case 2:
12133         *prot = PAGE_READ;
12134         if (!is_user) {
12135             *prot |= PAGE_WRITE;
12136         }
12137         break;
12138     case 3:
12139         *prot = PAGE_READ | PAGE_WRITE;
12140         break;
12141     case 5:
12142         if (is_user) {
12143             fi->type = ARMFault_Permission;
12144             fi->level = 1;
12145             return true;
12146         }
12147         *prot = PAGE_READ;
12148         break;
12149     case 6:
12150         *prot = PAGE_READ;
12151         break;
12152     default:
12153         /* Bad permission.  */
12154         fi->type = ARMFault_Permission;
12155         fi->level = 1;
12156         return true;
12157     }
12158     *prot |= PAGE_EXEC;
12159     return false;
12160 }
12161 
12162 /* Combine either inner or outer cacheability attributes for normal
12163  * memory, according to table D4-42 and pseudocode procedure
12164  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12165  *
12166  * NB: only stage 1 includes allocation hints (RW bits), leading to
12167  * some asymmetry.
12168  */
12169 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12170 {
12171     if (s1 == 4 || s2 == 4) {
12172         /* non-cacheable has precedence */
12173         return 4;
12174     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12175         /* stage 1 write-through takes precedence */
12176         return s1;
12177     } else if (extract32(s2, 2, 2) == 2) {
12178         /* stage 2 write-through takes precedence, but the allocation hint
12179          * is still taken from stage 1
12180          */
12181         return (2 << 2) | extract32(s1, 0, 2);
12182     } else { /* write-back */
12183         return s1;
12184     }
12185 }
12186 
12187 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12188  * and CombineS1S2Desc()
12189  *
12190  * @s1:      Attributes from stage 1 walk
12191  * @s2:      Attributes from stage 2 walk
12192  */
12193 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
12194 {
12195     uint8_t s1lo, s2lo, s1hi, s2hi;
12196     ARMCacheAttrs ret;
12197     bool tagged = false;
12198 
12199     if (s1.attrs == 0xf0) {
12200         tagged = true;
12201         s1.attrs = 0xff;
12202     }
12203 
12204     s1lo = extract32(s1.attrs, 0, 4);
12205     s2lo = extract32(s2.attrs, 0, 4);
12206     s1hi = extract32(s1.attrs, 4, 4);
12207     s2hi = extract32(s2.attrs, 4, 4);
12208 
12209     /* Combine shareability attributes (table D4-43) */
12210     if (s1.shareability == 2 || s2.shareability == 2) {
12211         /* if either are outer-shareable, the result is outer-shareable */
12212         ret.shareability = 2;
12213     } else if (s1.shareability == 3 || s2.shareability == 3) {
12214         /* if either are inner-shareable, the result is inner-shareable */
12215         ret.shareability = 3;
12216     } else {
12217         /* both non-shareable */
12218         ret.shareability = 0;
12219     }
12220 
12221     /* Combine memory type and cacheability attributes */
12222     if (s1hi == 0 || s2hi == 0) {
12223         /* Device has precedence over normal */
12224         if (s1lo == 0 || s2lo == 0) {
12225             /* nGnRnE has precedence over anything */
12226             ret.attrs = 0;
12227         } else if (s1lo == 4 || s2lo == 4) {
12228             /* non-Reordering has precedence over Reordering */
12229             ret.attrs = 4;  /* nGnRE */
12230         } else if (s1lo == 8 || s2lo == 8) {
12231             /* non-Gathering has precedence over Gathering */
12232             ret.attrs = 8;  /* nGRE */
12233         } else {
12234             ret.attrs = 0xc; /* GRE */
12235         }
12236 
12237         /* Any location for which the resultant memory type is any
12238          * type of Device memory is always treated as Outer Shareable.
12239          */
12240         ret.shareability = 2;
12241     } else { /* Normal memory */
12242         /* Outer/inner cacheability combine independently */
12243         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12244                   | combine_cacheattr_nibble(s1lo, s2lo);
12245 
12246         if (ret.attrs == 0x44) {
12247             /* Any location for which the resultant memory type is Normal
12248              * Inner Non-cacheable, Outer Non-cacheable is always treated
12249              * as Outer Shareable.
12250              */
12251             ret.shareability = 2;
12252         }
12253     }
12254 
12255     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
12256     if (tagged && ret.attrs == 0xff) {
12257         ret.attrs = 0xf0;
12258     }
12259 
12260     return ret;
12261 }
12262 
12263 
12264 /* get_phys_addr - get the physical address for this virtual address
12265  *
12266  * Find the physical address corresponding to the given virtual address,
12267  * by doing a translation table walk on MMU based systems or using the
12268  * MPU state on MPU based systems.
12269  *
12270  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12271  * prot and page_size may not be filled in, and the populated fsr value provides
12272  * information on why the translation aborted, in the format of a
12273  * DFSR/IFSR fault register, with the following caveats:
12274  *  * we honour the short vs long DFSR format differences.
12275  *  * the WnR bit is never set (the caller must do this).
12276  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12277  *    value.
12278  *
12279  * @env: CPUARMState
12280  * @address: virtual address to get physical address for
12281  * @access_type: 0 for read, 1 for write, 2 for execute
12282  * @mmu_idx: MMU index indicating required translation regime
12283  * @phys_ptr: set to the physical address corresponding to the virtual address
12284  * @attrs: set to the memory transaction attributes to use
12285  * @prot: set to the permissions for the page containing phys_ptr
12286  * @page_size: set to the size of the page containing phys_ptr
12287  * @fi: set to fault info if the translation fails
12288  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12289  */
12290 bool get_phys_addr(CPUARMState *env, target_ulong address,
12291                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12292                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12293                    target_ulong *page_size,
12294                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12295 {
12296     ARMMMUIdx s1_mmu_idx = stage_1_mmu_idx(mmu_idx);
12297 
12298     if (mmu_idx != s1_mmu_idx) {
12299         /* Call ourselves recursively to do the stage 1 and then stage 2
12300          * translations if mmu_idx is a two-stage regime.
12301          */
12302         if (arm_feature(env, ARM_FEATURE_EL2)) {
12303             hwaddr ipa;
12304             int s2_prot;
12305             int ret;
12306             ARMCacheAttrs cacheattrs2 = {};
12307             ARMMMUIdx s2_mmu_idx;
12308             bool is_el0;
12309 
12310             ret = get_phys_addr(env, address, access_type, s1_mmu_idx, &ipa,
12311                                 attrs, prot, page_size, fi, cacheattrs);
12312 
12313             /* If S1 fails or S2 is disabled, return early.  */
12314             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
12315                 *phys_ptr = ipa;
12316                 return ret;
12317             }
12318 
12319             s2_mmu_idx = attrs->secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
12320             is_el0 = mmu_idx == ARMMMUIdx_E10_0 || mmu_idx == ARMMMUIdx_SE10_0;
12321 
12322             /* S1 is done. Now do S2 translation.  */
12323             ret = get_phys_addr_lpae(env, ipa, access_type, s2_mmu_idx, is_el0,
12324                                      phys_ptr, attrs, &s2_prot,
12325                                      page_size, fi, &cacheattrs2);
12326             fi->s2addr = ipa;
12327             /* Combine the S1 and S2 perms.  */
12328             *prot &= s2_prot;
12329 
12330             /* If S2 fails, return early.  */
12331             if (ret) {
12332                 return ret;
12333             }
12334 
12335             /* Combine the S1 and S2 cache attributes. */
12336             if (arm_hcr_el2_eff(env) & HCR_DC) {
12337                 /*
12338                  * HCR.DC forces the first stage attributes to
12339                  *  Normal Non-Shareable,
12340                  *  Inner Write-Back Read-Allocate Write-Allocate,
12341                  *  Outer Write-Back Read-Allocate Write-Allocate.
12342                  * Do not overwrite Tagged within attrs.
12343                  */
12344                 if (cacheattrs->attrs != 0xf0) {
12345                     cacheattrs->attrs = 0xff;
12346                 }
12347                 cacheattrs->shareability = 0;
12348             }
12349             *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12350 
12351             /* Check if IPA translates to secure or non-secure PA space. */
12352             if (arm_is_secure_below_el3(env)) {
12353                 if (attrs->secure) {
12354                     attrs->secure =
12355                         !(env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW));
12356                 } else {
12357                     attrs->secure =
12358                         !((env->cp15.vtcr_el2.raw_tcr & (VTCR_NSA | VTCR_NSW))
12359                         || (env->cp15.vstcr_el2.raw_tcr & VSTCR_SA));
12360                 }
12361             }
12362             return 0;
12363         } else {
12364             /*
12365              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12366              */
12367             mmu_idx = stage_1_mmu_idx(mmu_idx);
12368         }
12369     }
12370 
12371     /* The page table entries may downgrade secure to non-secure, but
12372      * cannot upgrade an non-secure translation regime's attributes
12373      * to secure.
12374      */
12375     attrs->secure = regime_is_secure(env, mmu_idx);
12376     attrs->user = regime_is_user(env, mmu_idx);
12377 
12378     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12379      * In v7 and earlier it affects all stage 1 translations.
12380      */
12381     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
12382         && !arm_feature(env, ARM_FEATURE_V8)) {
12383         if (regime_el(env, mmu_idx) == 3) {
12384             address += env->cp15.fcseidr_s;
12385         } else {
12386             address += env->cp15.fcseidr_ns;
12387         }
12388     }
12389 
12390     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12391         bool ret;
12392         *page_size = TARGET_PAGE_SIZE;
12393 
12394         if (arm_feature(env, ARM_FEATURE_V8)) {
12395             /* PMSAv8 */
12396             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12397                                        phys_ptr, attrs, prot, page_size, fi);
12398         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12399             /* PMSAv7 */
12400             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12401                                        phys_ptr, prot, page_size, fi);
12402         } else {
12403             /* Pre-v7 MPU */
12404             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12405                                        phys_ptr, prot, fi);
12406         }
12407         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12408                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12409                       access_type == MMU_DATA_LOAD ? "reading" :
12410                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12411                       (uint32_t)address, mmu_idx,
12412                       ret ? "Miss" : "Hit",
12413                       *prot & PAGE_READ ? 'r' : '-',
12414                       *prot & PAGE_WRITE ? 'w' : '-',
12415                       *prot & PAGE_EXEC ? 'x' : '-');
12416 
12417         return ret;
12418     }
12419 
12420     /* Definitely a real MMU, not an MPU */
12421 
12422     if (regime_translation_disabled(env, mmu_idx)) {
12423         uint64_t hcr;
12424         uint8_t memattr;
12425 
12426         /*
12427          * MMU disabled.  S1 addresses within aa64 translation regimes are
12428          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
12429          */
12430         if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
12431             int r_el = regime_el(env, mmu_idx);
12432             if (arm_el_is_aa64(env, r_el)) {
12433                 int pamax = arm_pamax(env_archcpu(env));
12434                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
12435                 int addrtop, tbi;
12436 
12437                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
12438                 if (access_type == MMU_INST_FETCH) {
12439                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
12440                 }
12441                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
12442                 addrtop = (tbi ? 55 : 63);
12443 
12444                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
12445                     fi->type = ARMFault_AddressSize;
12446                     fi->level = 0;
12447                     fi->stage2 = false;
12448                     return 1;
12449                 }
12450 
12451                 /*
12452                  * When TBI is disabled, we've just validated that all of the
12453                  * bits above PAMax are zero, so logically we only need to
12454                  * clear the top byte for TBI.  But it's clearer to follow
12455                  * the pseudocode set of addrdesc.paddress.
12456                  */
12457                 address = extract64(address, 0, 52);
12458             }
12459         }
12460         *phys_ptr = address;
12461         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12462         *page_size = TARGET_PAGE_SIZE;
12463 
12464         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
12465         hcr = arm_hcr_el2_eff(env);
12466         cacheattrs->shareability = 0;
12467         if (hcr & HCR_DC) {
12468             if (hcr & HCR_DCT) {
12469                 memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
12470             } else {
12471                 memattr = 0xff;  /* Normal, WB, RWA */
12472             }
12473         } else if (access_type == MMU_INST_FETCH) {
12474             if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
12475                 memattr = 0xee;  /* Normal, WT, RA, NT */
12476             } else {
12477                 memattr = 0x44;  /* Normal, NC, No */
12478             }
12479             cacheattrs->shareability = 2; /* outer sharable */
12480         } else {
12481             memattr = 0x00;      /* Device, nGnRnE */
12482         }
12483         cacheattrs->attrs = memattr;
12484         return 0;
12485     }
12486 
12487     if (regime_using_lpae_format(env, mmu_idx)) {
12488         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
12489                                   phys_ptr, attrs, prot, page_size,
12490                                   fi, cacheattrs);
12491     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12492         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12493                                 phys_ptr, attrs, prot, page_size, fi);
12494     } else {
12495         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12496                                     phys_ptr, prot, page_size, fi);
12497     }
12498 }
12499 
12500 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12501                                          MemTxAttrs *attrs)
12502 {
12503     ARMCPU *cpu = ARM_CPU(cs);
12504     CPUARMState *env = &cpu->env;
12505     hwaddr phys_addr;
12506     target_ulong page_size;
12507     int prot;
12508     bool ret;
12509     ARMMMUFaultInfo fi = {};
12510     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12511     ARMCacheAttrs cacheattrs = {};
12512 
12513     *attrs = (MemTxAttrs) {};
12514 
12515     ret = get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &phys_addr,
12516                         attrs, &prot, &page_size, &fi, &cacheattrs);
12517 
12518     if (ret) {
12519         return -1;
12520     }
12521     return phys_addr;
12522 }
12523 
12524 #endif
12525 
12526 /* Note that signed overflow is undefined in C.  The following routines are
12527    careful to use unsigned types where modulo arithmetic is required.
12528    Failure to do so _will_ break on newer gcc.  */
12529 
12530 /* Signed saturating arithmetic.  */
12531 
12532 /* Perform 16-bit signed saturating addition.  */
12533 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
12534 {
12535     uint16_t res;
12536 
12537     res = a + b;
12538     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
12539         if (a & 0x8000)
12540             res = 0x8000;
12541         else
12542             res = 0x7fff;
12543     }
12544     return res;
12545 }
12546 
12547 /* Perform 8-bit signed saturating addition.  */
12548 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
12549 {
12550     uint8_t res;
12551 
12552     res = a + b;
12553     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
12554         if (a & 0x80)
12555             res = 0x80;
12556         else
12557             res = 0x7f;
12558     }
12559     return res;
12560 }
12561 
12562 /* Perform 16-bit signed saturating subtraction.  */
12563 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
12564 {
12565     uint16_t res;
12566 
12567     res = a - b;
12568     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
12569         if (a & 0x8000)
12570             res = 0x8000;
12571         else
12572             res = 0x7fff;
12573     }
12574     return res;
12575 }
12576 
12577 /* Perform 8-bit signed saturating subtraction.  */
12578 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
12579 {
12580     uint8_t res;
12581 
12582     res = a - b;
12583     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
12584         if (a & 0x80)
12585             res = 0x80;
12586         else
12587             res = 0x7f;
12588     }
12589     return res;
12590 }
12591 
12592 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
12593 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
12594 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
12595 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
12596 #define PFX q
12597 
12598 #include "op_addsub.h"
12599 
12600 /* Unsigned saturating arithmetic.  */
12601 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
12602 {
12603     uint16_t res;
12604     res = a + b;
12605     if (res < a)
12606         res = 0xffff;
12607     return res;
12608 }
12609 
12610 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
12611 {
12612     if (a > b)
12613         return a - b;
12614     else
12615         return 0;
12616 }
12617 
12618 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
12619 {
12620     uint8_t res;
12621     res = a + b;
12622     if (res < a)
12623         res = 0xff;
12624     return res;
12625 }
12626 
12627 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
12628 {
12629     if (a > b)
12630         return a - b;
12631     else
12632         return 0;
12633 }
12634 
12635 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
12636 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
12637 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
12638 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
12639 #define PFX uq
12640 
12641 #include "op_addsub.h"
12642 
12643 /* Signed modulo arithmetic.  */
12644 #define SARITH16(a, b, n, op) do { \
12645     int32_t sum; \
12646     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
12647     RESULT(sum, n, 16); \
12648     if (sum >= 0) \
12649         ge |= 3 << (n * 2); \
12650     } while(0)
12651 
12652 #define SARITH8(a, b, n, op) do { \
12653     int32_t sum; \
12654     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
12655     RESULT(sum, n, 8); \
12656     if (sum >= 0) \
12657         ge |= 1 << n; \
12658     } while(0)
12659 
12660 
12661 #define ADD16(a, b, n) SARITH16(a, b, n, +)
12662 #define SUB16(a, b, n) SARITH16(a, b, n, -)
12663 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
12664 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
12665 #define PFX s
12666 #define ARITH_GE
12667 
12668 #include "op_addsub.h"
12669 
12670 /* Unsigned modulo arithmetic.  */
12671 #define ADD16(a, b, n) do { \
12672     uint32_t sum; \
12673     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
12674     RESULT(sum, n, 16); \
12675     if ((sum >> 16) == 1) \
12676         ge |= 3 << (n * 2); \
12677     } while(0)
12678 
12679 #define ADD8(a, b, n) do { \
12680     uint32_t sum; \
12681     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
12682     RESULT(sum, n, 8); \
12683     if ((sum >> 8) == 1) \
12684         ge |= 1 << n; \
12685     } while(0)
12686 
12687 #define SUB16(a, b, n) do { \
12688     uint32_t sum; \
12689     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
12690     RESULT(sum, n, 16); \
12691     if ((sum >> 16) == 0) \
12692         ge |= 3 << (n * 2); \
12693     } while(0)
12694 
12695 #define SUB8(a, b, n) do { \
12696     uint32_t sum; \
12697     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
12698     RESULT(sum, n, 8); \
12699     if ((sum >> 8) == 0) \
12700         ge |= 1 << n; \
12701     } while(0)
12702 
12703 #define PFX u
12704 #define ARITH_GE
12705 
12706 #include "op_addsub.h"
12707 
12708 /* Halved signed arithmetic.  */
12709 #define ADD16(a, b, n) \
12710   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
12711 #define SUB16(a, b, n) \
12712   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
12713 #define ADD8(a, b, n) \
12714   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
12715 #define SUB8(a, b, n) \
12716   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
12717 #define PFX sh
12718 
12719 #include "op_addsub.h"
12720 
12721 /* Halved unsigned arithmetic.  */
12722 #define ADD16(a, b, n) \
12723   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12724 #define SUB16(a, b, n) \
12725   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
12726 #define ADD8(a, b, n) \
12727   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12728 #define SUB8(a, b, n) \
12729   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
12730 #define PFX uh
12731 
12732 #include "op_addsub.h"
12733 
12734 static inline uint8_t do_usad(uint8_t a, uint8_t b)
12735 {
12736     if (a > b)
12737         return a - b;
12738     else
12739         return b - a;
12740 }
12741 
12742 /* Unsigned sum of absolute byte differences.  */
12743 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
12744 {
12745     uint32_t sum;
12746     sum = do_usad(a, b);
12747     sum += do_usad(a >> 8, b >> 8);
12748     sum += do_usad(a >> 16, b >> 16);
12749     sum += do_usad(a >> 24, b >> 24);
12750     return sum;
12751 }
12752 
12753 /* For ARMv6 SEL instruction.  */
12754 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
12755 {
12756     uint32_t mask;
12757 
12758     mask = 0;
12759     if (flags & 1)
12760         mask |= 0xff;
12761     if (flags & 2)
12762         mask |= 0xff00;
12763     if (flags & 4)
12764         mask |= 0xff0000;
12765     if (flags & 8)
12766         mask |= 0xff000000;
12767     return (a & mask) | (b & ~mask);
12768 }
12769 
12770 /* CRC helpers.
12771  * The upper bytes of val (above the number specified by 'bytes') must have
12772  * been zeroed out by the caller.
12773  */
12774 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
12775 {
12776     uint8_t buf[4];
12777 
12778     stl_le_p(buf, val);
12779 
12780     /* zlib crc32 converts the accumulator and output to one's complement.  */
12781     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
12782 }
12783 
12784 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
12785 {
12786     uint8_t buf[4];
12787 
12788     stl_le_p(buf, val);
12789 
12790     /* Linux crc32c converts the output to one's complement.  */
12791     return crc32c(acc, buf, bytes) ^ 0xffffffff;
12792 }
12793 
12794 /* Return the exception level to which FP-disabled exceptions should
12795  * be taken, or 0 if FP is enabled.
12796  */
12797 int fp_exception_el(CPUARMState *env, int cur_el)
12798 {
12799 #ifndef CONFIG_USER_ONLY
12800     /* CPACR and the CPTR registers don't exist before v6, so FP is
12801      * always accessible
12802      */
12803     if (!arm_feature(env, ARM_FEATURE_V6)) {
12804         return 0;
12805     }
12806 
12807     if (arm_feature(env, ARM_FEATURE_M)) {
12808         /* CPACR can cause a NOCP UsageFault taken to current security state */
12809         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
12810             return 1;
12811         }
12812 
12813         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
12814             if (!extract32(env->v7m.nsacr, 10, 1)) {
12815                 /* FP insns cause a NOCP UsageFault taken to Secure */
12816                 return 3;
12817             }
12818         }
12819 
12820         return 0;
12821     }
12822 
12823     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
12824      * 0, 2 : trap EL0 and EL1/PL1 accesses
12825      * 1    : trap only EL0 accesses
12826      * 3    : trap no accesses
12827      * This register is ignored if E2H+TGE are both set.
12828      */
12829     if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
12830         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
12831 
12832         switch (fpen) {
12833         case 0:
12834         case 2:
12835             if (cur_el == 0 || cur_el == 1) {
12836                 /* Trap to PL1, which might be EL1 or EL3 */
12837                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
12838                     return 3;
12839                 }
12840                 return 1;
12841             }
12842             if (cur_el == 3 && !is_a64(env)) {
12843                 /* Secure PL1 running at EL3 */
12844                 return 3;
12845             }
12846             break;
12847         case 1:
12848             if (cur_el == 0) {
12849                 return 1;
12850             }
12851             break;
12852         case 3:
12853             break;
12854         }
12855     }
12856 
12857     /*
12858      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
12859      * to control non-secure access to the FPU. It doesn't have any
12860      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
12861      */
12862     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
12863          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
12864         if (!extract32(env->cp15.nsacr, 10, 1)) {
12865             /* FP insns act as UNDEF */
12866             return cur_el == 2 ? 2 : 1;
12867         }
12868     }
12869 
12870     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
12871      * check because zero bits in the registers mean "don't trap".
12872      */
12873 
12874     /* CPTR_EL2 : present in v7VE or v8 */
12875     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
12876         && arm_is_el2_enabled(env)) {
12877         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
12878         return 2;
12879     }
12880 
12881     /* CPTR_EL3 : present in v8 */
12882     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
12883         /* Trap all FP ops to EL3 */
12884         return 3;
12885     }
12886 #endif
12887     return 0;
12888 }
12889 
12890 /* Return the exception level we're running at if this is our mmu_idx */
12891 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
12892 {
12893     if (mmu_idx & ARM_MMU_IDX_M) {
12894         return mmu_idx & ARM_MMU_IDX_M_PRIV;
12895     }
12896 
12897     switch (mmu_idx) {
12898     case ARMMMUIdx_E10_0:
12899     case ARMMMUIdx_E20_0:
12900     case ARMMMUIdx_SE10_0:
12901     case ARMMMUIdx_SE20_0:
12902         return 0;
12903     case ARMMMUIdx_E10_1:
12904     case ARMMMUIdx_E10_1_PAN:
12905     case ARMMMUIdx_SE10_1:
12906     case ARMMMUIdx_SE10_1_PAN:
12907         return 1;
12908     case ARMMMUIdx_E2:
12909     case ARMMMUIdx_E20_2:
12910     case ARMMMUIdx_E20_2_PAN:
12911     case ARMMMUIdx_SE2:
12912     case ARMMMUIdx_SE20_2:
12913     case ARMMMUIdx_SE20_2_PAN:
12914         return 2;
12915     case ARMMMUIdx_SE3:
12916         return 3;
12917     default:
12918         g_assert_not_reached();
12919     }
12920 }
12921 
12922 #ifndef CONFIG_TCG
12923 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
12924 {
12925     g_assert_not_reached();
12926 }
12927 #endif
12928 
12929 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
12930 {
12931     ARMMMUIdx idx;
12932     uint64_t hcr;
12933 
12934     if (arm_feature(env, ARM_FEATURE_M)) {
12935         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
12936     }
12937 
12938     /* See ARM pseudo-function ELIsInHost.  */
12939     switch (el) {
12940     case 0:
12941         hcr = arm_hcr_el2_eff(env);
12942         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
12943             idx = ARMMMUIdx_E20_0;
12944         } else {
12945             idx = ARMMMUIdx_E10_0;
12946         }
12947         break;
12948     case 1:
12949         if (env->pstate & PSTATE_PAN) {
12950             idx = ARMMMUIdx_E10_1_PAN;
12951         } else {
12952             idx = ARMMMUIdx_E10_1;
12953         }
12954         break;
12955     case 2:
12956         /* Note that TGE does not apply at EL2.  */
12957         if (arm_hcr_el2_eff(env) & HCR_E2H) {
12958             if (env->pstate & PSTATE_PAN) {
12959                 idx = ARMMMUIdx_E20_2_PAN;
12960             } else {
12961                 idx = ARMMMUIdx_E20_2;
12962             }
12963         } else {
12964             idx = ARMMMUIdx_E2;
12965         }
12966         break;
12967     case 3:
12968         return ARMMMUIdx_SE3;
12969     default:
12970         g_assert_not_reached();
12971     }
12972 
12973     if (arm_is_secure_below_el3(env)) {
12974         idx &= ~ARM_MMU_IDX_A_NS;
12975     }
12976 
12977     return idx;
12978 }
12979 
12980 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
12981 {
12982     return arm_mmu_idx_el(env, arm_current_el(env));
12983 }
12984 
12985 #ifndef CONFIG_USER_ONLY
12986 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
12987 {
12988     return stage_1_mmu_idx(arm_mmu_idx(env));
12989 }
12990 #endif
12991 
12992 static uint32_t rebuild_hflags_common(CPUARMState *env, int fp_el,
12993                                       ARMMMUIdx mmu_idx, uint32_t flags)
12994 {
12995     flags = FIELD_DP32(flags, TBFLAG_ANY, FPEXC_EL, fp_el);
12996     flags = FIELD_DP32(flags, TBFLAG_ANY, MMUIDX,
12997                        arm_to_core_mmu_idx(mmu_idx));
12998 
12999     if (arm_singlestep_active(env)) {
13000         flags = FIELD_DP32(flags, TBFLAG_ANY, SS_ACTIVE, 1);
13001     }
13002     return flags;
13003 }
13004 
13005 static uint32_t rebuild_hflags_common_32(CPUARMState *env, int fp_el,
13006                                          ARMMMUIdx mmu_idx, uint32_t flags)
13007 {
13008     bool sctlr_b = arm_sctlr_b(env);
13009 
13010     if (sctlr_b) {
13011         flags = FIELD_DP32(flags, TBFLAG_A32, SCTLR_B, 1);
13012     }
13013     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
13014         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
13015     }
13016     flags = FIELD_DP32(flags, TBFLAG_A32, NS, !access_secure_reg(env));
13017 
13018     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13019 }
13020 
13021 static uint32_t rebuild_hflags_m32(CPUARMState *env, int fp_el,
13022                                    ARMMMUIdx mmu_idx)
13023 {
13024     uint32_t flags = 0;
13025 
13026     if (arm_v7m_is_handler_mode(env)) {
13027         flags = FIELD_DP32(flags, TBFLAG_M32, HANDLER, 1);
13028     }
13029 
13030     /*
13031      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
13032      * is suppressing them because the requested execution priority
13033      * is less than 0.
13034      */
13035     if (arm_feature(env, ARM_FEATURE_V8) &&
13036         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
13037           (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13038         flags = FIELD_DP32(flags, TBFLAG_M32, STACKCHECK, 1);
13039     }
13040 
13041     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13042 }
13043 
13044 static uint32_t rebuild_hflags_aprofile(CPUARMState *env)
13045 {
13046     int flags = 0;
13047 
13048     flags = FIELD_DP32(flags, TBFLAG_ANY, DEBUG_TARGET_EL,
13049                        arm_debug_target_el(env));
13050     return flags;
13051 }
13052 
13053 static uint32_t rebuild_hflags_a32(CPUARMState *env, int fp_el,
13054                                    ARMMMUIdx mmu_idx)
13055 {
13056     uint32_t flags = rebuild_hflags_aprofile(env);
13057 
13058     if (arm_el_is_aa64(env, 1)) {
13059         flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
13060     }
13061 
13062     if (arm_current_el(env) < 2 && env->cp15.hstr_el2 &&
13063         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13064         flags = FIELD_DP32(flags, TBFLAG_A32, HSTR_ACTIVE, 1);
13065     }
13066 
13067     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13068 }
13069 
13070 static uint32_t rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
13071                                    ARMMMUIdx mmu_idx)
13072 {
13073     uint32_t flags = rebuild_hflags_aprofile(env);
13074     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13075     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
13076     uint64_t sctlr;
13077     int tbii, tbid;
13078 
13079     flags = FIELD_DP32(flags, TBFLAG_ANY, AARCH64_STATE, 1);
13080 
13081     /* Get control bits for tagged addresses.  */
13082     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
13083     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
13084 
13085     flags = FIELD_DP32(flags, TBFLAG_A64, TBII, tbii);
13086     flags = FIELD_DP32(flags, TBFLAG_A64, TBID, tbid);
13087 
13088     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
13089         int sve_el = sve_exception_el(env, el);
13090         uint32_t zcr_len;
13091 
13092         /*
13093          * If SVE is disabled, but FP is enabled,
13094          * then the effective len is 0.
13095          */
13096         if (sve_el != 0 && fp_el == 0) {
13097             zcr_len = 0;
13098         } else {
13099             zcr_len = sve_zcr_len_for_el(env, el);
13100         }
13101         flags = FIELD_DP32(flags, TBFLAG_A64, SVEEXC_EL, sve_el);
13102         flags = FIELD_DP32(flags, TBFLAG_A64, ZCR_LEN, zcr_len);
13103     }
13104 
13105     sctlr = regime_sctlr(env, stage1);
13106 
13107     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
13108         flags = FIELD_DP32(flags, TBFLAG_ANY, BE_DATA, 1);
13109     }
13110 
13111     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
13112         /*
13113          * In order to save space in flags, we record only whether
13114          * pauth is "inactive", meaning all insns are implemented as
13115          * a nop, or "active" when some action must be performed.
13116          * The decision of which action to take is left to a helper.
13117          */
13118         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13119             flags = FIELD_DP32(flags, TBFLAG_A64, PAUTH_ACTIVE, 1);
13120         }
13121     }
13122 
13123     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13124         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13125         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13126             flags = FIELD_DP32(flags, TBFLAG_A64, BT, 1);
13127         }
13128     }
13129 
13130     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
13131     if (!(env->pstate & PSTATE_UAO)) {
13132         switch (mmu_idx) {
13133         case ARMMMUIdx_E10_1:
13134         case ARMMMUIdx_E10_1_PAN:
13135         case ARMMMUIdx_SE10_1:
13136         case ARMMMUIdx_SE10_1_PAN:
13137             /* TODO: ARMv8.3-NV */
13138             flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
13139             break;
13140         case ARMMMUIdx_E20_2:
13141         case ARMMMUIdx_E20_2_PAN:
13142         case ARMMMUIdx_SE20_2:
13143         case ARMMMUIdx_SE20_2_PAN:
13144             /*
13145              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
13146              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
13147              */
13148             if (env->cp15.hcr_el2 & HCR_TGE) {
13149                 flags = FIELD_DP32(flags, TBFLAG_A64, UNPRIV, 1);
13150             }
13151             break;
13152         default:
13153             break;
13154         }
13155     }
13156 
13157     if (cpu_isar_feature(aa64_mte, env_archcpu(env))) {
13158         /*
13159          * Set MTE_ACTIVE if any access may be Checked, and leave clear
13160          * if all accesses must be Unchecked:
13161          * 1) If no TBI, then there are no tags in the address to check,
13162          * 2) If Tag Check Override, then all accesses are Unchecked,
13163          * 3) If Tag Check Fail == 0, then Checked access have no effect,
13164          * 4) If no Allocation Tag Access, then all accesses are Unchecked.
13165          */
13166         if (allocation_tag_access_enabled(env, el, sctlr)) {
13167             flags = FIELD_DP32(flags, TBFLAG_A64, ATA, 1);
13168             if (tbid
13169                 && !(env->pstate & PSTATE_TCO)
13170                 && (sctlr & (el == 0 ? SCTLR_TCF0 : SCTLR_TCF))) {
13171                 flags = FIELD_DP32(flags, TBFLAG_A64, MTE_ACTIVE, 1);
13172             }
13173         }
13174         /* And again for unprivileged accesses, if required.  */
13175         if (FIELD_EX32(flags, TBFLAG_A64, UNPRIV)
13176             && tbid
13177             && !(env->pstate & PSTATE_TCO)
13178             && (sctlr & SCTLR_TCF0)
13179             && allocation_tag_access_enabled(env, 0, sctlr)) {
13180             flags = FIELD_DP32(flags, TBFLAG_A64, MTE0_ACTIVE, 1);
13181         }
13182         /* Cache TCMA as well as TBI. */
13183         flags = FIELD_DP32(flags, TBFLAG_A64, TCMA,
13184                            aa64_va_parameter_tcma(tcr, mmu_idx));
13185     }
13186 
13187     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13188 }
13189 
13190 static uint32_t rebuild_hflags_internal(CPUARMState *env)
13191 {
13192     int el = arm_current_el(env);
13193     int fp_el = fp_exception_el(env, el);
13194     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13195 
13196     if (is_a64(env)) {
13197         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13198     } else if (arm_feature(env, ARM_FEATURE_M)) {
13199         return rebuild_hflags_m32(env, fp_el, mmu_idx);
13200     } else {
13201         return rebuild_hflags_a32(env, fp_el, mmu_idx);
13202     }
13203 }
13204 
13205 void arm_rebuild_hflags(CPUARMState *env)
13206 {
13207     env->hflags = rebuild_hflags_internal(env);
13208 }
13209 
13210 /*
13211  * If we have triggered a EL state change we can't rely on the
13212  * translator having passed it to us, we need to recompute.
13213  */
13214 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
13215 {
13216     int el = arm_current_el(env);
13217     int fp_el = fp_exception_el(env, el);
13218     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13219     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13220 }
13221 
13222 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
13223 {
13224     int fp_el = fp_exception_el(env, el);
13225     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13226 
13227     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13228 }
13229 
13230 /*
13231  * If we have triggered a EL state change we can't rely on the
13232  * translator having passed it to us, we need to recompute.
13233  */
13234 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
13235 {
13236     int el = arm_current_el(env);
13237     int fp_el = fp_exception_el(env, el);
13238     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13239     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13240 }
13241 
13242 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
13243 {
13244     int fp_el = fp_exception_el(env, el);
13245     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13246 
13247     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13248 }
13249 
13250 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
13251 {
13252     int fp_el = fp_exception_el(env, el);
13253     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13254 
13255     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13256 }
13257 
13258 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
13259 {
13260 #ifdef CONFIG_DEBUG_TCG
13261     uint32_t env_flags_current = env->hflags;
13262     uint32_t env_flags_rebuilt = rebuild_hflags_internal(env);
13263 
13264     if (unlikely(env_flags_current != env_flags_rebuilt)) {
13265         fprintf(stderr, "TCG hflags mismatch (current:0x%08x rebuilt:0x%08x)\n",
13266                 env_flags_current, env_flags_rebuilt);
13267         abort();
13268     }
13269 #endif
13270 }
13271 
13272 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13273                           target_ulong *cs_base, uint32_t *pflags)
13274 {
13275     uint32_t flags = env->hflags;
13276 
13277     *cs_base = 0;
13278     assert_hflags_rebuild_correctly(env);
13279 
13280     if (FIELD_EX32(flags, TBFLAG_ANY, AARCH64_STATE)) {
13281         *pc = env->pc;
13282         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13283             flags = FIELD_DP32(flags, TBFLAG_A64, BTYPE, env->btype);
13284         }
13285     } else {
13286         *pc = env->regs[15];
13287 
13288         if (arm_feature(env, ARM_FEATURE_M)) {
13289             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13290                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
13291                 != env->v7m.secure) {
13292                 flags = FIELD_DP32(flags, TBFLAG_M32, FPCCR_S_WRONG, 1);
13293             }
13294 
13295             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13296                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13297                  (env->v7m.secure &&
13298                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13299                 /*
13300                  * ASPEN is set, but FPCA/SFPA indicate that there is no
13301                  * active FP context; we must create a new FP context before
13302                  * executing any FP insn.
13303                  */
13304                 flags = FIELD_DP32(flags, TBFLAG_M32, NEW_FP_CTXT_NEEDED, 1);
13305             }
13306 
13307             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13308             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13309                 flags = FIELD_DP32(flags, TBFLAG_M32, LSPACT, 1);
13310             }
13311         } else {
13312             /*
13313              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
13314              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
13315              */
13316             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13317                 flags = FIELD_DP32(flags, TBFLAG_A32,
13318                                    XSCALE_CPAR, env->cp15.c15_cpar);
13319             } else {
13320                 flags = FIELD_DP32(flags, TBFLAG_A32, VECLEN,
13321                                    env->vfp.vec_len);
13322                 flags = FIELD_DP32(flags, TBFLAG_A32, VECSTRIDE,
13323                                    env->vfp.vec_stride);
13324             }
13325             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
13326                 flags = FIELD_DP32(flags, TBFLAG_A32, VFPEN, 1);
13327             }
13328         }
13329 
13330         flags = FIELD_DP32(flags, TBFLAG_AM32, THUMB, env->thumb);
13331         flags = FIELD_DP32(flags, TBFLAG_AM32, CONDEXEC, env->condexec_bits);
13332     }
13333 
13334     /*
13335      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13336      * states defined in the ARM ARM for software singlestep:
13337      *  SS_ACTIVE   PSTATE.SS   State
13338      *     0            x       Inactive (the TB flag for SS is always 0)
13339      *     1            0       Active-pending
13340      *     1            1       Active-not-pending
13341      * SS_ACTIVE is set in hflags; PSTATE_SS is computed every TB.
13342      */
13343     if (FIELD_EX32(flags, TBFLAG_ANY, SS_ACTIVE) &&
13344         (env->pstate & PSTATE_SS)) {
13345         flags = FIELD_DP32(flags, TBFLAG_ANY, PSTATE_SS, 1);
13346     }
13347 
13348     *pflags = flags;
13349 }
13350 
13351 #ifdef TARGET_AARCH64
13352 /*
13353  * The manual says that when SVE is enabled and VQ is widened the
13354  * implementation is allowed to zero the previously inaccessible
13355  * portion of the registers.  The corollary to that is that when
13356  * SVE is enabled and VQ is narrowed we are also allowed to zero
13357  * the now inaccessible portion of the registers.
13358  *
13359  * The intent of this is that no predicate bit beyond VQ is ever set.
13360  * Which means that some operations on predicate registers themselves
13361  * may operate on full uint64_t or even unrolled across the maximum
13362  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13363  * may well be cheaper than conditionals to restrict the operation
13364  * to the relevant portion of a uint16_t[16].
13365  */
13366 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13367 {
13368     int i, j;
13369     uint64_t pmask;
13370 
13371     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13372     assert(vq <= env_archcpu(env)->sve_max_vq);
13373 
13374     /* Zap the high bits of the zregs.  */
13375     for (i = 0; i < 32; i++) {
13376         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13377     }
13378 
13379     /* Zap the high bits of the pregs and ffr.  */
13380     pmask = 0;
13381     if (vq & 3) {
13382         pmask = ~(-1ULL << (16 * (vq & 3)));
13383     }
13384     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13385         for (i = 0; i < 17; ++i) {
13386             env->vfp.pregs[i].p[j] &= pmask;
13387         }
13388         pmask = 0;
13389     }
13390 }
13391 
13392 /*
13393  * Notice a change in SVE vector size when changing EL.
13394  */
13395 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13396                            int new_el, bool el0_a64)
13397 {
13398     ARMCPU *cpu = env_archcpu(env);
13399     int old_len, new_len;
13400     bool old_a64, new_a64;
13401 
13402     /* Nothing to do if no SVE.  */
13403     if (!cpu_isar_feature(aa64_sve, cpu)) {
13404         return;
13405     }
13406 
13407     /* Nothing to do if FP is disabled in either EL.  */
13408     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13409         return;
13410     }
13411 
13412     /*
13413      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13414      * at ELx, or not available because the EL is in AArch32 state, then
13415      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13416      * has an effective value of 0".
13417      *
13418      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13419      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13420      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13421      * we already have the correct register contents when encountering the
13422      * vq0->vq0 transition between EL0->EL1.
13423      */
13424     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13425     old_len = (old_a64 && !sve_exception_el(env, old_el)
13426                ? sve_zcr_len_for_el(env, old_el) : 0);
13427     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13428     new_len = (new_a64 && !sve_exception_el(env, new_el)
13429                ? sve_zcr_len_for_el(env, new_el) : 0);
13430 
13431     /* When changing vector length, clear inaccessible state.  */
13432     if (new_len < old_len) {
13433         aarch64_sve_narrow_vq(env, new_len + 1);
13434     }
13435 }
13436 #endif
13437