xref: /openbmc/qemu/target/arm/helper.c (revision 3cfafd31)
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 #define PMCR_NUM_COUNTERS 4 /* QEMU IMPDEF choice */
42 
43 #ifndef CONFIG_USER_ONLY
44 
45 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
46                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
47                                bool s1_is_el0,
48                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
49                                target_ulong *page_size_ptr,
50                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
51     __attribute__((nonnull));
52 #endif
53 
54 static void switch_mode(CPUARMState *env, int mode);
55 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx);
56 
57 static int vfp_gdb_get_reg(CPUARMState *env, GByteArray *buf, int reg)
58 {
59     ARMCPU *cpu = env_archcpu(env);
60     int nregs = cpu_isar_feature(aa32_simd_r32, cpu) ? 32 : 16;
61 
62     /* VFP data registers are always little-endian.  */
63     if (reg < nregs) {
64         return gdb_get_reg64(buf, *aa32_vfp_dreg(env, reg));
65     }
66     if (arm_feature(env, ARM_FEATURE_NEON)) {
67         /* Aliases for Q regs.  */
68         nregs += 16;
69         if (reg < nregs) {
70             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
71             return gdb_get_reg128(buf, q[0], q[1]);
72         }
73     }
74     switch (reg - nregs) {
75     case 0: return gdb_get_reg32(buf, env->vfp.xregs[ARM_VFP_FPSID]); break;
76     case 1: return gdb_get_reg32(buf, vfp_get_fpscr(env)); break;
77     case 2: return gdb_get_reg32(buf, env->vfp.xregs[ARM_VFP_FPEXC]); break;
78     }
79     return 0;
80 }
81 
82 static int vfp_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
83 {
84     ARMCPU *cpu = env_archcpu(env);
85     int nregs = cpu_isar_feature(aa32_simd_r32, cpu) ? 32 : 16;
86 
87     if (reg < nregs) {
88         *aa32_vfp_dreg(env, reg) = ldq_le_p(buf);
89         return 8;
90     }
91     if (arm_feature(env, ARM_FEATURE_NEON)) {
92         nregs += 16;
93         if (reg < nregs) {
94             uint64_t *q = aa32_vfp_qreg(env, reg - 32);
95             q[0] = ldq_le_p(buf);
96             q[1] = ldq_le_p(buf + 8);
97             return 16;
98         }
99     }
100     switch (reg - nregs) {
101     case 0: env->vfp.xregs[ARM_VFP_FPSID] = ldl_p(buf); return 4;
102     case 1: vfp_set_fpscr(env, ldl_p(buf)); return 4;
103     case 2: env->vfp.xregs[ARM_VFP_FPEXC] = ldl_p(buf) & (1 << 30); return 4;
104     }
105     return 0;
106 }
107 
108 static int aarch64_fpu_gdb_get_reg(CPUARMState *env, GByteArray *buf, int reg)
109 {
110     switch (reg) {
111     case 0 ... 31:
112     {
113         /* 128 bit FP register - quads are in LE order */
114         uint64_t *q = aa64_vfp_qreg(env, reg);
115         return gdb_get_reg128(buf, q[1], q[0]);
116     }
117     case 32:
118         /* FPSR */
119         return gdb_get_reg32(buf, vfp_get_fpsr(env));
120     case 33:
121         /* FPCR */
122         return gdb_get_reg32(buf,vfp_get_fpcr(env));
123     default:
124         return 0;
125     }
126 }
127 
128 static int aarch64_fpu_gdb_set_reg(CPUARMState *env, uint8_t *buf, int reg)
129 {
130     switch (reg) {
131     case 0 ... 31:
132         /* 128 bit FP register */
133         {
134             uint64_t *q = aa64_vfp_qreg(env, reg);
135             q[0] = ldq_le_p(buf);
136             q[1] = ldq_le_p(buf + 8);
137             return 16;
138         }
139     case 32:
140         /* FPSR */
141         vfp_set_fpsr(env, ldl_p(buf));
142         return 4;
143     case 33:
144         /* FPCR */
145         vfp_set_fpcr(env, ldl_p(buf));
146         return 4;
147     default:
148         return 0;
149     }
150 }
151 
152 static uint64_t raw_read(CPUARMState *env, const ARMCPRegInfo *ri)
153 {
154     assert(ri->fieldoffset);
155     if (cpreg_field_is_64bit(ri)) {
156         return CPREG_FIELD64(env, ri);
157     } else {
158         return CPREG_FIELD32(env, ri);
159     }
160 }
161 
162 static void raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
163                       uint64_t value)
164 {
165     assert(ri->fieldoffset);
166     if (cpreg_field_is_64bit(ri)) {
167         CPREG_FIELD64(env, ri) = value;
168     } else {
169         CPREG_FIELD32(env, ri) = value;
170     }
171 }
172 
173 static void *raw_ptr(CPUARMState *env, const ARMCPRegInfo *ri)
174 {
175     return (char *)env + ri->fieldoffset;
176 }
177 
178 uint64_t read_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri)
179 {
180     /* Raw read of a coprocessor register (as needed for migration, etc). */
181     if (ri->type & ARM_CP_CONST) {
182         return ri->resetvalue;
183     } else if (ri->raw_readfn) {
184         return ri->raw_readfn(env, ri);
185     } else if (ri->readfn) {
186         return ri->readfn(env, ri);
187     } else {
188         return raw_read(env, ri);
189     }
190 }
191 
192 static void write_raw_cp_reg(CPUARMState *env, const ARMCPRegInfo *ri,
193                              uint64_t v)
194 {
195     /* Raw write of a coprocessor register (as needed for migration, etc).
196      * Note that constant registers are treated as write-ignored; the
197      * caller should check for success by whether a readback gives the
198      * value written.
199      */
200     if (ri->type & ARM_CP_CONST) {
201         return;
202     } else if (ri->raw_writefn) {
203         ri->raw_writefn(env, ri, v);
204     } else if (ri->writefn) {
205         ri->writefn(env, ri, v);
206     } else {
207         raw_write(env, ri, v);
208     }
209 }
210 
211 /**
212  * arm_get/set_gdb_*: get/set a gdb register
213  * @env: the CPU state
214  * @buf: a buffer to copy to/from
215  * @reg: register number (offset from start of group)
216  *
217  * We return the number of bytes copied
218  */
219 
220 static int arm_gdb_get_sysreg(CPUARMState *env, GByteArray *buf, int reg)
221 {
222     ARMCPU *cpu = env_archcpu(env);
223     const ARMCPRegInfo *ri;
224     uint32_t key;
225 
226     key = cpu->dyn_sysreg_xml.data.cpregs.keys[reg];
227     ri = get_arm_cp_reginfo(cpu->cp_regs, key);
228     if (ri) {
229         if (cpreg_field_is_64bit(ri)) {
230             return gdb_get_reg64(buf, (uint64_t)read_raw_cp_reg(env, ri));
231         } else {
232             return gdb_get_reg32(buf, (uint32_t)read_raw_cp_reg(env, ri));
233         }
234     }
235     return 0;
236 }
237 
238 static int arm_gdb_set_sysreg(CPUARMState *env, uint8_t *buf, int reg)
239 {
240     return 0;
241 }
242 
243 #ifdef TARGET_AARCH64
244 static int arm_gdb_get_svereg(CPUARMState *env, GByteArray *buf, int reg)
245 {
246     ARMCPU *cpu = env_archcpu(env);
247 
248     switch (reg) {
249     /* The first 32 registers are the zregs */
250     case 0 ... 31:
251     {
252         int vq, len = 0;
253         for (vq = 0; vq < cpu->sve_max_vq; vq++) {
254             len += gdb_get_reg128(buf,
255                                   env->vfp.zregs[reg].d[vq * 2 + 1],
256                                   env->vfp.zregs[reg].d[vq * 2]);
257         }
258         return len;
259     }
260     case 32:
261         return gdb_get_reg32(buf, vfp_get_fpsr(env));
262     case 33:
263         return gdb_get_reg32(buf, vfp_get_fpcr(env));
264     /* then 16 predicates and the ffr */
265     case 34 ... 50:
266     {
267         int preg = reg - 34;
268         int vq, len = 0;
269         for (vq = 0; vq < cpu->sve_max_vq; vq = vq + 4) {
270             len += gdb_get_reg64(buf, env->vfp.pregs[preg].p[vq / 4]);
271         }
272         return len;
273     }
274     case 51:
275     {
276         /*
277          * We report in Vector Granules (VG) which is 64bit in a Z reg
278          * while the ZCR works in Vector Quads (VQ) which is 128bit chunks.
279          */
280         int vq = sve_zcr_len_for_el(env, arm_current_el(env)) + 1;
281         return gdb_get_reg64(buf, vq * 2);
282     }
283     default:
284         /* gdbstub asked for something out our range */
285         qemu_log_mask(LOG_UNIMP, "%s: out of range register %d", __func__, reg);
286         break;
287     }
288 
289     return 0;
290 }
291 
292 static int arm_gdb_set_svereg(CPUARMState *env, uint8_t *buf, int reg)
293 {
294     ARMCPU *cpu = env_archcpu(env);
295 
296     /* The first 32 registers are the zregs */
297     switch (reg) {
298     /* The first 32 registers are the zregs */
299     case 0 ... 31:
300     {
301         int vq, len = 0;
302         uint64_t *p = (uint64_t *) buf;
303         for (vq = 0; vq < cpu->sve_max_vq; vq++) {
304             env->vfp.zregs[reg].d[vq * 2 + 1] = *p++;
305             env->vfp.zregs[reg].d[vq * 2] = *p++;
306             len += 16;
307         }
308         return len;
309     }
310     case 32:
311         vfp_set_fpsr(env, *(uint32_t *)buf);
312         return 4;
313     case 33:
314         vfp_set_fpcr(env, *(uint32_t *)buf);
315         return 4;
316     case 34 ... 50:
317     {
318         int preg = reg - 34;
319         int vq, len = 0;
320         uint64_t *p = (uint64_t *) buf;
321         for (vq = 0; vq < cpu->sve_max_vq; vq = vq + 4) {
322             env->vfp.pregs[preg].p[vq / 4] = *p++;
323             len += 8;
324         }
325         return len;
326     }
327     case 51:
328         /* cannot set vg via gdbstub */
329         return 0;
330     default:
331         /* gdbstub asked for something out our range */
332         break;
333     }
334 
335     return 0;
336 }
337 #endif /* TARGET_AARCH64 */
338 
339 static bool raw_accessors_invalid(const ARMCPRegInfo *ri)
340 {
341    /* Return true if the regdef would cause an assertion if you called
342     * read_raw_cp_reg() or write_raw_cp_reg() on it (ie if it is a
343     * program bug for it not to have the NO_RAW flag).
344     * NB that returning false here doesn't necessarily mean that calling
345     * read/write_raw_cp_reg() is safe, because we can't distinguish "has
346     * read/write access functions which are safe for raw use" from "has
347     * read/write access functions which have side effects but has forgotten
348     * to provide raw access functions".
349     * The tests here line up with the conditions in read/write_raw_cp_reg()
350     * and assertions in raw_read()/raw_write().
351     */
352     if ((ri->type & ARM_CP_CONST) ||
353         ri->fieldoffset ||
354         ((ri->raw_writefn || ri->writefn) && (ri->raw_readfn || ri->readfn))) {
355         return false;
356     }
357     return true;
358 }
359 
360 bool write_cpustate_to_list(ARMCPU *cpu, bool kvm_sync)
361 {
362     /* Write the coprocessor state from cpu->env to the (index,value) list. */
363     int i;
364     bool ok = true;
365 
366     for (i = 0; i < cpu->cpreg_array_len; i++) {
367         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
368         const ARMCPRegInfo *ri;
369         uint64_t newval;
370 
371         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
372         if (!ri) {
373             ok = false;
374             continue;
375         }
376         if (ri->type & ARM_CP_NO_RAW) {
377             continue;
378         }
379 
380         newval = read_raw_cp_reg(&cpu->env, ri);
381         if (kvm_sync) {
382             /*
383              * Only sync if the previous list->cpustate sync succeeded.
384              * Rather than tracking the success/failure state for every
385              * item in the list, we just recheck "does the raw write we must
386              * have made in write_list_to_cpustate() read back OK" here.
387              */
388             uint64_t oldval = cpu->cpreg_values[i];
389 
390             if (oldval == newval) {
391                 continue;
392             }
393 
394             write_raw_cp_reg(&cpu->env, ri, oldval);
395             if (read_raw_cp_reg(&cpu->env, ri) != oldval) {
396                 continue;
397             }
398 
399             write_raw_cp_reg(&cpu->env, ri, newval);
400         }
401         cpu->cpreg_values[i] = newval;
402     }
403     return ok;
404 }
405 
406 bool write_list_to_cpustate(ARMCPU *cpu)
407 {
408     int i;
409     bool ok = true;
410 
411     for (i = 0; i < cpu->cpreg_array_len; i++) {
412         uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);
413         uint64_t v = cpu->cpreg_values[i];
414         const ARMCPRegInfo *ri;
415 
416         ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
417         if (!ri) {
418             ok = false;
419             continue;
420         }
421         if (ri->type & ARM_CP_NO_RAW) {
422             continue;
423         }
424         /* Write value and confirm it reads back as written
425          * (to catch read-only registers and partially read-only
426          * registers where the incoming migration value doesn't match)
427          */
428         write_raw_cp_reg(&cpu->env, ri, v);
429         if (read_raw_cp_reg(&cpu->env, ri) != v) {
430             ok = false;
431         }
432     }
433     return ok;
434 }
435 
436 static void add_cpreg_to_list(gpointer key, gpointer opaque)
437 {
438     ARMCPU *cpu = opaque;
439     uint64_t regidx;
440     const ARMCPRegInfo *ri;
441 
442     regidx = *(uint32_t *)key;
443     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
444 
445     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
446         cpu->cpreg_indexes[cpu->cpreg_array_len] = cpreg_to_kvm_id(regidx);
447         /* The value array need not be initialized at this point */
448         cpu->cpreg_array_len++;
449     }
450 }
451 
452 static void count_cpreg(gpointer key, gpointer opaque)
453 {
454     ARMCPU *cpu = opaque;
455     uint64_t regidx;
456     const ARMCPRegInfo *ri;
457 
458     regidx = *(uint32_t *)key;
459     ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);
460 
461     if (!(ri->type & (ARM_CP_NO_RAW|ARM_CP_ALIAS))) {
462         cpu->cpreg_array_len++;
463     }
464 }
465 
466 static gint cpreg_key_compare(gconstpointer a, gconstpointer b)
467 {
468     uint64_t aidx = cpreg_to_kvm_id(*(uint32_t *)a);
469     uint64_t bidx = cpreg_to_kvm_id(*(uint32_t *)b);
470 
471     if (aidx > bidx) {
472         return 1;
473     }
474     if (aidx < bidx) {
475         return -1;
476     }
477     return 0;
478 }
479 
480 void init_cpreg_list(ARMCPU *cpu)
481 {
482     /* Initialise the cpreg_tuples[] array based on the cp_regs hash.
483      * Note that we require cpreg_tuples[] to be sorted by key ID.
484      */
485     GList *keys;
486     int arraylen;
487 
488     keys = g_hash_table_get_keys(cpu->cp_regs);
489     keys = g_list_sort(keys, cpreg_key_compare);
490 
491     cpu->cpreg_array_len = 0;
492 
493     g_list_foreach(keys, count_cpreg, cpu);
494 
495     arraylen = cpu->cpreg_array_len;
496     cpu->cpreg_indexes = g_new(uint64_t, arraylen);
497     cpu->cpreg_values = g_new(uint64_t, arraylen);
498     cpu->cpreg_vmstate_indexes = g_new(uint64_t, arraylen);
499     cpu->cpreg_vmstate_values = g_new(uint64_t, arraylen);
500     cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;
501     cpu->cpreg_array_len = 0;
502 
503     g_list_foreach(keys, add_cpreg_to_list, cpu);
504 
505     assert(cpu->cpreg_array_len == arraylen);
506 
507     g_list_free(keys);
508 }
509 
510 /*
511  * Some registers are not accessible from AArch32 EL3 if SCR.NS == 0.
512  */
513 static CPAccessResult access_el3_aa32ns(CPUARMState *env,
514                                         const ARMCPRegInfo *ri,
515                                         bool isread)
516 {
517     if (!is_a64(env) && arm_current_el(env) == 3 &&
518         arm_is_secure_below_el3(env)) {
519         return CP_ACCESS_TRAP_UNCATEGORIZED;
520     }
521     return CP_ACCESS_OK;
522 }
523 
524 /* Some secure-only AArch32 registers trap to EL3 if used from
525  * Secure EL1 (but are just ordinary UNDEF in other non-EL3 contexts).
526  * Note that an access from Secure EL1 can only happen if EL3 is AArch64.
527  * We assume that the .access field is set to PL1_RW.
528  */
529 static CPAccessResult access_trap_aa32s_el1(CPUARMState *env,
530                                             const ARMCPRegInfo *ri,
531                                             bool isread)
532 {
533     if (arm_current_el(env) == 3) {
534         return CP_ACCESS_OK;
535     }
536     if (arm_is_secure_below_el3(env)) {
537         if (env->cp15.scr_el3 & SCR_EEL2) {
538             return CP_ACCESS_TRAP_EL2;
539         }
540         return CP_ACCESS_TRAP_EL3;
541     }
542     /* This will be EL1 NS and EL2 NS, which just UNDEF */
543     return CP_ACCESS_TRAP_UNCATEGORIZED;
544 }
545 
546 static uint64_t arm_mdcr_el2_eff(CPUARMState *env)
547 {
548     return arm_is_el2_enabled(env) ? env->cp15.mdcr_el2 : 0;
549 }
550 
551 /* Check for traps to "powerdown debug" registers, which are controlled
552  * by MDCR.TDOSA
553  */
554 static CPAccessResult access_tdosa(CPUARMState *env, const ARMCPRegInfo *ri,
555                                    bool isread)
556 {
557     int el = arm_current_el(env);
558     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
559     bool mdcr_el2_tdosa = (mdcr_el2 & MDCR_TDOSA) || (mdcr_el2 & MDCR_TDE) ||
560         (arm_hcr_el2_eff(env) & HCR_TGE);
561 
562     if (el < 2 && mdcr_el2_tdosa) {
563         return CP_ACCESS_TRAP_EL2;
564     }
565     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDOSA)) {
566         return CP_ACCESS_TRAP_EL3;
567     }
568     return CP_ACCESS_OK;
569 }
570 
571 /* Check for traps to "debug ROM" registers, which are controlled
572  * by MDCR_EL2.TDRA for EL2 but by the more general MDCR_EL3.TDA for EL3.
573  */
574 static CPAccessResult access_tdra(CPUARMState *env, const ARMCPRegInfo *ri,
575                                   bool isread)
576 {
577     int el = arm_current_el(env);
578     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
579     bool mdcr_el2_tdra = (mdcr_el2 & MDCR_TDRA) || (mdcr_el2 & MDCR_TDE) ||
580         (arm_hcr_el2_eff(env) & HCR_TGE);
581 
582     if (el < 2 && mdcr_el2_tdra) {
583         return CP_ACCESS_TRAP_EL2;
584     }
585     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
586         return CP_ACCESS_TRAP_EL3;
587     }
588     return CP_ACCESS_OK;
589 }
590 
591 /* Check for traps to general debug registers, which are controlled
592  * by MDCR_EL2.TDA for EL2 and MDCR_EL3.TDA for EL3.
593  */
594 static CPAccessResult access_tda(CPUARMState *env, const ARMCPRegInfo *ri,
595                                   bool isread)
596 {
597     int el = arm_current_el(env);
598     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
599     bool mdcr_el2_tda = (mdcr_el2 & MDCR_TDA) || (mdcr_el2 & MDCR_TDE) ||
600         (arm_hcr_el2_eff(env) & HCR_TGE);
601 
602     if (el < 2 && mdcr_el2_tda) {
603         return CP_ACCESS_TRAP_EL2;
604     }
605     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TDA)) {
606         return CP_ACCESS_TRAP_EL3;
607     }
608     return CP_ACCESS_OK;
609 }
610 
611 /* Check for traps to performance monitor registers, which are controlled
612  * by MDCR_EL2.TPM for EL2 and MDCR_EL3.TPM for EL3.
613  */
614 static CPAccessResult access_tpm(CPUARMState *env, const ARMCPRegInfo *ri,
615                                  bool isread)
616 {
617     int el = arm_current_el(env);
618     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
619 
620     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
621         return CP_ACCESS_TRAP_EL2;
622     }
623     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
624         return CP_ACCESS_TRAP_EL3;
625     }
626     return CP_ACCESS_OK;
627 }
628 
629 /* Check for traps from EL1 due to HCR_EL2.TVM and HCR_EL2.TRVM.  */
630 static CPAccessResult access_tvm_trvm(CPUARMState *env, const ARMCPRegInfo *ri,
631                                       bool isread)
632 {
633     if (arm_current_el(env) == 1) {
634         uint64_t trap = isread ? HCR_TRVM : HCR_TVM;
635         if (arm_hcr_el2_eff(env) & trap) {
636             return CP_ACCESS_TRAP_EL2;
637         }
638     }
639     return CP_ACCESS_OK;
640 }
641 
642 /* Check for traps from EL1 due to HCR_EL2.TSW.  */
643 static CPAccessResult access_tsw(CPUARMState *env, const ARMCPRegInfo *ri,
644                                  bool isread)
645 {
646     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TSW)) {
647         return CP_ACCESS_TRAP_EL2;
648     }
649     return CP_ACCESS_OK;
650 }
651 
652 /* Check for traps from EL1 due to HCR_EL2.TACR.  */
653 static CPAccessResult access_tacr(CPUARMState *env, const ARMCPRegInfo *ri,
654                                   bool isread)
655 {
656     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TACR)) {
657         return CP_ACCESS_TRAP_EL2;
658     }
659     return CP_ACCESS_OK;
660 }
661 
662 /* Check for traps from EL1 due to HCR_EL2.TTLB. */
663 static CPAccessResult access_ttlb(CPUARMState *env, const ARMCPRegInfo *ri,
664                                   bool isread)
665 {
666     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TTLB)) {
667         return CP_ACCESS_TRAP_EL2;
668     }
669     return CP_ACCESS_OK;
670 }
671 
672 static void dacr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
673 {
674     ARMCPU *cpu = env_archcpu(env);
675 
676     raw_write(env, ri, value);
677     tlb_flush(CPU(cpu)); /* Flush TLB as domain not tracked in TLB */
678 }
679 
680 static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
681 {
682     ARMCPU *cpu = env_archcpu(env);
683 
684     if (raw_read(env, ri) != value) {
685         /* Unlike real hardware the qemu TLB uses virtual addresses,
686          * not modified virtual addresses, so this causes a TLB flush.
687          */
688         tlb_flush(CPU(cpu));
689         raw_write(env, ri, value);
690     }
691 }
692 
693 static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,
694                              uint64_t value)
695 {
696     ARMCPU *cpu = env_archcpu(env);
697 
698     if (raw_read(env, ri) != value && !arm_feature(env, ARM_FEATURE_PMSA)
699         && !extended_addresses_enabled(env)) {
700         /* For VMSA (when not using the LPAE long descriptor page table
701          * format) this register includes the ASID, so do a TLB flush.
702          * For PMSA it is purely a process ID and no action is needed.
703          */
704         tlb_flush(CPU(cpu));
705     }
706     raw_write(env, ri, value);
707 }
708 
709 /* IS variants of TLB operations must affect all cores */
710 static void tlbiall_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
711                              uint64_t value)
712 {
713     CPUState *cs = env_cpu(env);
714 
715     tlb_flush_all_cpus_synced(cs);
716 }
717 
718 static void tlbiasid_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
719                              uint64_t value)
720 {
721     CPUState *cs = env_cpu(env);
722 
723     tlb_flush_all_cpus_synced(cs);
724 }
725 
726 static void tlbimva_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
727                              uint64_t value)
728 {
729     CPUState *cs = env_cpu(env);
730 
731     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
732 }
733 
734 static void tlbimvaa_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
735                              uint64_t value)
736 {
737     CPUState *cs = env_cpu(env);
738 
739     tlb_flush_page_all_cpus_synced(cs, value & TARGET_PAGE_MASK);
740 }
741 
742 /*
743  * Non-IS variants of TLB operations are upgraded to
744  * IS versions if we are at EL1 and HCR_EL2.FB is effectively set to
745  * force broadcast of these operations.
746  */
747 static bool tlb_force_broadcast(CPUARMState *env)
748 {
749     return arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_FB);
750 }
751 
752 static void tlbiall_write(CPUARMState *env, const ARMCPRegInfo *ri,
753                           uint64_t value)
754 {
755     /* Invalidate all (TLBIALL) */
756     CPUState *cs = env_cpu(env);
757 
758     if (tlb_force_broadcast(env)) {
759         tlb_flush_all_cpus_synced(cs);
760     } else {
761         tlb_flush(cs);
762     }
763 }
764 
765 static void tlbimva_write(CPUARMState *env, const ARMCPRegInfo *ri,
766                           uint64_t value)
767 {
768     /* Invalidate single TLB entry by MVA and ASID (TLBIMVA) */
769     CPUState *cs = env_cpu(env);
770 
771     value &= TARGET_PAGE_MASK;
772     if (tlb_force_broadcast(env)) {
773         tlb_flush_page_all_cpus_synced(cs, value);
774     } else {
775         tlb_flush_page(cs, value);
776     }
777 }
778 
779 static void tlbiasid_write(CPUARMState *env, const ARMCPRegInfo *ri,
780                            uint64_t value)
781 {
782     /* Invalidate by ASID (TLBIASID) */
783     CPUState *cs = env_cpu(env);
784 
785     if (tlb_force_broadcast(env)) {
786         tlb_flush_all_cpus_synced(cs);
787     } else {
788         tlb_flush(cs);
789     }
790 }
791 
792 static void tlbimvaa_write(CPUARMState *env, const ARMCPRegInfo *ri,
793                            uint64_t value)
794 {
795     /* Invalidate single entry by MVA, all ASIDs (TLBIMVAA) */
796     CPUState *cs = env_cpu(env);
797 
798     value &= TARGET_PAGE_MASK;
799     if (tlb_force_broadcast(env)) {
800         tlb_flush_page_all_cpus_synced(cs, value);
801     } else {
802         tlb_flush_page(cs, value);
803     }
804 }
805 
806 static void tlbiall_nsnh_write(CPUARMState *env, const ARMCPRegInfo *ri,
807                                uint64_t value)
808 {
809     CPUState *cs = env_cpu(env);
810 
811     tlb_flush_by_mmuidx(cs,
812                         ARMMMUIdxBit_E10_1 |
813                         ARMMMUIdxBit_E10_1_PAN |
814                         ARMMMUIdxBit_E10_0);
815 }
816 
817 static void tlbiall_nsnh_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
818                                   uint64_t value)
819 {
820     CPUState *cs = env_cpu(env);
821 
822     tlb_flush_by_mmuidx_all_cpus_synced(cs,
823                                         ARMMMUIdxBit_E10_1 |
824                                         ARMMMUIdxBit_E10_1_PAN |
825                                         ARMMMUIdxBit_E10_0);
826 }
827 
828 
829 static void tlbiall_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
830                               uint64_t value)
831 {
832     CPUState *cs = env_cpu(env);
833 
834     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_E2);
835 }
836 
837 static void tlbiall_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
838                                  uint64_t value)
839 {
840     CPUState *cs = env_cpu(env);
841 
842     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_E2);
843 }
844 
845 static void tlbimva_hyp_write(CPUARMState *env, const ARMCPRegInfo *ri,
846                               uint64_t value)
847 {
848     CPUState *cs = env_cpu(env);
849     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
850 
851     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_E2);
852 }
853 
854 static void tlbimva_hyp_is_write(CPUARMState *env, const ARMCPRegInfo *ri,
855                                  uint64_t value)
856 {
857     CPUState *cs = env_cpu(env);
858     uint64_t pageaddr = value & ~MAKE_64BIT_MASK(0, 12);
859 
860     tlb_flush_page_by_mmuidx_all_cpus_synced(cs, pageaddr,
861                                              ARMMMUIdxBit_E2);
862 }
863 
864 static const ARMCPRegInfo cp_reginfo[] = {
865     /* Define the secure and non-secure FCSE identifier CP registers
866      * separately because there is no secure bank in V8 (no _EL3).  This allows
867      * the secure register to be properly reset and migrated. There is also no
868      * v8 EL1 version of the register so the non-secure instance stands alone.
869      */
870     { .name = "FCSEIDR",
871       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
872       .access = PL1_RW, .secure = ARM_CP_SECSTATE_NS,
873       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_ns),
874       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
875     { .name = "FCSEIDR_S",
876       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 0,
877       .access = PL1_RW, .secure = ARM_CP_SECSTATE_S,
878       .fieldoffset = offsetof(CPUARMState, cp15.fcseidr_s),
879       .resetvalue = 0, .writefn = fcse_write, .raw_writefn = raw_write, },
880     /* Define the secure and non-secure context identifier CP registers
881      * separately because there is no secure bank in V8 (no _EL3).  This allows
882      * the secure register to be properly reset and migrated.  In the
883      * non-secure case, the 32-bit register will have reset and migration
884      * disabled during registration as it is handled by the 64-bit instance.
885      */
886     { .name = "CONTEXTIDR_EL1", .state = ARM_CP_STATE_BOTH,
887       .opc0 = 3, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
888       .access = PL1_RW, .accessfn = access_tvm_trvm,
889       .secure = ARM_CP_SECSTATE_NS,
890       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[1]),
891       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
892     { .name = "CONTEXTIDR_S", .state = ARM_CP_STATE_AA32,
893       .cp = 15, .opc1 = 0, .crn = 13, .crm = 0, .opc2 = 1,
894       .access = PL1_RW, .accessfn = access_tvm_trvm,
895       .secure = ARM_CP_SECSTATE_S,
896       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_s),
897       .resetvalue = 0, .writefn = contextidr_write, .raw_writefn = raw_write, },
898     REGINFO_SENTINEL
899 };
900 
901 static const ARMCPRegInfo not_v8_cp_reginfo[] = {
902     /* NB: Some of these registers exist in v8 but with more precise
903      * definitions that don't use CP_ANY wildcards (mostly in v8_cp_reginfo[]).
904      */
905     /* MMU Domain access control / MPU write buffer control */
906     { .name = "DACR",
907       .cp = 15, .opc1 = CP_ANY, .crn = 3, .crm = CP_ANY, .opc2 = CP_ANY,
908       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
909       .writefn = dacr_write, .raw_writefn = raw_write,
910       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
911                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
912     /* ARMv7 allocates a range of implementation defined TLB LOCKDOWN regs.
913      * For v6 and v5, these mappings are overly broad.
914      */
915     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 0,
916       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
917     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 1,
918       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
919     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 4,
920       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
921     { .name = "TLB_LOCKDOWN", .cp = 15, .crn = 10, .crm = 8,
922       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_NOP },
923     /* Cache maintenance ops; some of this space may be overridden later. */
924     { .name = "CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
925       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
926       .type = ARM_CP_NOP | ARM_CP_OVERRIDE },
927     REGINFO_SENTINEL
928 };
929 
930 static const ARMCPRegInfo not_v6_cp_reginfo[] = {
931     /* Not all pre-v6 cores implemented this WFI, so this is slightly
932      * over-broad.
933      */
934     { .name = "WFI_v5", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = 2,
935       .access = PL1_W, .type = ARM_CP_WFI },
936     REGINFO_SENTINEL
937 };
938 
939 static const ARMCPRegInfo not_v7_cp_reginfo[] = {
940     /* Standard v6 WFI (also used in some pre-v6 cores); not in v7 (which
941      * is UNPREDICTABLE; we choose to NOP as most implementations do).
942      */
943     { .name = "WFI_v6", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
944       .access = PL1_W, .type = ARM_CP_WFI },
945     /* L1 cache lockdown. Not architectural in v6 and earlier but in practice
946      * implemented in 926, 946, 1026, 1136, 1176 and 11MPCore. StrongARM and
947      * OMAPCP will override this space.
948      */
949     { .name = "DLOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 0,
950       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_data),
951       .resetvalue = 0 },
952     { .name = "ILOCKDOWN", .cp = 15, .crn = 9, .crm = 0, .opc1 = 0, .opc2 = 1,
953       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.c9_insn),
954       .resetvalue = 0 },
955     /* v6 doesn't have the cache ID registers but Linux reads them anyway */
956     { .name = "DUMMY", .cp = 15, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = CP_ANY,
957       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
958       .resetvalue = 0 },
959     /* We don't implement pre-v7 debug but most CPUs had at least a DBGDIDR;
960      * implementing it as RAZ means the "debug architecture version" bits
961      * will read as a reserved value, which should cause Linux to not try
962      * to use the debug hardware.
963      */
964     { .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 0,
965       .access = PL0_R, .type = ARM_CP_CONST, .resetvalue = 0 },
966     /* MMU TLB control. Note that the wildcarding means we cover not just
967      * the unified TLB ops but also the dside/iside/inner-shareable variants.
968      */
969     { .name = "TLBIALL", .cp = 15, .crn = 8, .crm = CP_ANY,
970       .opc1 = CP_ANY, .opc2 = 0, .access = PL1_W, .writefn = tlbiall_write,
971       .type = ARM_CP_NO_RAW },
972     { .name = "TLBIMVA", .cp = 15, .crn = 8, .crm = CP_ANY,
973       .opc1 = CP_ANY, .opc2 = 1, .access = PL1_W, .writefn = tlbimva_write,
974       .type = ARM_CP_NO_RAW },
975     { .name = "TLBIASID", .cp = 15, .crn = 8, .crm = CP_ANY,
976       .opc1 = CP_ANY, .opc2 = 2, .access = PL1_W, .writefn = tlbiasid_write,
977       .type = ARM_CP_NO_RAW },
978     { .name = "TLBIMVAA", .cp = 15, .crn = 8, .crm = CP_ANY,
979       .opc1 = CP_ANY, .opc2 = 3, .access = PL1_W, .writefn = tlbimvaa_write,
980       .type = ARM_CP_NO_RAW },
981     { .name = "PRRR", .cp = 15, .crn = 10, .crm = 2,
982       .opc1 = 0, .opc2 = 0, .access = PL1_RW, .type = ARM_CP_NOP },
983     { .name = "NMRR", .cp = 15, .crn = 10, .crm = 2,
984       .opc1 = 0, .opc2 = 1, .access = PL1_RW, .type = ARM_CP_NOP },
985     REGINFO_SENTINEL
986 };
987 
988 static void cpacr_write(CPUARMState *env, const ARMCPRegInfo *ri,
989                         uint64_t value)
990 {
991     uint32_t mask = 0;
992 
993     /* In ARMv8 most bits of CPACR_EL1 are RES0. */
994     if (!arm_feature(env, ARM_FEATURE_V8)) {
995         /* ARMv7 defines bits for unimplemented coprocessors as RAZ/WI.
996          * ASEDIS [31] and D32DIS [30] are both UNK/SBZP without VFP.
997          * TRCDIS [28] is RAZ/WI since we do not implement a trace macrocell.
998          */
999         if (cpu_isar_feature(aa32_vfp_simd, env_archcpu(env))) {
1000             /* VFP coprocessor: cp10 & cp11 [23:20] */
1001             mask |= (1 << 31) | (1 << 30) | (0xf << 20);
1002 
1003             if (!arm_feature(env, ARM_FEATURE_NEON)) {
1004                 /* ASEDIS [31] bit is RAO/WI */
1005                 value |= (1 << 31);
1006             }
1007 
1008             /* VFPv3 and upwards with NEON implement 32 double precision
1009              * registers (D0-D31).
1010              */
1011             if (!cpu_isar_feature(aa32_simd_r32, env_archcpu(env))) {
1012                 /* D32DIS [30] is RAO/WI if D16-31 are not implemented. */
1013                 value |= (1 << 30);
1014             }
1015         }
1016         value &= mask;
1017     }
1018 
1019     /*
1020      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
1021      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
1022      */
1023     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
1024         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
1025         value &= ~(0xf << 20);
1026         value |= env->cp15.cpacr_el1 & (0xf << 20);
1027     }
1028 
1029     env->cp15.cpacr_el1 = value;
1030 }
1031 
1032 static uint64_t cpacr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1033 {
1034     /*
1035      * For A-profile AArch32 EL3 (but not M-profile secure mode), if NSACR.CP10
1036      * is 0 then CPACR.{CP11,CP10} ignore writes and read as 0b00.
1037      */
1038     uint64_t value = env->cp15.cpacr_el1;
1039 
1040     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
1041         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
1042         value &= ~(0xf << 20);
1043     }
1044     return value;
1045 }
1046 
1047 
1048 static void cpacr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
1049 {
1050     /* Call cpacr_write() so that we reset with the correct RAO bits set
1051      * for our CPU features.
1052      */
1053     cpacr_write(env, ri, 0);
1054 }
1055 
1056 static CPAccessResult cpacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1057                                    bool isread)
1058 {
1059     if (arm_feature(env, ARM_FEATURE_V8)) {
1060         /* Check if CPACR accesses are to be trapped to EL2 */
1061         if (arm_current_el(env) == 1 && arm_is_el2_enabled(env) &&
1062             (env->cp15.cptr_el[2] & CPTR_TCPAC)) {
1063             return CP_ACCESS_TRAP_EL2;
1064         /* Check if CPACR accesses are to be trapped to EL3 */
1065         } else if (arm_current_el(env) < 3 &&
1066                    (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
1067             return CP_ACCESS_TRAP_EL3;
1068         }
1069     }
1070 
1071     return CP_ACCESS_OK;
1072 }
1073 
1074 static CPAccessResult cptr_access(CPUARMState *env, const ARMCPRegInfo *ri,
1075                                   bool isread)
1076 {
1077     /* Check if CPTR accesses are set to trap to EL3 */
1078     if (arm_current_el(env) == 2 && (env->cp15.cptr_el[3] & CPTR_TCPAC)) {
1079         return CP_ACCESS_TRAP_EL3;
1080     }
1081 
1082     return CP_ACCESS_OK;
1083 }
1084 
1085 static const ARMCPRegInfo v6_cp_reginfo[] = {
1086     /* prefetch by MVA in v6, NOP in v7 */
1087     { .name = "MVA_prefetch",
1088       .cp = 15, .crn = 7, .crm = 13, .opc1 = 0, .opc2 = 1,
1089       .access = PL1_W, .type = ARM_CP_NOP },
1090     /* We need to break the TB after ISB to execute self-modifying code
1091      * correctly and also to take any pending interrupts immediately.
1092      * So use arm_cp_write_ignore() function instead of ARM_CP_NOP flag.
1093      */
1094     { .name = "ISB", .cp = 15, .crn = 7, .crm = 5, .opc1 = 0, .opc2 = 4,
1095       .access = PL0_W, .type = ARM_CP_NO_RAW, .writefn = arm_cp_write_ignore },
1096     { .name = "DSB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 4,
1097       .access = PL0_W, .type = ARM_CP_NOP },
1098     { .name = "DMB", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 5,
1099       .access = PL0_W, .type = ARM_CP_NOP },
1100     { .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 2,
1101       .access = PL1_RW, .accessfn = access_tvm_trvm,
1102       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ifar_s),
1103                              offsetof(CPUARMState, cp15.ifar_ns) },
1104       .resetvalue = 0, },
1105     /* Watchpoint Fault Address Register : should actually only be present
1106      * for 1136, 1176, 11MPCore.
1107      */
1108     { .name = "WFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,
1109       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0, },
1110     { .name = "CPACR", .state = ARM_CP_STATE_BOTH, .opc0 = 3,
1111       .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 2, .accessfn = cpacr_access,
1112       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, cp15.cpacr_el1),
1113       .resetfn = cpacr_reset, .writefn = cpacr_write, .readfn = cpacr_read },
1114     REGINFO_SENTINEL
1115 };
1116 
1117 /* Definitions for the PMU registers */
1118 #define PMCRN_MASK  0xf800
1119 #define PMCRN_SHIFT 11
1120 #define PMCRLC  0x40
1121 #define PMCRDP  0x20
1122 #define PMCRX   0x10
1123 #define PMCRD   0x8
1124 #define PMCRC   0x4
1125 #define PMCRP   0x2
1126 #define PMCRE   0x1
1127 /*
1128  * Mask of PMCR bits writeable by guest (not including WO bits like C, P,
1129  * which can be written as 1 to trigger behaviour but which stay RAZ).
1130  */
1131 #define PMCR_WRITEABLE_MASK (PMCRLC | PMCRDP | PMCRX | PMCRD | PMCRE)
1132 
1133 #define PMXEVTYPER_P          0x80000000
1134 #define PMXEVTYPER_U          0x40000000
1135 #define PMXEVTYPER_NSK        0x20000000
1136 #define PMXEVTYPER_NSU        0x10000000
1137 #define PMXEVTYPER_NSH        0x08000000
1138 #define PMXEVTYPER_M          0x04000000
1139 #define PMXEVTYPER_MT         0x02000000
1140 #define PMXEVTYPER_EVTCOUNT   0x0000ffff
1141 #define PMXEVTYPER_MASK       (PMXEVTYPER_P | PMXEVTYPER_U | PMXEVTYPER_NSK | \
1142                                PMXEVTYPER_NSU | PMXEVTYPER_NSH | \
1143                                PMXEVTYPER_M | PMXEVTYPER_MT | \
1144                                PMXEVTYPER_EVTCOUNT)
1145 
1146 #define PMCCFILTR             0xf8000000
1147 #define PMCCFILTR_M           PMXEVTYPER_M
1148 #define PMCCFILTR_EL0         (PMCCFILTR | PMCCFILTR_M)
1149 
1150 static inline uint32_t pmu_num_counters(CPUARMState *env)
1151 {
1152   return (env->cp15.c9_pmcr & PMCRN_MASK) >> PMCRN_SHIFT;
1153 }
1154 
1155 /* Bits allowed to be set/cleared for PMCNTEN* and PMINTEN* */
1156 static inline uint64_t pmu_counter_mask(CPUARMState *env)
1157 {
1158   return (1 << 31) | ((1 << pmu_num_counters(env)) - 1);
1159 }
1160 
1161 typedef struct pm_event {
1162     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1163     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1164     bool (*supported)(CPUARMState *);
1165     /*
1166      * Retrieve the current count of the underlying event. The programmed
1167      * counters hold a difference from the return value from this function
1168      */
1169     uint64_t (*get_count)(CPUARMState *);
1170     /*
1171      * Return how many nanoseconds it will take (at a minimum) for count events
1172      * to occur. A negative value indicates the counter will never overflow, or
1173      * that the counter has otherwise arranged for the overflow bit to be set
1174      * and the PMU interrupt to be raised on overflow.
1175      */
1176     int64_t (*ns_per_count)(uint64_t);
1177 } pm_event;
1178 
1179 static bool event_always_supported(CPUARMState *env)
1180 {
1181     return true;
1182 }
1183 
1184 static uint64_t swinc_get_count(CPUARMState *env)
1185 {
1186     /*
1187      * SW_INCR events are written directly to the pmevcntr's by writes to
1188      * PMSWINC, so there is no underlying count maintained by the PMU itself
1189      */
1190     return 0;
1191 }
1192 
1193 static int64_t swinc_ns_per(uint64_t ignored)
1194 {
1195     return -1;
1196 }
1197 
1198 /*
1199  * Return the underlying cycle count for the PMU cycle counters. If we're in
1200  * usermode, simply return 0.
1201  */
1202 static uint64_t cycles_get_count(CPUARMState *env)
1203 {
1204 #ifndef CONFIG_USER_ONLY
1205     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1206                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1207 #else
1208     return cpu_get_host_ticks();
1209 #endif
1210 }
1211 
1212 #ifndef CONFIG_USER_ONLY
1213 static int64_t cycles_ns_per(uint64_t cycles)
1214 {
1215     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1216 }
1217 
1218 static bool instructions_supported(CPUARMState *env)
1219 {
1220     return icount_enabled() == 1; /* Precise instruction counting */
1221 }
1222 
1223 static uint64_t instructions_get_count(CPUARMState *env)
1224 {
1225     return (uint64_t)icount_get_raw();
1226 }
1227 
1228 static int64_t instructions_ns_per(uint64_t icount)
1229 {
1230     return icount_to_ns((int64_t)icount);
1231 }
1232 #endif
1233 
1234 static bool pmu_8_1_events_supported(CPUARMState *env)
1235 {
1236     /* For events which are supported in any v8.1 PMU */
1237     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
1238 }
1239 
1240 static bool pmu_8_4_events_supported(CPUARMState *env)
1241 {
1242     /* For events which are supported in any v8.1 PMU */
1243     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
1244 }
1245 
1246 static uint64_t zero_event_get_count(CPUARMState *env)
1247 {
1248     /* For events which on QEMU never fire, so their count is always zero */
1249     return 0;
1250 }
1251 
1252 static int64_t zero_event_ns_per(uint64_t cycles)
1253 {
1254     /* An event which never fires can never overflow */
1255     return -1;
1256 }
1257 
1258 static const pm_event pm_events[] = {
1259     { .number = 0x000, /* SW_INCR */
1260       .supported = event_always_supported,
1261       .get_count = swinc_get_count,
1262       .ns_per_count = swinc_ns_per,
1263     },
1264 #ifndef CONFIG_USER_ONLY
1265     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1266       .supported = instructions_supported,
1267       .get_count = instructions_get_count,
1268       .ns_per_count = instructions_ns_per,
1269     },
1270     { .number = 0x011, /* CPU_CYCLES, Cycle */
1271       .supported = event_always_supported,
1272       .get_count = cycles_get_count,
1273       .ns_per_count = cycles_ns_per,
1274     },
1275 #endif
1276     { .number = 0x023, /* STALL_FRONTEND */
1277       .supported = pmu_8_1_events_supported,
1278       .get_count = zero_event_get_count,
1279       .ns_per_count = zero_event_ns_per,
1280     },
1281     { .number = 0x024, /* STALL_BACKEND */
1282       .supported = pmu_8_1_events_supported,
1283       .get_count = zero_event_get_count,
1284       .ns_per_count = zero_event_ns_per,
1285     },
1286     { .number = 0x03c, /* STALL */
1287       .supported = pmu_8_4_events_supported,
1288       .get_count = zero_event_get_count,
1289       .ns_per_count = zero_event_ns_per,
1290     },
1291 };
1292 
1293 /*
1294  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1295  * events (i.e. the statistical profiling extension), this implementation
1296  * should first be updated to something sparse instead of the current
1297  * supported_event_map[] array.
1298  */
1299 #define MAX_EVENT_ID 0x3c
1300 #define UNSUPPORTED_EVENT UINT16_MAX
1301 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1302 
1303 /*
1304  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1305  * of ARM event numbers to indices in our pm_events array.
1306  *
1307  * Note: Events in the 0x40XX range are not currently supported.
1308  */
1309 void pmu_init(ARMCPU *cpu)
1310 {
1311     unsigned int i;
1312 
1313     /*
1314      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1315      * events to them
1316      */
1317     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1318         supported_event_map[i] = UNSUPPORTED_EVENT;
1319     }
1320     cpu->pmceid0 = 0;
1321     cpu->pmceid1 = 0;
1322 
1323     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1324         const pm_event *cnt = &pm_events[i];
1325         assert(cnt->number <= MAX_EVENT_ID);
1326         /* We do not currently support events in the 0x40xx range */
1327         assert(cnt->number <= 0x3f);
1328 
1329         if (cnt->supported(&cpu->env)) {
1330             supported_event_map[cnt->number] = i;
1331             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1332             if (cnt->number & 0x20) {
1333                 cpu->pmceid1 |= event_mask;
1334             } else {
1335                 cpu->pmceid0 |= event_mask;
1336             }
1337         }
1338     }
1339 }
1340 
1341 /*
1342  * Check at runtime whether a PMU event is supported for the current machine
1343  */
1344 static bool event_supported(uint16_t number)
1345 {
1346     if (number > MAX_EVENT_ID) {
1347         return false;
1348     }
1349     return supported_event_map[number] != UNSUPPORTED_EVENT;
1350 }
1351 
1352 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1353                                    bool isread)
1354 {
1355     /* Performance monitor registers user accessibility is controlled
1356      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1357      * trapping to EL2 or EL3 for other accesses.
1358      */
1359     int el = arm_current_el(env);
1360     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1361 
1362     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1363         return CP_ACCESS_TRAP;
1364     }
1365     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
1366         return CP_ACCESS_TRAP_EL2;
1367     }
1368     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1369         return CP_ACCESS_TRAP_EL3;
1370     }
1371 
1372     return CP_ACCESS_OK;
1373 }
1374 
1375 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1376                                            const ARMCPRegInfo *ri,
1377                                            bool isread)
1378 {
1379     /* ER: event counter read trap control */
1380     if (arm_feature(env, ARM_FEATURE_V8)
1381         && arm_current_el(env) == 0
1382         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1383         && isread) {
1384         return CP_ACCESS_OK;
1385     }
1386 
1387     return pmreg_access(env, ri, isread);
1388 }
1389 
1390 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1391                                          const ARMCPRegInfo *ri,
1392                                          bool isread)
1393 {
1394     /* SW: software increment write trap control */
1395     if (arm_feature(env, ARM_FEATURE_V8)
1396         && arm_current_el(env) == 0
1397         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1398         && !isread) {
1399         return CP_ACCESS_OK;
1400     }
1401 
1402     return pmreg_access(env, ri, isread);
1403 }
1404 
1405 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1406                                         const ARMCPRegInfo *ri,
1407                                         bool isread)
1408 {
1409     /* ER: event counter read trap control */
1410     if (arm_feature(env, ARM_FEATURE_V8)
1411         && arm_current_el(env) == 0
1412         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1413         return CP_ACCESS_OK;
1414     }
1415 
1416     return pmreg_access(env, ri, isread);
1417 }
1418 
1419 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1420                                          const ARMCPRegInfo *ri,
1421                                          bool isread)
1422 {
1423     /* CR: cycle counter read trap control */
1424     if (arm_feature(env, ARM_FEATURE_V8)
1425         && arm_current_el(env) == 0
1426         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1427         && isread) {
1428         return CP_ACCESS_OK;
1429     }
1430 
1431     return pmreg_access(env, ri, isread);
1432 }
1433 
1434 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1435  * the current EL, security state, and register configuration.
1436  */
1437 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1438 {
1439     uint64_t filter;
1440     bool e, p, u, nsk, nsu, nsh, m;
1441     bool enabled, prohibited, filtered;
1442     bool secure = arm_is_secure(env);
1443     int el = arm_current_el(env);
1444     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1445     uint8_t hpmn = mdcr_el2 & MDCR_HPMN;
1446 
1447     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1448         return false;
1449     }
1450 
1451     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1452             (counter < hpmn || counter == 31)) {
1453         e = env->cp15.c9_pmcr & PMCRE;
1454     } else {
1455         e = mdcr_el2 & MDCR_HPME;
1456     }
1457     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1458 
1459     if (!secure) {
1460         if (el == 2 && (counter < hpmn || counter == 31)) {
1461             prohibited = mdcr_el2 & MDCR_HPMD;
1462         } else {
1463             prohibited = false;
1464         }
1465     } else {
1466         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1467            !(env->cp15.mdcr_el3 & MDCR_SPME);
1468     }
1469 
1470     if (prohibited && counter == 31) {
1471         prohibited = env->cp15.c9_pmcr & PMCRDP;
1472     }
1473 
1474     if (counter == 31) {
1475         filter = env->cp15.pmccfiltr_el0;
1476     } else {
1477         filter = env->cp15.c14_pmevtyper[counter];
1478     }
1479 
1480     p   = filter & PMXEVTYPER_P;
1481     u   = filter & PMXEVTYPER_U;
1482     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1483     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1484     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1485     m   = arm_el_is_aa64(env, 1) &&
1486               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1487 
1488     if (el == 0) {
1489         filtered = secure ? u : u != nsu;
1490     } else if (el == 1) {
1491         filtered = secure ? p : p != nsk;
1492     } else if (el == 2) {
1493         filtered = !nsh;
1494     } else { /* EL3 */
1495         filtered = m != p;
1496     }
1497 
1498     if (counter != 31) {
1499         /*
1500          * If not checking PMCCNTR, ensure the counter is setup to an event we
1501          * support
1502          */
1503         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1504         if (!event_supported(event)) {
1505             return false;
1506         }
1507     }
1508 
1509     return enabled && !prohibited && !filtered;
1510 }
1511 
1512 static void pmu_update_irq(CPUARMState *env)
1513 {
1514     ARMCPU *cpu = env_archcpu(env);
1515     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1516             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1517 }
1518 
1519 /*
1520  * Ensure c15_ccnt is the guest-visible count so that operations such as
1521  * enabling/disabling the counter or filtering, modifying the count itself,
1522  * etc. can be done logically. This is essentially a no-op if the counter is
1523  * not enabled at the time of the call.
1524  */
1525 static void pmccntr_op_start(CPUARMState *env)
1526 {
1527     uint64_t cycles = cycles_get_count(env);
1528 
1529     if (pmu_counter_enabled(env, 31)) {
1530         uint64_t eff_cycles = cycles;
1531         if (env->cp15.c9_pmcr & PMCRD) {
1532             /* Increment once every 64 processor clock cycles */
1533             eff_cycles /= 64;
1534         }
1535 
1536         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1537 
1538         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1539                                  1ull << 63 : 1ull << 31;
1540         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1541             env->cp15.c9_pmovsr |= (1 << 31);
1542             pmu_update_irq(env);
1543         }
1544 
1545         env->cp15.c15_ccnt = new_pmccntr;
1546     }
1547     env->cp15.c15_ccnt_delta = cycles;
1548 }
1549 
1550 /*
1551  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1552  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1553  * pmccntr_op_start.
1554  */
1555 static void pmccntr_op_finish(CPUARMState *env)
1556 {
1557     if (pmu_counter_enabled(env, 31)) {
1558 #ifndef CONFIG_USER_ONLY
1559         /* Calculate when the counter will next overflow */
1560         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1561         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1562             remaining_cycles = (uint32_t)remaining_cycles;
1563         }
1564         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1565 
1566         if (overflow_in > 0) {
1567             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1568                 overflow_in;
1569             ARMCPU *cpu = env_archcpu(env);
1570             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1571         }
1572 #endif
1573 
1574         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1575         if (env->cp15.c9_pmcr & PMCRD) {
1576             /* Increment once every 64 processor clock cycles */
1577             prev_cycles /= 64;
1578         }
1579         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1580     }
1581 }
1582 
1583 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1584 {
1585 
1586     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1587     uint64_t count = 0;
1588     if (event_supported(event)) {
1589         uint16_t event_idx = supported_event_map[event];
1590         count = pm_events[event_idx].get_count(env);
1591     }
1592 
1593     if (pmu_counter_enabled(env, counter)) {
1594         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1595 
1596         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1597             env->cp15.c9_pmovsr |= (1 << counter);
1598             pmu_update_irq(env);
1599         }
1600         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1601     }
1602     env->cp15.c14_pmevcntr_delta[counter] = count;
1603 }
1604 
1605 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1606 {
1607     if (pmu_counter_enabled(env, counter)) {
1608 #ifndef CONFIG_USER_ONLY
1609         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1610         uint16_t event_idx = supported_event_map[event];
1611         uint64_t delta = UINT32_MAX -
1612             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1613         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1614 
1615         if (overflow_in > 0) {
1616             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1617                 overflow_in;
1618             ARMCPU *cpu = env_archcpu(env);
1619             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1620         }
1621 #endif
1622 
1623         env->cp15.c14_pmevcntr_delta[counter] -=
1624             env->cp15.c14_pmevcntr[counter];
1625     }
1626 }
1627 
1628 void pmu_op_start(CPUARMState *env)
1629 {
1630     unsigned int i;
1631     pmccntr_op_start(env);
1632     for (i = 0; i < pmu_num_counters(env); i++) {
1633         pmevcntr_op_start(env, i);
1634     }
1635 }
1636 
1637 void pmu_op_finish(CPUARMState *env)
1638 {
1639     unsigned int i;
1640     pmccntr_op_finish(env);
1641     for (i = 0; i < pmu_num_counters(env); i++) {
1642         pmevcntr_op_finish(env, i);
1643     }
1644 }
1645 
1646 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1647 {
1648     pmu_op_start(&cpu->env);
1649 }
1650 
1651 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1652 {
1653     pmu_op_finish(&cpu->env);
1654 }
1655 
1656 void arm_pmu_timer_cb(void *opaque)
1657 {
1658     ARMCPU *cpu = opaque;
1659 
1660     /*
1661      * Update all the counter values based on the current underlying counts,
1662      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1663      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1664      * counter may expire.
1665      */
1666     pmu_op_start(&cpu->env);
1667     pmu_op_finish(&cpu->env);
1668 }
1669 
1670 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1671                        uint64_t value)
1672 {
1673     pmu_op_start(env);
1674 
1675     if (value & PMCRC) {
1676         /* The counter has been reset */
1677         env->cp15.c15_ccnt = 0;
1678     }
1679 
1680     if (value & PMCRP) {
1681         unsigned int i;
1682         for (i = 0; i < pmu_num_counters(env); i++) {
1683             env->cp15.c14_pmevcntr[i] = 0;
1684         }
1685     }
1686 
1687     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1688     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1689 
1690     pmu_op_finish(env);
1691 }
1692 
1693 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1694                           uint64_t value)
1695 {
1696     unsigned int i;
1697     for (i = 0; i < pmu_num_counters(env); i++) {
1698         /* Increment a counter's count iff: */
1699         if ((value & (1 << i)) && /* counter's bit is set */
1700                 /* counter is enabled and not filtered */
1701                 pmu_counter_enabled(env, i) &&
1702                 /* counter is SW_INCR */
1703                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1704             pmevcntr_op_start(env, i);
1705 
1706             /*
1707              * Detect if this write causes an overflow since we can't predict
1708              * PMSWINC overflows like we can for other events
1709              */
1710             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1711 
1712             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1713                 env->cp15.c9_pmovsr |= (1 << i);
1714                 pmu_update_irq(env);
1715             }
1716 
1717             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1718 
1719             pmevcntr_op_finish(env, i);
1720         }
1721     }
1722 }
1723 
1724 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1725 {
1726     uint64_t ret;
1727     pmccntr_op_start(env);
1728     ret = env->cp15.c15_ccnt;
1729     pmccntr_op_finish(env);
1730     return ret;
1731 }
1732 
1733 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1734                          uint64_t value)
1735 {
1736     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1737      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1738      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1739      * accessed.
1740      */
1741     env->cp15.c9_pmselr = value & 0x1f;
1742 }
1743 
1744 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1745                         uint64_t value)
1746 {
1747     pmccntr_op_start(env);
1748     env->cp15.c15_ccnt = value;
1749     pmccntr_op_finish(env);
1750 }
1751 
1752 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1753                             uint64_t value)
1754 {
1755     uint64_t cur_val = pmccntr_read(env, NULL);
1756 
1757     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1758 }
1759 
1760 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1761                             uint64_t value)
1762 {
1763     pmccntr_op_start(env);
1764     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1765     pmccntr_op_finish(env);
1766 }
1767 
1768 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1769                             uint64_t value)
1770 {
1771     pmccntr_op_start(env);
1772     /* M is not accessible from AArch32 */
1773     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1774         (value & PMCCFILTR);
1775     pmccntr_op_finish(env);
1776 }
1777 
1778 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1779 {
1780     /* M is not visible in AArch32 */
1781     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1782 }
1783 
1784 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1785                             uint64_t value)
1786 {
1787     value &= pmu_counter_mask(env);
1788     env->cp15.c9_pmcnten |= value;
1789 }
1790 
1791 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1792                              uint64_t value)
1793 {
1794     value &= pmu_counter_mask(env);
1795     env->cp15.c9_pmcnten &= ~value;
1796 }
1797 
1798 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1799                          uint64_t value)
1800 {
1801     value &= pmu_counter_mask(env);
1802     env->cp15.c9_pmovsr &= ~value;
1803     pmu_update_irq(env);
1804 }
1805 
1806 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1807                          uint64_t value)
1808 {
1809     value &= pmu_counter_mask(env);
1810     env->cp15.c9_pmovsr |= value;
1811     pmu_update_irq(env);
1812 }
1813 
1814 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1815                              uint64_t value, const uint8_t counter)
1816 {
1817     if (counter == 31) {
1818         pmccfiltr_write(env, ri, value);
1819     } else if (counter < pmu_num_counters(env)) {
1820         pmevcntr_op_start(env, counter);
1821 
1822         /*
1823          * If this counter's event type is changing, store the current
1824          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1825          * pmevcntr_op_finish has the correct baseline when it converts back to
1826          * a delta.
1827          */
1828         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1829             PMXEVTYPER_EVTCOUNT;
1830         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1831         if (old_event != new_event) {
1832             uint64_t count = 0;
1833             if (event_supported(new_event)) {
1834                 uint16_t event_idx = supported_event_map[new_event];
1835                 count = pm_events[event_idx].get_count(env);
1836             }
1837             env->cp15.c14_pmevcntr_delta[counter] = count;
1838         }
1839 
1840         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1841         pmevcntr_op_finish(env, counter);
1842     }
1843     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1844      * PMSELR value is equal to or greater than the number of implemented
1845      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1846      */
1847 }
1848 
1849 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1850                                const uint8_t counter)
1851 {
1852     if (counter == 31) {
1853         return env->cp15.pmccfiltr_el0;
1854     } else if (counter < pmu_num_counters(env)) {
1855         return env->cp15.c14_pmevtyper[counter];
1856     } else {
1857       /*
1858        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1859        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1860        */
1861         return 0;
1862     }
1863 }
1864 
1865 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1866                               uint64_t value)
1867 {
1868     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1869     pmevtyper_write(env, ri, value, counter);
1870 }
1871 
1872 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1873                                uint64_t value)
1874 {
1875     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1876     env->cp15.c14_pmevtyper[counter] = value;
1877 
1878     /*
1879      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1880      * pmu_op_finish calls when loading saved state for a migration. Because
1881      * we're potentially updating the type of event here, the value written to
1882      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1883      * different counter type. Therefore, we need to set this value to the
1884      * current count for the counter type we're writing so that pmu_op_finish
1885      * has the correct count for its calculation.
1886      */
1887     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1888     if (event_supported(event)) {
1889         uint16_t event_idx = supported_event_map[event];
1890         env->cp15.c14_pmevcntr_delta[counter] =
1891             pm_events[event_idx].get_count(env);
1892     }
1893 }
1894 
1895 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1896 {
1897     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1898     return pmevtyper_read(env, ri, counter);
1899 }
1900 
1901 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1902                              uint64_t value)
1903 {
1904     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1905 }
1906 
1907 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1908 {
1909     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1910 }
1911 
1912 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1913                              uint64_t value, uint8_t counter)
1914 {
1915     if (counter < pmu_num_counters(env)) {
1916         pmevcntr_op_start(env, counter);
1917         env->cp15.c14_pmevcntr[counter] = value;
1918         pmevcntr_op_finish(env, counter);
1919     }
1920     /*
1921      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1922      * are CONSTRAINED UNPREDICTABLE.
1923      */
1924 }
1925 
1926 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1927                               uint8_t counter)
1928 {
1929     if (counter < pmu_num_counters(env)) {
1930         uint64_t ret;
1931         pmevcntr_op_start(env, counter);
1932         ret = env->cp15.c14_pmevcntr[counter];
1933         pmevcntr_op_finish(env, counter);
1934         return ret;
1935     } else {
1936       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1937        * are CONSTRAINED UNPREDICTABLE. */
1938         return 0;
1939     }
1940 }
1941 
1942 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1943                              uint64_t value)
1944 {
1945     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1946     pmevcntr_write(env, ri, value, counter);
1947 }
1948 
1949 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1950 {
1951     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1952     return pmevcntr_read(env, ri, counter);
1953 }
1954 
1955 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1956                              uint64_t value)
1957 {
1958     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1959     assert(counter < pmu_num_counters(env));
1960     env->cp15.c14_pmevcntr[counter] = value;
1961     pmevcntr_write(env, ri, value, counter);
1962 }
1963 
1964 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1965 {
1966     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1967     assert(counter < pmu_num_counters(env));
1968     return env->cp15.c14_pmevcntr[counter];
1969 }
1970 
1971 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1972                              uint64_t value)
1973 {
1974     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1975 }
1976 
1977 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1978 {
1979     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1980 }
1981 
1982 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1983                             uint64_t value)
1984 {
1985     if (arm_feature(env, ARM_FEATURE_V8)) {
1986         env->cp15.c9_pmuserenr = value & 0xf;
1987     } else {
1988         env->cp15.c9_pmuserenr = value & 1;
1989     }
1990 }
1991 
1992 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1993                              uint64_t value)
1994 {
1995     /* We have no event counters so only the C bit can be changed */
1996     value &= pmu_counter_mask(env);
1997     env->cp15.c9_pminten |= value;
1998     pmu_update_irq(env);
1999 }
2000 
2001 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2002                              uint64_t value)
2003 {
2004     value &= pmu_counter_mask(env);
2005     env->cp15.c9_pminten &= ~value;
2006     pmu_update_irq(env);
2007 }
2008 
2009 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
2010                        uint64_t value)
2011 {
2012     /* Note that even though the AArch64 view of this register has bits
2013      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
2014      * architectural requirements for bits which are RES0 only in some
2015      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
2016      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
2017      */
2018     raw_write(env, ri, value & ~0x1FULL);
2019 }
2020 
2021 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
2022 {
2023     /* Begin with base v8.0 state.  */
2024     uint32_t valid_mask = 0x3fff;
2025     ARMCPU *cpu = env_archcpu(env);
2026 
2027     if (ri->state == ARM_CP_STATE_AA64) {
2028         if (arm_feature(env, ARM_FEATURE_AARCH64) &&
2029             !cpu_isar_feature(aa64_aa32_el1, cpu)) {
2030                 value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
2031         }
2032         valid_mask &= ~SCR_NET;
2033 
2034         if (cpu_isar_feature(aa64_lor, cpu)) {
2035             valid_mask |= SCR_TLOR;
2036         }
2037         if (cpu_isar_feature(aa64_pauth, cpu)) {
2038             valid_mask |= SCR_API | SCR_APK;
2039         }
2040         if (cpu_isar_feature(aa64_sel2, cpu)) {
2041             valid_mask |= SCR_EEL2;
2042         }
2043         if (cpu_isar_feature(aa64_mte, cpu)) {
2044             valid_mask |= SCR_ATA;
2045         }
2046     } else {
2047         valid_mask &= ~(SCR_RW | SCR_ST);
2048     }
2049 
2050     if (!arm_feature(env, ARM_FEATURE_EL2)) {
2051         valid_mask &= ~SCR_HCE;
2052 
2053         /* On ARMv7, SMD (or SCD as it is called in v7) is only
2054          * supported if EL2 exists. The bit is UNK/SBZP when
2055          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
2056          * when EL2 is unavailable.
2057          * On ARMv8, this bit is always available.
2058          */
2059         if (arm_feature(env, ARM_FEATURE_V7) &&
2060             !arm_feature(env, ARM_FEATURE_V8)) {
2061             valid_mask &= ~SCR_SMD;
2062         }
2063     }
2064 
2065     /* Clear all-context RES0 bits.  */
2066     value &= valid_mask;
2067     raw_write(env, ri, value);
2068 }
2069 
2070 static void scr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2071 {
2072     /*
2073      * scr_write will set the RES1 bits on an AArch64-only CPU.
2074      * The reset value will be 0x30 on an AArch64-only CPU and 0 otherwise.
2075      */
2076     scr_write(env, ri, 0);
2077 }
2078 
2079 static CPAccessResult access_aa64_tid2(CPUARMState *env,
2080                                        const ARMCPRegInfo *ri,
2081                                        bool isread)
2082 {
2083     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
2084         return CP_ACCESS_TRAP_EL2;
2085     }
2086 
2087     return CP_ACCESS_OK;
2088 }
2089 
2090 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2091 {
2092     ARMCPU *cpu = env_archcpu(env);
2093 
2094     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
2095      * bank
2096      */
2097     uint32_t index = A32_BANKED_REG_GET(env, csselr,
2098                                         ri->secure & ARM_CP_SECSTATE_S);
2099 
2100     return cpu->ccsidr[index];
2101 }
2102 
2103 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2104                          uint64_t value)
2105 {
2106     raw_write(env, ri, value & 0xf);
2107 }
2108 
2109 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2110 {
2111     CPUState *cs = env_cpu(env);
2112     bool el1 = arm_current_el(env) == 1;
2113     uint64_t hcr_el2 = el1 ? arm_hcr_el2_eff(env) : 0;
2114     uint64_t ret = 0;
2115 
2116     if (hcr_el2 & HCR_IMO) {
2117         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
2118             ret |= CPSR_I;
2119         }
2120     } else {
2121         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
2122             ret |= CPSR_I;
2123         }
2124     }
2125 
2126     if (hcr_el2 & HCR_FMO) {
2127         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
2128             ret |= CPSR_F;
2129         }
2130     } else {
2131         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
2132             ret |= CPSR_F;
2133         }
2134     }
2135 
2136     /* External aborts are not possible in QEMU so A bit is always clear */
2137     return ret;
2138 }
2139 
2140 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2141                                        bool isread)
2142 {
2143     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
2144         return CP_ACCESS_TRAP_EL2;
2145     }
2146 
2147     return CP_ACCESS_OK;
2148 }
2149 
2150 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2151                                        bool isread)
2152 {
2153     if (arm_feature(env, ARM_FEATURE_V8)) {
2154         return access_aa64_tid1(env, ri, isread);
2155     }
2156 
2157     return CP_ACCESS_OK;
2158 }
2159 
2160 static const ARMCPRegInfo v7_cp_reginfo[] = {
2161     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
2162     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
2163       .access = PL1_W, .type = ARM_CP_NOP },
2164     /* Performance monitors are implementation defined in v7,
2165      * but with an ARM recommended set of registers, which we
2166      * follow.
2167      *
2168      * Performance registers fall into three categories:
2169      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
2170      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
2171      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
2172      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
2173      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
2174      */
2175     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
2176       .access = PL0_RW, .type = ARM_CP_ALIAS,
2177       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2178       .writefn = pmcntenset_write,
2179       .accessfn = pmreg_access,
2180       .raw_writefn = raw_write },
2181     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
2182       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
2183       .access = PL0_RW, .accessfn = pmreg_access,
2184       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
2185       .writefn = pmcntenset_write, .raw_writefn = raw_write },
2186     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
2187       .access = PL0_RW,
2188       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2189       .accessfn = pmreg_access,
2190       .writefn = pmcntenclr_write,
2191       .type = ARM_CP_ALIAS },
2192     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
2193       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
2194       .access = PL0_RW, .accessfn = pmreg_access,
2195       .type = ARM_CP_ALIAS,
2196       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
2197       .writefn = pmcntenclr_write },
2198     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
2199       .access = PL0_RW, .type = ARM_CP_IO,
2200       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2201       .accessfn = pmreg_access,
2202       .writefn = pmovsr_write,
2203       .raw_writefn = raw_write },
2204     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2205       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2206       .access = PL0_RW, .accessfn = pmreg_access,
2207       .type = ARM_CP_ALIAS | ARM_CP_IO,
2208       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2209       .writefn = pmovsr_write,
2210       .raw_writefn = raw_write },
2211     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2212       .access = PL0_W, .accessfn = pmreg_access_swinc,
2213       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2214       .writefn = pmswinc_write },
2215     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2216       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2217       .access = PL0_W, .accessfn = pmreg_access_swinc,
2218       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2219       .writefn = pmswinc_write },
2220     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2221       .access = PL0_RW, .type = ARM_CP_ALIAS,
2222       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2223       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2224       .raw_writefn = raw_write},
2225     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2226       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2227       .access = PL0_RW, .accessfn = pmreg_access_selr,
2228       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2229       .writefn = pmselr_write, .raw_writefn = raw_write, },
2230     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2231       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2232       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2233       .accessfn = pmreg_access_ccntr },
2234     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2235       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2236       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2237       .type = ARM_CP_IO,
2238       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2239       .readfn = pmccntr_read, .writefn = pmccntr_write,
2240       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2241     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2242       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2243       .access = PL0_RW, .accessfn = pmreg_access,
2244       .type = ARM_CP_ALIAS | ARM_CP_IO,
2245       .resetvalue = 0, },
2246     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2247       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2248       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2249       .access = PL0_RW, .accessfn = pmreg_access,
2250       .type = ARM_CP_IO,
2251       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2252       .resetvalue = 0, },
2253     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2254       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2255       .accessfn = pmreg_access,
2256       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2257     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2258       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2259       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2260       .accessfn = pmreg_access,
2261       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2262     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2263       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2264       .accessfn = pmreg_access_xevcntr,
2265       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2266     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2267       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2268       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2269       .accessfn = pmreg_access_xevcntr,
2270       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2271     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2272       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2273       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2274       .resetvalue = 0,
2275       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2276     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2277       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2278       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2279       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2280       .resetvalue = 0,
2281       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2282     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2283       .access = PL1_RW, .accessfn = access_tpm,
2284       .type = ARM_CP_ALIAS | ARM_CP_IO,
2285       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2286       .resetvalue = 0,
2287       .writefn = pmintenset_write, .raw_writefn = raw_write },
2288     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2289       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2290       .access = PL1_RW, .accessfn = access_tpm,
2291       .type = ARM_CP_IO,
2292       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2293       .writefn = pmintenset_write, .raw_writefn = raw_write,
2294       .resetvalue = 0x0 },
2295     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2296       .access = PL1_RW, .accessfn = access_tpm,
2297       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2298       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2299       .writefn = pmintenclr_write, },
2300     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2301       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2302       .access = PL1_RW, .accessfn = access_tpm,
2303       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2304       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2305       .writefn = pmintenclr_write },
2306     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2307       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2308       .access = PL1_R,
2309       .accessfn = access_aa64_tid2,
2310       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2311     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2312       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2313       .access = PL1_RW,
2314       .accessfn = access_aa64_tid2,
2315       .writefn = csselr_write, .resetvalue = 0,
2316       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2317                              offsetof(CPUARMState, cp15.csselr_ns) } },
2318     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2319      * just RAZ for all cores:
2320      */
2321     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2322       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2323       .access = PL1_R, .type = ARM_CP_CONST,
2324       .accessfn = access_aa64_tid1,
2325       .resetvalue = 0 },
2326     /* Auxiliary fault status registers: these also are IMPDEF, and we
2327      * choose to RAZ/WI for all cores.
2328      */
2329     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2330       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2331       .access = PL1_RW, .accessfn = access_tvm_trvm,
2332       .type = ARM_CP_CONST, .resetvalue = 0 },
2333     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2334       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2335       .access = PL1_RW, .accessfn = access_tvm_trvm,
2336       .type = ARM_CP_CONST, .resetvalue = 0 },
2337     /* MAIR can just read-as-written because we don't implement caches
2338      * and so don't need to care about memory attributes.
2339      */
2340     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2341       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2342       .access = PL1_RW, .accessfn = access_tvm_trvm,
2343       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2344       .resetvalue = 0 },
2345     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2346       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2347       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2348       .resetvalue = 0 },
2349     /* For non-long-descriptor page tables these are PRRR and NMRR;
2350      * regardless they still act as reads-as-written for QEMU.
2351      */
2352      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2353       * allows them to assign the correct fieldoffset based on the endianness
2354       * handled in the field definitions.
2355       */
2356     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2357       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2358       .access = PL1_RW, .accessfn = access_tvm_trvm,
2359       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2360                              offsetof(CPUARMState, cp15.mair0_ns) },
2361       .resetfn = arm_cp_reset_ignore },
2362     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2363       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2364       .access = PL1_RW, .accessfn = access_tvm_trvm,
2365       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2366                              offsetof(CPUARMState, cp15.mair1_ns) },
2367       .resetfn = arm_cp_reset_ignore },
2368     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2369       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2370       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2371     /* 32 bit ITLB invalidates */
2372     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2373       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2374       .writefn = tlbiall_write },
2375     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2376       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2377       .writefn = tlbimva_write },
2378     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2379       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2380       .writefn = tlbiasid_write },
2381     /* 32 bit DTLB invalidates */
2382     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2383       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2384       .writefn = tlbiall_write },
2385     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2386       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2387       .writefn = tlbimva_write },
2388     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2389       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2390       .writefn = tlbiasid_write },
2391     /* 32 bit TLB invalidates */
2392     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2393       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2394       .writefn = tlbiall_write },
2395     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2396       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2397       .writefn = tlbimva_write },
2398     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2399       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2400       .writefn = tlbiasid_write },
2401     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2402       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2403       .writefn = tlbimvaa_write },
2404     REGINFO_SENTINEL
2405 };
2406 
2407 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2408     /* 32 bit TLB invalidates, Inner Shareable */
2409     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2410       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2411       .writefn = tlbiall_is_write },
2412     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2413       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2414       .writefn = tlbimva_is_write },
2415     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2416       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2417       .writefn = tlbiasid_is_write },
2418     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2419       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2420       .writefn = tlbimvaa_is_write },
2421     REGINFO_SENTINEL
2422 };
2423 
2424 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2425     /* PMOVSSET is not implemented in v7 before v7ve */
2426     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2427       .access = PL0_RW, .accessfn = pmreg_access,
2428       .type = ARM_CP_ALIAS | ARM_CP_IO,
2429       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2430       .writefn = pmovsset_write,
2431       .raw_writefn = raw_write },
2432     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2433       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2434       .access = PL0_RW, .accessfn = pmreg_access,
2435       .type = ARM_CP_ALIAS | ARM_CP_IO,
2436       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2437       .writefn = pmovsset_write,
2438       .raw_writefn = raw_write },
2439     REGINFO_SENTINEL
2440 };
2441 
2442 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2443                         uint64_t value)
2444 {
2445     value &= 1;
2446     env->teecr = value;
2447 }
2448 
2449 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2450                                     bool isread)
2451 {
2452     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2453         return CP_ACCESS_TRAP;
2454     }
2455     return CP_ACCESS_OK;
2456 }
2457 
2458 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2459     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2460       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2461       .resetvalue = 0,
2462       .writefn = teecr_write },
2463     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2464       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2465       .accessfn = teehbr_access, .resetvalue = 0 },
2466     REGINFO_SENTINEL
2467 };
2468 
2469 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2470     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2471       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2472       .access = PL0_RW,
2473       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2474     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2475       .access = PL0_RW,
2476       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2477                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2478       .resetfn = arm_cp_reset_ignore },
2479     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2480       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2481       .access = PL0_R|PL1_W,
2482       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2483       .resetvalue = 0},
2484     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2485       .access = PL0_R|PL1_W,
2486       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2487                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2488       .resetfn = arm_cp_reset_ignore },
2489     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2490       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2491       .access = PL1_RW,
2492       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2493     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2494       .access = PL1_RW,
2495       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2496                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2497       .resetvalue = 0 },
2498     REGINFO_SENTINEL
2499 };
2500 
2501 #ifndef CONFIG_USER_ONLY
2502 
2503 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2504                                        bool isread)
2505 {
2506     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2507      * Writable only at the highest implemented exception level.
2508      */
2509     int el = arm_current_el(env);
2510     uint64_t hcr;
2511     uint32_t cntkctl;
2512 
2513     switch (el) {
2514     case 0:
2515         hcr = arm_hcr_el2_eff(env);
2516         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2517             cntkctl = env->cp15.cnthctl_el2;
2518         } else {
2519             cntkctl = env->cp15.c14_cntkctl;
2520         }
2521         if (!extract32(cntkctl, 0, 2)) {
2522             return CP_ACCESS_TRAP;
2523         }
2524         break;
2525     case 1:
2526         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2527             arm_is_secure_below_el3(env)) {
2528             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2529             return CP_ACCESS_TRAP_UNCATEGORIZED;
2530         }
2531         break;
2532     case 2:
2533     case 3:
2534         break;
2535     }
2536 
2537     if (!isread && el < arm_highest_el(env)) {
2538         return CP_ACCESS_TRAP_UNCATEGORIZED;
2539     }
2540 
2541     return CP_ACCESS_OK;
2542 }
2543 
2544 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2545                                         bool isread)
2546 {
2547     unsigned int cur_el = arm_current_el(env);
2548     bool has_el2 = arm_is_el2_enabled(env);
2549     uint64_t hcr = arm_hcr_el2_eff(env);
2550 
2551     switch (cur_el) {
2552     case 0:
2553         /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2554         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2555             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2556                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2557         }
2558 
2559         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2560         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2561             return CP_ACCESS_TRAP;
2562         }
2563 
2564         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2565         if (hcr & HCR_E2H) {
2566             if (timeridx == GTIMER_PHYS &&
2567                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2568                 return CP_ACCESS_TRAP_EL2;
2569             }
2570         } else {
2571             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2572             if (has_el2 && timeridx == GTIMER_PHYS &&
2573                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2574                 return CP_ACCESS_TRAP_EL2;
2575             }
2576         }
2577         break;
2578 
2579     case 1:
2580         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2581         if (has_el2 && timeridx == GTIMER_PHYS &&
2582             (hcr & HCR_E2H
2583              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2584              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2585             return CP_ACCESS_TRAP_EL2;
2586         }
2587         break;
2588     }
2589     return CP_ACCESS_OK;
2590 }
2591 
2592 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2593                                       bool isread)
2594 {
2595     unsigned int cur_el = arm_current_el(env);
2596     bool has_el2 = arm_is_el2_enabled(env);
2597     uint64_t hcr = arm_hcr_el2_eff(env);
2598 
2599     switch (cur_el) {
2600     case 0:
2601         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2602             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2603             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2604                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2605         }
2606 
2607         /*
2608          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2609          * EL0 if EL0[PV]TEN is zero.
2610          */
2611         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2612             return CP_ACCESS_TRAP;
2613         }
2614         /* fall through */
2615 
2616     case 1:
2617         if (has_el2 && timeridx == GTIMER_PHYS) {
2618             if (hcr & HCR_E2H) {
2619                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2620                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2621                     return CP_ACCESS_TRAP_EL2;
2622                 }
2623             } else {
2624                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2625                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2626                     return CP_ACCESS_TRAP_EL2;
2627                 }
2628             }
2629         }
2630         break;
2631     }
2632     return CP_ACCESS_OK;
2633 }
2634 
2635 static CPAccessResult gt_pct_access(CPUARMState *env,
2636                                     const ARMCPRegInfo *ri,
2637                                     bool isread)
2638 {
2639     return gt_counter_access(env, GTIMER_PHYS, isread);
2640 }
2641 
2642 static CPAccessResult gt_vct_access(CPUARMState *env,
2643                                     const ARMCPRegInfo *ri,
2644                                     bool isread)
2645 {
2646     return gt_counter_access(env, GTIMER_VIRT, isread);
2647 }
2648 
2649 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2650                                        bool isread)
2651 {
2652     return gt_timer_access(env, GTIMER_PHYS, isread);
2653 }
2654 
2655 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2656                                        bool isread)
2657 {
2658     return gt_timer_access(env, GTIMER_VIRT, isread);
2659 }
2660 
2661 static CPAccessResult gt_stimer_access(CPUARMState *env,
2662                                        const ARMCPRegInfo *ri,
2663                                        bool isread)
2664 {
2665     /* The AArch64 register view of the secure physical timer is
2666      * always accessible from EL3, and configurably accessible from
2667      * Secure EL1.
2668      */
2669     switch (arm_current_el(env)) {
2670     case 1:
2671         if (!arm_is_secure(env)) {
2672             return CP_ACCESS_TRAP;
2673         }
2674         if (!(env->cp15.scr_el3 & SCR_ST)) {
2675             return CP_ACCESS_TRAP_EL3;
2676         }
2677         return CP_ACCESS_OK;
2678     case 0:
2679     case 2:
2680         return CP_ACCESS_TRAP;
2681     case 3:
2682         return CP_ACCESS_OK;
2683     default:
2684         g_assert_not_reached();
2685     }
2686 }
2687 
2688 static uint64_t gt_get_countervalue(CPUARMState *env)
2689 {
2690     ARMCPU *cpu = env_archcpu(env);
2691 
2692     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2693 }
2694 
2695 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2696 {
2697     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2698 
2699     if (gt->ctl & 1) {
2700         /* Timer enabled: calculate and set current ISTATUS, irq, and
2701          * reset timer to when ISTATUS next has to change
2702          */
2703         uint64_t offset = timeridx == GTIMER_VIRT ?
2704                                       cpu->env.cp15.cntvoff_el2 : 0;
2705         uint64_t count = gt_get_countervalue(&cpu->env);
2706         /* Note that this must be unsigned 64 bit arithmetic: */
2707         int istatus = count - offset >= gt->cval;
2708         uint64_t nexttick;
2709         int irqstate;
2710 
2711         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2712 
2713         irqstate = (istatus && !(gt->ctl & 2));
2714         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2715 
2716         if (istatus) {
2717             /* Next transition is when count rolls back over to zero */
2718             nexttick = UINT64_MAX;
2719         } else {
2720             /* Next transition is when we hit cval */
2721             nexttick = gt->cval + offset;
2722         }
2723         /* Note that the desired next expiry time might be beyond the
2724          * signed-64-bit range of a QEMUTimer -- in this case we just
2725          * set the timer for as far in the future as possible. When the
2726          * timer expires we will reset the timer for any remaining period.
2727          */
2728         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2729             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2730         } else {
2731             timer_mod(cpu->gt_timer[timeridx], nexttick);
2732         }
2733         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2734     } else {
2735         /* Timer disabled: ISTATUS and timer output always clear */
2736         gt->ctl &= ~4;
2737         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2738         timer_del(cpu->gt_timer[timeridx]);
2739         trace_arm_gt_recalc_disabled(timeridx);
2740     }
2741 }
2742 
2743 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2744                            int timeridx)
2745 {
2746     ARMCPU *cpu = env_archcpu(env);
2747 
2748     timer_del(cpu->gt_timer[timeridx]);
2749 }
2750 
2751 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2752 {
2753     return gt_get_countervalue(env);
2754 }
2755 
2756 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2757 {
2758     uint64_t hcr;
2759 
2760     switch (arm_current_el(env)) {
2761     case 2:
2762         hcr = arm_hcr_el2_eff(env);
2763         if (hcr & HCR_E2H) {
2764             return 0;
2765         }
2766         break;
2767     case 0:
2768         hcr = arm_hcr_el2_eff(env);
2769         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2770             return 0;
2771         }
2772         break;
2773     }
2774 
2775     return env->cp15.cntvoff_el2;
2776 }
2777 
2778 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2779 {
2780     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2781 }
2782 
2783 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2784                           int timeridx,
2785                           uint64_t value)
2786 {
2787     trace_arm_gt_cval_write(timeridx, value);
2788     env->cp15.c14_timer[timeridx].cval = value;
2789     gt_recalc_timer(env_archcpu(env), timeridx);
2790 }
2791 
2792 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2793                              int timeridx)
2794 {
2795     uint64_t offset = 0;
2796 
2797     switch (timeridx) {
2798     case GTIMER_VIRT:
2799     case GTIMER_HYPVIRT:
2800         offset = gt_virt_cnt_offset(env);
2801         break;
2802     }
2803 
2804     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2805                       (gt_get_countervalue(env) - offset));
2806 }
2807 
2808 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2809                           int timeridx,
2810                           uint64_t value)
2811 {
2812     uint64_t offset = 0;
2813 
2814     switch (timeridx) {
2815     case GTIMER_VIRT:
2816     case GTIMER_HYPVIRT:
2817         offset = gt_virt_cnt_offset(env);
2818         break;
2819     }
2820 
2821     trace_arm_gt_tval_write(timeridx, value);
2822     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2823                                          sextract64(value, 0, 32);
2824     gt_recalc_timer(env_archcpu(env), timeridx);
2825 }
2826 
2827 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2828                          int timeridx,
2829                          uint64_t value)
2830 {
2831     ARMCPU *cpu = env_archcpu(env);
2832     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2833 
2834     trace_arm_gt_ctl_write(timeridx, value);
2835     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2836     if ((oldval ^ value) & 1) {
2837         /* Enable toggled */
2838         gt_recalc_timer(cpu, timeridx);
2839     } else if ((oldval ^ value) & 2) {
2840         /* IMASK toggled: don't need to recalculate,
2841          * just set the interrupt line based on ISTATUS
2842          */
2843         int irqstate = (oldval & 4) && !(value & 2);
2844 
2845         trace_arm_gt_imask_toggle(timeridx, irqstate);
2846         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2847     }
2848 }
2849 
2850 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2851 {
2852     gt_timer_reset(env, ri, GTIMER_PHYS);
2853 }
2854 
2855 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2856                                uint64_t value)
2857 {
2858     gt_cval_write(env, ri, GTIMER_PHYS, value);
2859 }
2860 
2861 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2862 {
2863     return gt_tval_read(env, ri, GTIMER_PHYS);
2864 }
2865 
2866 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2867                                uint64_t value)
2868 {
2869     gt_tval_write(env, ri, GTIMER_PHYS, value);
2870 }
2871 
2872 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2873                               uint64_t value)
2874 {
2875     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2876 }
2877 
2878 static int gt_phys_redir_timeridx(CPUARMState *env)
2879 {
2880     switch (arm_mmu_idx(env)) {
2881     case ARMMMUIdx_E20_0:
2882     case ARMMMUIdx_E20_2:
2883     case ARMMMUIdx_E20_2_PAN:
2884     case ARMMMUIdx_SE20_0:
2885     case ARMMMUIdx_SE20_2:
2886     case ARMMMUIdx_SE20_2_PAN:
2887         return GTIMER_HYP;
2888     default:
2889         return GTIMER_PHYS;
2890     }
2891 }
2892 
2893 static int gt_virt_redir_timeridx(CPUARMState *env)
2894 {
2895     switch (arm_mmu_idx(env)) {
2896     case ARMMMUIdx_E20_0:
2897     case ARMMMUIdx_E20_2:
2898     case ARMMMUIdx_E20_2_PAN:
2899     case ARMMMUIdx_SE20_0:
2900     case ARMMMUIdx_SE20_2:
2901     case ARMMMUIdx_SE20_2_PAN:
2902         return GTIMER_HYPVIRT;
2903     default:
2904         return GTIMER_VIRT;
2905     }
2906 }
2907 
2908 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2909                                         const ARMCPRegInfo *ri)
2910 {
2911     int timeridx = gt_phys_redir_timeridx(env);
2912     return env->cp15.c14_timer[timeridx].cval;
2913 }
2914 
2915 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2916                                      uint64_t value)
2917 {
2918     int timeridx = gt_phys_redir_timeridx(env);
2919     gt_cval_write(env, ri, timeridx, value);
2920 }
2921 
2922 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2923                                         const ARMCPRegInfo *ri)
2924 {
2925     int timeridx = gt_phys_redir_timeridx(env);
2926     return gt_tval_read(env, ri, timeridx);
2927 }
2928 
2929 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2930                                      uint64_t value)
2931 {
2932     int timeridx = gt_phys_redir_timeridx(env);
2933     gt_tval_write(env, ri, timeridx, value);
2934 }
2935 
2936 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2937                                        const ARMCPRegInfo *ri)
2938 {
2939     int timeridx = gt_phys_redir_timeridx(env);
2940     return env->cp15.c14_timer[timeridx].ctl;
2941 }
2942 
2943 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2944                                     uint64_t value)
2945 {
2946     int timeridx = gt_phys_redir_timeridx(env);
2947     gt_ctl_write(env, ri, timeridx, value);
2948 }
2949 
2950 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2951 {
2952     gt_timer_reset(env, ri, GTIMER_VIRT);
2953 }
2954 
2955 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2956                                uint64_t value)
2957 {
2958     gt_cval_write(env, ri, GTIMER_VIRT, value);
2959 }
2960 
2961 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2962 {
2963     return gt_tval_read(env, ri, GTIMER_VIRT);
2964 }
2965 
2966 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2967                                uint64_t value)
2968 {
2969     gt_tval_write(env, ri, GTIMER_VIRT, value);
2970 }
2971 
2972 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2973                               uint64_t value)
2974 {
2975     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2976 }
2977 
2978 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2979                               uint64_t value)
2980 {
2981     ARMCPU *cpu = env_archcpu(env);
2982 
2983     trace_arm_gt_cntvoff_write(value);
2984     raw_write(env, ri, value);
2985     gt_recalc_timer(cpu, GTIMER_VIRT);
2986 }
2987 
2988 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
2989                                         const ARMCPRegInfo *ri)
2990 {
2991     int timeridx = gt_virt_redir_timeridx(env);
2992     return env->cp15.c14_timer[timeridx].cval;
2993 }
2994 
2995 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2996                                      uint64_t value)
2997 {
2998     int timeridx = gt_virt_redir_timeridx(env);
2999     gt_cval_write(env, ri, timeridx, value);
3000 }
3001 
3002 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
3003                                         const ARMCPRegInfo *ri)
3004 {
3005     int timeridx = gt_virt_redir_timeridx(env);
3006     return gt_tval_read(env, ri, timeridx);
3007 }
3008 
3009 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3010                                      uint64_t value)
3011 {
3012     int timeridx = gt_virt_redir_timeridx(env);
3013     gt_tval_write(env, ri, timeridx, value);
3014 }
3015 
3016 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
3017                                        const ARMCPRegInfo *ri)
3018 {
3019     int timeridx = gt_virt_redir_timeridx(env);
3020     return env->cp15.c14_timer[timeridx].ctl;
3021 }
3022 
3023 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3024                                     uint64_t value)
3025 {
3026     int timeridx = gt_virt_redir_timeridx(env);
3027     gt_ctl_write(env, ri, timeridx, value);
3028 }
3029 
3030 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3031 {
3032     gt_timer_reset(env, ri, GTIMER_HYP);
3033 }
3034 
3035 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3036                               uint64_t value)
3037 {
3038     gt_cval_write(env, ri, GTIMER_HYP, value);
3039 }
3040 
3041 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3042 {
3043     return gt_tval_read(env, ri, GTIMER_HYP);
3044 }
3045 
3046 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3047                               uint64_t value)
3048 {
3049     gt_tval_write(env, ri, GTIMER_HYP, value);
3050 }
3051 
3052 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3053                               uint64_t value)
3054 {
3055     gt_ctl_write(env, ri, GTIMER_HYP, value);
3056 }
3057 
3058 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3059 {
3060     gt_timer_reset(env, ri, GTIMER_SEC);
3061 }
3062 
3063 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3064                               uint64_t value)
3065 {
3066     gt_cval_write(env, ri, GTIMER_SEC, value);
3067 }
3068 
3069 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3070 {
3071     return gt_tval_read(env, ri, GTIMER_SEC);
3072 }
3073 
3074 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3075                               uint64_t value)
3076 {
3077     gt_tval_write(env, ri, GTIMER_SEC, value);
3078 }
3079 
3080 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3081                               uint64_t value)
3082 {
3083     gt_ctl_write(env, ri, GTIMER_SEC, value);
3084 }
3085 
3086 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3087 {
3088     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
3089 }
3090 
3091 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3092                              uint64_t value)
3093 {
3094     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
3095 }
3096 
3097 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3098 {
3099     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
3100 }
3101 
3102 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3103                              uint64_t value)
3104 {
3105     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
3106 }
3107 
3108 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3109                             uint64_t value)
3110 {
3111     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
3112 }
3113 
3114 void arm_gt_ptimer_cb(void *opaque)
3115 {
3116     ARMCPU *cpu = opaque;
3117 
3118     gt_recalc_timer(cpu, GTIMER_PHYS);
3119 }
3120 
3121 void arm_gt_vtimer_cb(void *opaque)
3122 {
3123     ARMCPU *cpu = opaque;
3124 
3125     gt_recalc_timer(cpu, GTIMER_VIRT);
3126 }
3127 
3128 void arm_gt_htimer_cb(void *opaque)
3129 {
3130     ARMCPU *cpu = opaque;
3131 
3132     gt_recalc_timer(cpu, GTIMER_HYP);
3133 }
3134 
3135 void arm_gt_stimer_cb(void *opaque)
3136 {
3137     ARMCPU *cpu = opaque;
3138 
3139     gt_recalc_timer(cpu, GTIMER_SEC);
3140 }
3141 
3142 void arm_gt_hvtimer_cb(void *opaque)
3143 {
3144     ARMCPU *cpu = opaque;
3145 
3146     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
3147 }
3148 
3149 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
3150 {
3151     ARMCPU *cpu = env_archcpu(env);
3152 
3153     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
3154 }
3155 
3156 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3157     /* Note that CNTFRQ is purely reads-as-written for the benefit
3158      * of software; writing it doesn't actually change the timer frequency.
3159      * Our reset value matches the fixed frequency we implement the timer at.
3160      */
3161     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
3162       .type = ARM_CP_ALIAS,
3163       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3164       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
3165     },
3166     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3167       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3168       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3169       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3170       .resetfn = arm_gt_cntfrq_reset,
3171     },
3172     /* overall control: mostly access permissions */
3173     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
3174       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
3175       .access = PL1_RW,
3176       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
3177       .resetvalue = 0,
3178     },
3179     /* per-timer control */
3180     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3181       .secure = ARM_CP_SECSTATE_NS,
3182       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3183       .accessfn = gt_ptimer_access,
3184       .fieldoffset = offsetoflow32(CPUARMState,
3185                                    cp15.c14_timer[GTIMER_PHYS].ctl),
3186       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3187       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3188     },
3189     { .name = "CNTP_CTL_S",
3190       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3191       .secure = ARM_CP_SECSTATE_S,
3192       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3193       .accessfn = gt_ptimer_access,
3194       .fieldoffset = offsetoflow32(CPUARMState,
3195                                    cp15.c14_timer[GTIMER_SEC].ctl),
3196       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3197     },
3198     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
3199       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
3200       .type = ARM_CP_IO, .access = PL0_RW,
3201       .accessfn = gt_ptimer_access,
3202       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
3203       .resetvalue = 0,
3204       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3205       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3206     },
3207     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
3208       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3209       .accessfn = gt_vtimer_access,
3210       .fieldoffset = offsetoflow32(CPUARMState,
3211                                    cp15.c14_timer[GTIMER_VIRT].ctl),
3212       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3213       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3214     },
3215     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
3216       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
3217       .type = ARM_CP_IO, .access = PL0_RW,
3218       .accessfn = gt_vtimer_access,
3219       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
3220       .resetvalue = 0,
3221       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3222       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3223     },
3224     /* TimerValue views: a 32 bit downcounting view of the underlying state */
3225     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3226       .secure = ARM_CP_SECSTATE_NS,
3227       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3228       .accessfn = gt_ptimer_access,
3229       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3230     },
3231     { .name = "CNTP_TVAL_S",
3232       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3233       .secure = ARM_CP_SECSTATE_S,
3234       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3235       .accessfn = gt_ptimer_access,
3236       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
3237     },
3238     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3239       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
3240       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3241       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
3242       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3243     },
3244     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
3245       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3246       .accessfn = gt_vtimer_access,
3247       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3248     },
3249     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3250       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
3251       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3252       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
3253       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3254     },
3255     /* The counter itself */
3256     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
3257       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3258       .accessfn = gt_pct_access,
3259       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
3260     },
3261     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
3262       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
3263       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3264       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
3265     },
3266     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3267       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3268       .accessfn = gt_vct_access,
3269       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3270     },
3271     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3272       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3273       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3274       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3275     },
3276     /* Comparison value, indicating when the timer goes off */
3277     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3278       .secure = ARM_CP_SECSTATE_NS,
3279       .access = PL0_RW,
3280       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3281       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3282       .accessfn = gt_ptimer_access,
3283       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3284       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3285     },
3286     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3287       .secure = ARM_CP_SECSTATE_S,
3288       .access = PL0_RW,
3289       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3290       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3291       .accessfn = gt_ptimer_access,
3292       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3293     },
3294     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3295       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3296       .access = PL0_RW,
3297       .type = ARM_CP_IO,
3298       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3299       .resetvalue = 0, .accessfn = gt_ptimer_access,
3300       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3301       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3302     },
3303     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3304       .access = PL0_RW,
3305       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3306       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3307       .accessfn = gt_vtimer_access,
3308       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3309       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3310     },
3311     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3312       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3313       .access = PL0_RW,
3314       .type = ARM_CP_IO,
3315       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3316       .resetvalue = 0, .accessfn = gt_vtimer_access,
3317       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3318       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3319     },
3320     /* Secure timer -- this is actually restricted to only EL3
3321      * and configurably Secure-EL1 via the accessfn.
3322      */
3323     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3324       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3325       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3326       .accessfn = gt_stimer_access,
3327       .readfn = gt_sec_tval_read,
3328       .writefn = gt_sec_tval_write,
3329       .resetfn = gt_sec_timer_reset,
3330     },
3331     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3332       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3333       .type = ARM_CP_IO, .access = PL1_RW,
3334       .accessfn = gt_stimer_access,
3335       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3336       .resetvalue = 0,
3337       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3338     },
3339     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3340       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3341       .type = ARM_CP_IO, .access = PL1_RW,
3342       .accessfn = gt_stimer_access,
3343       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3344       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3345     },
3346     REGINFO_SENTINEL
3347 };
3348 
3349 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3350                                  bool isread)
3351 {
3352     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3353         return CP_ACCESS_TRAP;
3354     }
3355     return CP_ACCESS_OK;
3356 }
3357 
3358 #else
3359 
3360 /* In user-mode most of the generic timer registers are inaccessible
3361  * however modern kernels (4.12+) allow access to cntvct_el0
3362  */
3363 
3364 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3365 {
3366     ARMCPU *cpu = env_archcpu(env);
3367 
3368     /* Currently we have no support for QEMUTimer in linux-user so we
3369      * can't call gt_get_countervalue(env), instead we directly
3370      * call the lower level functions.
3371      */
3372     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3373 }
3374 
3375 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3376     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3377       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3378       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3379       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3380       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3381     },
3382     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3383       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3384       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3385       .readfn = gt_virt_cnt_read,
3386     },
3387     REGINFO_SENTINEL
3388 };
3389 
3390 #endif
3391 
3392 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3393 {
3394     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3395         raw_write(env, ri, value);
3396     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3397         raw_write(env, ri, value & 0xfffff6ff);
3398     } else {
3399         raw_write(env, ri, value & 0xfffff1ff);
3400     }
3401 }
3402 
3403 #ifndef CONFIG_USER_ONLY
3404 /* get_phys_addr() isn't present for user-mode-only targets */
3405 
3406 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3407                                  bool isread)
3408 {
3409     if (ri->opc2 & 4) {
3410         /* The ATS12NSO* operations must trap to EL3 or EL2 if executed in
3411          * Secure EL1 (which can only happen if EL3 is AArch64).
3412          * They are simply UNDEF if executed from NS EL1.
3413          * They function normally from EL2 or EL3.
3414          */
3415         if (arm_current_el(env) == 1) {
3416             if (arm_is_secure_below_el3(env)) {
3417                 if (env->cp15.scr_el3 & SCR_EEL2) {
3418                     return CP_ACCESS_TRAP_UNCATEGORIZED_EL2;
3419                 }
3420                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3421             }
3422             return CP_ACCESS_TRAP_UNCATEGORIZED;
3423         }
3424     }
3425     return CP_ACCESS_OK;
3426 }
3427 
3428 #ifdef CONFIG_TCG
3429 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3430                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3431 {
3432     hwaddr phys_addr;
3433     target_ulong page_size;
3434     int prot;
3435     bool ret;
3436     uint64_t par64;
3437     bool format64 = false;
3438     MemTxAttrs attrs = {};
3439     ARMMMUFaultInfo fi = {};
3440     ARMCacheAttrs cacheattrs = {};
3441 
3442     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3443                         &prot, &page_size, &fi, &cacheattrs);
3444 
3445     if (ret) {
3446         /*
3447          * Some kinds of translation fault must cause exceptions rather
3448          * than being reported in the PAR.
3449          */
3450         int current_el = arm_current_el(env);
3451         int target_el;
3452         uint32_t syn, fsr, fsc;
3453         bool take_exc = false;
3454 
3455         if (fi.s1ptw && current_el == 1
3456             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3457             /*
3458              * Synchronous stage 2 fault on an access made as part of the
3459              * translation table walk for AT S1E0* or AT S1E1* insn
3460              * executed from NS EL1. If this is a synchronous external abort
3461              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3462              * to EL3. Otherwise the fault is taken as an exception to EL2,
3463              * and HPFAR_EL2 holds the faulting IPA.
3464              */
3465             if (fi.type == ARMFault_SyncExternalOnWalk &&
3466                 (env->cp15.scr_el3 & SCR_EA)) {
3467                 target_el = 3;
3468             } else {
3469                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3470                 if (arm_is_secure_below_el3(env) && fi.s1ns) {
3471                     env->cp15.hpfar_el2 |= HPFAR_NS;
3472                 }
3473                 target_el = 2;
3474             }
3475             take_exc = true;
3476         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3477             /*
3478              * Synchronous external aborts during a translation table walk
3479              * are taken as Data Abort exceptions.
3480              */
3481             if (fi.stage2) {
3482                 if (current_el == 3) {
3483                     target_el = 3;
3484                 } else {
3485                     target_el = 2;
3486                 }
3487             } else {
3488                 target_el = exception_target_el(env);
3489             }
3490             take_exc = true;
3491         }
3492 
3493         if (take_exc) {
3494             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3495             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3496                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3497                 fsr = arm_fi_to_lfsc(&fi);
3498                 fsc = extract32(fsr, 0, 6);
3499             } else {
3500                 fsr = arm_fi_to_sfsc(&fi);
3501                 fsc = 0x3f;
3502             }
3503             /*
3504              * Report exception with ESR indicating a fault due to a
3505              * translation table walk for a cache maintenance instruction.
3506              */
3507             syn = syn_data_abort_no_iss(current_el == target_el, 0,
3508                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3509             env->exception.vaddress = value;
3510             env->exception.fsr = fsr;
3511             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3512         }
3513     }
3514 
3515     if (is_a64(env)) {
3516         format64 = true;
3517     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3518         /*
3519          * ATS1Cxx:
3520          * * TTBCR.EAE determines whether the result is returned using the
3521          *   32-bit or the 64-bit PAR format
3522          * * Instructions executed in Hyp mode always use the 64bit format
3523          *
3524          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3525          * * The Non-secure TTBCR.EAE bit is set to 1
3526          * * The implementation includes EL2, and the value of HCR.VM is 1
3527          *
3528          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3529          *
3530          * ATS1Hx always uses the 64bit format.
3531          */
3532         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3533 
3534         if (arm_feature(env, ARM_FEATURE_EL2)) {
3535             if (mmu_idx == ARMMMUIdx_E10_0 ||
3536                 mmu_idx == ARMMMUIdx_E10_1 ||
3537                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3538                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3539             } else {
3540                 format64 |= arm_current_el(env) == 2;
3541             }
3542         }
3543     }
3544 
3545     if (format64) {
3546         /* Create a 64-bit PAR */
3547         par64 = (1 << 11); /* LPAE bit always set */
3548         if (!ret) {
3549             par64 |= phys_addr & ~0xfffULL;
3550             if (!attrs.secure) {
3551                 par64 |= (1 << 9); /* NS */
3552             }
3553             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3554             par64 |= cacheattrs.shareability << 7; /* SH */
3555         } else {
3556             uint32_t fsr = arm_fi_to_lfsc(&fi);
3557 
3558             par64 |= 1; /* F */
3559             par64 |= (fsr & 0x3f) << 1; /* FS */
3560             if (fi.stage2) {
3561                 par64 |= (1 << 9); /* S */
3562             }
3563             if (fi.s1ptw) {
3564                 par64 |= (1 << 8); /* PTW */
3565             }
3566         }
3567     } else {
3568         /* fsr is a DFSR/IFSR value for the short descriptor
3569          * translation table format (with WnR always clear).
3570          * Convert it to a 32-bit PAR.
3571          */
3572         if (!ret) {
3573             /* We do not set any attribute bits in the PAR */
3574             if (page_size == (1 << 24)
3575                 && arm_feature(env, ARM_FEATURE_V7)) {
3576                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3577             } else {
3578                 par64 = phys_addr & 0xfffff000;
3579             }
3580             if (!attrs.secure) {
3581                 par64 |= (1 << 9); /* NS */
3582             }
3583         } else {
3584             uint32_t fsr = arm_fi_to_sfsc(&fi);
3585 
3586             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3587                     ((fsr & 0xf) << 1) | 1;
3588         }
3589     }
3590     return par64;
3591 }
3592 #endif /* CONFIG_TCG */
3593 
3594 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3595 {
3596 #ifdef CONFIG_TCG
3597     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3598     uint64_t par64;
3599     ARMMMUIdx mmu_idx;
3600     int el = arm_current_el(env);
3601     bool secure = arm_is_secure_below_el3(env);
3602 
3603     switch (ri->opc2 & 6) {
3604     case 0:
3605         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3606         switch (el) {
3607         case 3:
3608             mmu_idx = ARMMMUIdx_SE3;
3609             break;
3610         case 2:
3611             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3612             /* fall through */
3613         case 1:
3614             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3615                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3616                            : ARMMMUIdx_Stage1_E1_PAN);
3617             } else {
3618                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3619             }
3620             break;
3621         default:
3622             g_assert_not_reached();
3623         }
3624         break;
3625     case 2:
3626         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3627         switch (el) {
3628         case 3:
3629             mmu_idx = ARMMMUIdx_SE10_0;
3630             break;
3631         case 2:
3632             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3633             mmu_idx = ARMMMUIdx_Stage1_E0;
3634             break;
3635         case 1:
3636             mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3637             break;
3638         default:
3639             g_assert_not_reached();
3640         }
3641         break;
3642     case 4:
3643         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3644         mmu_idx = ARMMMUIdx_E10_1;
3645         break;
3646     case 6:
3647         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3648         mmu_idx = ARMMMUIdx_E10_0;
3649         break;
3650     default:
3651         g_assert_not_reached();
3652     }
3653 
3654     par64 = do_ats_write(env, value, access_type, mmu_idx);
3655 
3656     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3657 #else
3658     /* Handled by hardware accelerator. */
3659     g_assert_not_reached();
3660 #endif /* CONFIG_TCG */
3661 }
3662 
3663 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3664                         uint64_t value)
3665 {
3666 #ifdef CONFIG_TCG
3667     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3668     uint64_t par64;
3669 
3670     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3671 
3672     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3673 #else
3674     /* Handled by hardware accelerator. */
3675     g_assert_not_reached();
3676 #endif /* CONFIG_TCG */
3677 }
3678 
3679 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3680                                      bool isread)
3681 {
3682     if (arm_current_el(env) == 3 &&
3683         !(env->cp15.scr_el3 & (SCR_NS | SCR_EEL2))) {
3684         return CP_ACCESS_TRAP;
3685     }
3686     return CP_ACCESS_OK;
3687 }
3688 
3689 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3690                         uint64_t value)
3691 {
3692 #ifdef CONFIG_TCG
3693     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3694     ARMMMUIdx mmu_idx;
3695     int secure = arm_is_secure_below_el3(env);
3696 
3697     switch (ri->opc2 & 6) {
3698     case 0:
3699         switch (ri->opc1) {
3700         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3701             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3702                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3703                            : ARMMMUIdx_Stage1_E1_PAN);
3704             } else {
3705                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3706             }
3707             break;
3708         case 4: /* AT S1E2R, AT S1E2W */
3709             mmu_idx = secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2;
3710             break;
3711         case 6: /* AT S1E3R, AT S1E3W */
3712             mmu_idx = ARMMMUIdx_SE3;
3713             break;
3714         default:
3715             g_assert_not_reached();
3716         }
3717         break;
3718     case 2: /* AT S1E0R, AT S1E0W */
3719         mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3720         break;
3721     case 4: /* AT S12E1R, AT S12E1W */
3722         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3723         break;
3724     case 6: /* AT S12E0R, AT S12E0W */
3725         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3726         break;
3727     default:
3728         g_assert_not_reached();
3729     }
3730 
3731     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3732 #else
3733     /* Handled by hardware accelerator. */
3734     g_assert_not_reached();
3735 #endif /* CONFIG_TCG */
3736 }
3737 #endif
3738 
3739 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3740     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3741       .access = PL1_RW, .resetvalue = 0,
3742       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3743                              offsetoflow32(CPUARMState, cp15.par_ns) },
3744       .writefn = par_write },
3745 #ifndef CONFIG_USER_ONLY
3746     /* This underdecoding is safe because the reginfo is NO_RAW. */
3747     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3748       .access = PL1_W, .accessfn = ats_access,
3749       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3750 #endif
3751     REGINFO_SENTINEL
3752 };
3753 
3754 /* Return basic MPU access permission bits.  */
3755 static uint32_t simple_mpu_ap_bits(uint32_t val)
3756 {
3757     uint32_t ret;
3758     uint32_t mask;
3759     int i;
3760     ret = 0;
3761     mask = 3;
3762     for (i = 0; i < 16; i += 2) {
3763         ret |= (val >> i) & mask;
3764         mask <<= 2;
3765     }
3766     return ret;
3767 }
3768 
3769 /* Pad basic MPU access permission bits to extended format.  */
3770 static uint32_t extended_mpu_ap_bits(uint32_t val)
3771 {
3772     uint32_t ret;
3773     uint32_t mask;
3774     int i;
3775     ret = 0;
3776     mask = 3;
3777     for (i = 0; i < 16; i += 2) {
3778         ret |= (val & mask) << i;
3779         mask <<= 2;
3780     }
3781     return ret;
3782 }
3783 
3784 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3785                                  uint64_t value)
3786 {
3787     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3788 }
3789 
3790 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3791 {
3792     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3793 }
3794 
3795 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3796                                  uint64_t value)
3797 {
3798     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3799 }
3800 
3801 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3802 {
3803     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3804 }
3805 
3806 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3807 {
3808     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3809 
3810     if (!u32p) {
3811         return 0;
3812     }
3813 
3814     u32p += env->pmsav7.rnr[M_REG_NS];
3815     return *u32p;
3816 }
3817 
3818 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3819                          uint64_t value)
3820 {
3821     ARMCPU *cpu = env_archcpu(env);
3822     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3823 
3824     if (!u32p) {
3825         return;
3826     }
3827 
3828     u32p += env->pmsav7.rnr[M_REG_NS];
3829     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3830     *u32p = value;
3831 }
3832 
3833 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3834                               uint64_t value)
3835 {
3836     ARMCPU *cpu = env_archcpu(env);
3837     uint32_t nrgs = cpu->pmsav7_dregion;
3838 
3839     if (value >= nrgs) {
3840         qemu_log_mask(LOG_GUEST_ERROR,
3841                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3842                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3843         return;
3844     }
3845 
3846     raw_write(env, ri, value);
3847 }
3848 
3849 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3850     /* Reset for all these registers is handled in arm_cpu_reset(),
3851      * because the PMSAv7 is also used by M-profile CPUs, which do
3852      * not register cpregs but still need the state to be reset.
3853      */
3854     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3855       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3856       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3857       .readfn = pmsav7_read, .writefn = pmsav7_write,
3858       .resetfn = arm_cp_reset_ignore },
3859     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3860       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3861       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3862       .readfn = pmsav7_read, .writefn = pmsav7_write,
3863       .resetfn = arm_cp_reset_ignore },
3864     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3865       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3866       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3867       .readfn = pmsav7_read, .writefn = pmsav7_write,
3868       .resetfn = arm_cp_reset_ignore },
3869     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3870       .access = PL1_RW,
3871       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3872       .writefn = pmsav7_rgnr_write,
3873       .resetfn = arm_cp_reset_ignore },
3874     REGINFO_SENTINEL
3875 };
3876 
3877 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3878     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3879       .access = PL1_RW, .type = ARM_CP_ALIAS,
3880       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3881       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3882     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3883       .access = PL1_RW, .type = ARM_CP_ALIAS,
3884       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3885       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3886     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3887       .access = PL1_RW,
3888       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3889       .resetvalue = 0, },
3890     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3891       .access = PL1_RW,
3892       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3893       .resetvalue = 0, },
3894     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3895       .access = PL1_RW,
3896       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3897     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3898       .access = PL1_RW,
3899       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3900     /* Protection region base and size registers */
3901     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3902       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3903       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3904     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3905       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3906       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3907     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3908       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3909       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3910     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3911       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3912       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3913     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3914       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3915       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3916     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3917       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3918       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3919     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3920       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3921       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3922     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3923       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3924       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3925     REGINFO_SENTINEL
3926 };
3927 
3928 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3929                                  uint64_t value)
3930 {
3931     TCR *tcr = raw_ptr(env, ri);
3932     int maskshift = extract32(value, 0, 3);
3933 
3934     if (!arm_feature(env, ARM_FEATURE_V8)) {
3935         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3936             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3937              * using Long-desciptor translation table format */
3938             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3939         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3940             /* In an implementation that includes the Security Extensions
3941              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3942              * Short-descriptor translation table format.
3943              */
3944             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3945         } else {
3946             value &= TTBCR_N;
3947         }
3948     }
3949 
3950     /* Update the masks corresponding to the TCR bank being written
3951      * Note that we always calculate mask and base_mask, but
3952      * they are only used for short-descriptor tables (ie if EAE is 0);
3953      * for long-descriptor tables the TCR fields are used differently
3954      * and the mask and base_mask values are meaningless.
3955      */
3956     tcr->raw_tcr = value;
3957     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3958     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3959 }
3960 
3961 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3962                              uint64_t value)
3963 {
3964     ARMCPU *cpu = env_archcpu(env);
3965     TCR *tcr = raw_ptr(env, ri);
3966 
3967     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3968         /* With LPAE the TTBCR could result in a change of ASID
3969          * via the TTBCR.A1 bit, so do a TLB flush.
3970          */
3971         tlb_flush(CPU(cpu));
3972     }
3973     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3974     value = deposit64(tcr->raw_tcr, 0, 32, value);
3975     vmsa_ttbcr_raw_write(env, ri, value);
3976 }
3977 
3978 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3979 {
3980     TCR *tcr = raw_ptr(env, ri);
3981 
3982     /* Reset both the TCR as well as the masks corresponding to the bank of
3983      * the TCR being reset.
3984      */
3985     tcr->raw_tcr = 0;
3986     tcr->mask = 0;
3987     tcr->base_mask = 0xffffc000u;
3988 }
3989 
3990 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3991                                uint64_t value)
3992 {
3993     ARMCPU *cpu = env_archcpu(env);
3994     TCR *tcr = raw_ptr(env, ri);
3995 
3996     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3997     tlb_flush(CPU(cpu));
3998     tcr->raw_tcr = value;
3999 }
4000 
4001 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4002                             uint64_t value)
4003 {
4004     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
4005     if (cpreg_field_is_64bit(ri) &&
4006         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
4007         ARMCPU *cpu = env_archcpu(env);
4008         tlb_flush(CPU(cpu));
4009     }
4010     raw_write(env, ri, value);
4011 }
4012 
4013 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4014                                     uint64_t value)
4015 {
4016     /*
4017      * If we are running with E2&0 regime, then an ASID is active.
4018      * Flush if that might be changing.  Note we're not checking
4019      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
4020      * holds the active ASID, only checking the field that might.
4021      */
4022     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
4023         (arm_hcr_el2_eff(env) & HCR_E2H)) {
4024         uint16_t mask = ARMMMUIdxBit_E20_2 |
4025                         ARMMMUIdxBit_E20_2_PAN |
4026                         ARMMMUIdxBit_E20_0;
4027 
4028         if (arm_is_secure_below_el3(env)) {
4029             mask >>= ARM_MMU_IDX_A_NS;
4030         }
4031 
4032         tlb_flush_by_mmuidx(env_cpu(env), mask);
4033     }
4034     raw_write(env, ri, value);
4035 }
4036 
4037 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4038                         uint64_t value)
4039 {
4040     ARMCPU *cpu = env_archcpu(env);
4041     CPUState *cs = CPU(cpu);
4042 
4043     /*
4044      * A change in VMID to the stage2 page table (Stage2) invalidates
4045      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
4046      */
4047     if (raw_read(env, ri) != value) {
4048         uint16_t mask = ARMMMUIdxBit_E10_1 |
4049                         ARMMMUIdxBit_E10_1_PAN |
4050                         ARMMMUIdxBit_E10_0;
4051 
4052         if (arm_is_secure_below_el3(env)) {
4053             mask >>= ARM_MMU_IDX_A_NS;
4054         }
4055 
4056         tlb_flush_by_mmuidx(cs, mask);
4057         raw_write(env, ri, value);
4058     }
4059 }
4060 
4061 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
4062     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
4063       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
4064       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
4065                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
4066     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
4067       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4068       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
4069                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
4070     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
4071       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4072       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
4073                              offsetof(CPUARMState, cp15.dfar_ns) } },
4074     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
4075       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
4076       .access = PL1_RW, .accessfn = access_tvm_trvm,
4077       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
4078       .resetvalue = 0, },
4079     REGINFO_SENTINEL
4080 };
4081 
4082 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
4083     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
4084       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
4085       .access = PL1_RW, .accessfn = access_tvm_trvm,
4086       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
4087     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
4088       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
4089       .access = PL1_RW, .accessfn = access_tvm_trvm,
4090       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4091       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4092                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
4093     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
4094       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
4095       .access = PL1_RW, .accessfn = access_tvm_trvm,
4096       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4097       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4098                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
4099     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
4100       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4101       .access = PL1_RW, .accessfn = access_tvm_trvm,
4102       .writefn = vmsa_tcr_el12_write,
4103       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
4104       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
4105     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4106       .access = PL1_RW, .accessfn = access_tvm_trvm,
4107       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
4108       .raw_writefn = vmsa_ttbcr_raw_write,
4109       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tcr_el[3]),
4110                              offsetoflow32(CPUARMState, cp15.tcr_el[1])} },
4111     REGINFO_SENTINEL
4112 };
4113 
4114 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
4115  * qemu tlbs nor adjusting cached masks.
4116  */
4117 static const ARMCPRegInfo ttbcr2_reginfo = {
4118     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
4119     .access = PL1_RW, .accessfn = access_tvm_trvm,
4120     .type = ARM_CP_ALIAS,
4121     .bank_fieldoffsets = { offsetofhigh32(CPUARMState, cp15.tcr_el[3]),
4122                            offsetofhigh32(CPUARMState, cp15.tcr_el[1]) },
4123 };
4124 
4125 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
4126                                 uint64_t value)
4127 {
4128     env->cp15.c15_ticonfig = value & 0xe7;
4129     /* The OS_TYPE bit in this register changes the reported CPUID! */
4130     env->cp15.c0_cpuid = (value & (1 << 5)) ?
4131         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
4132 }
4133 
4134 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
4135                                 uint64_t value)
4136 {
4137     env->cp15.c15_threadid = value & 0xffff;
4138 }
4139 
4140 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
4141                            uint64_t value)
4142 {
4143     /* Wait-for-interrupt (deprecated) */
4144     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
4145 }
4146 
4147 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
4148                                   uint64_t value)
4149 {
4150     /* On OMAP there are registers indicating the max/min index of dcache lines
4151      * containing a dirty line; cache flush operations have to reset these.
4152      */
4153     env->cp15.c15_i_max = 0x000;
4154     env->cp15.c15_i_min = 0xff0;
4155 }
4156 
4157 static const ARMCPRegInfo omap_cp_reginfo[] = {
4158     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
4159       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
4160       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
4161       .resetvalue = 0, },
4162     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
4163       .access = PL1_RW, .type = ARM_CP_NOP },
4164     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
4165       .access = PL1_RW,
4166       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
4167       .writefn = omap_ticonfig_write },
4168     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
4169       .access = PL1_RW,
4170       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
4171     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
4172       .access = PL1_RW, .resetvalue = 0xff0,
4173       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
4174     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
4175       .access = PL1_RW,
4176       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
4177       .writefn = omap_threadid_write },
4178     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
4179       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4180       .type = ARM_CP_NO_RAW,
4181       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
4182     /* TODO: Peripheral port remap register:
4183      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
4184      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
4185      * when MMU is off.
4186      */
4187     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
4188       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
4189       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
4190       .writefn = omap_cachemaint_write },
4191     { .name = "C9", .cp = 15, .crn = 9,
4192       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
4193       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
4194     REGINFO_SENTINEL
4195 };
4196 
4197 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4198                               uint64_t value)
4199 {
4200     env->cp15.c15_cpar = value & 0x3fff;
4201 }
4202 
4203 static const ARMCPRegInfo xscale_cp_reginfo[] = {
4204     { .name = "XSCALE_CPAR",
4205       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4206       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
4207       .writefn = xscale_cpar_write, },
4208     { .name = "XSCALE_AUXCR",
4209       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
4210       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
4211       .resetvalue = 0, },
4212     /* XScale specific cache-lockdown: since we have no cache we NOP these
4213      * and hope the guest does not really rely on cache behaviour.
4214      */
4215     { .name = "XSCALE_LOCK_ICACHE_LINE",
4216       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
4217       .access = PL1_W, .type = ARM_CP_NOP },
4218     { .name = "XSCALE_UNLOCK_ICACHE",
4219       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
4220       .access = PL1_W, .type = ARM_CP_NOP },
4221     { .name = "XSCALE_DCACHE_LOCK",
4222       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
4223       .access = PL1_RW, .type = ARM_CP_NOP },
4224     { .name = "XSCALE_UNLOCK_DCACHE",
4225       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
4226       .access = PL1_W, .type = ARM_CP_NOP },
4227     REGINFO_SENTINEL
4228 };
4229 
4230 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
4231     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
4232      * implementation of this implementation-defined space.
4233      * Ideally this should eventually disappear in favour of actually
4234      * implementing the correct behaviour for all cores.
4235      */
4236     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
4237       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4238       .access = PL1_RW,
4239       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
4240       .resetvalue = 0 },
4241     REGINFO_SENTINEL
4242 };
4243 
4244 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
4245     /* Cache status: RAZ because we have no cache so it's always clean */
4246     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
4247       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4248       .resetvalue = 0 },
4249     REGINFO_SENTINEL
4250 };
4251 
4252 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
4253     /* We never have a a block transfer operation in progress */
4254     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
4255       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4256       .resetvalue = 0 },
4257     /* The cache ops themselves: these all NOP for QEMU */
4258     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
4259       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4260     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
4261       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4262     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
4263       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4264     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4265       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4266     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4267       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4268     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4269       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4270     REGINFO_SENTINEL
4271 };
4272 
4273 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4274     /* The cache test-and-clean instructions always return (1 << 30)
4275      * to indicate that there are no dirty cache lines.
4276      */
4277     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4278       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4279       .resetvalue = (1 << 30) },
4280     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4281       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4282       .resetvalue = (1 << 30) },
4283     REGINFO_SENTINEL
4284 };
4285 
4286 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4287     /* Ignore ReadBuffer accesses */
4288     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4289       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4290       .access = PL1_RW, .resetvalue = 0,
4291       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4292     REGINFO_SENTINEL
4293 };
4294 
4295 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4296 {
4297     unsigned int cur_el = arm_current_el(env);
4298 
4299     if (arm_is_el2_enabled(env) && cur_el == 1) {
4300         return env->cp15.vpidr_el2;
4301     }
4302     return raw_read(env, ri);
4303 }
4304 
4305 static uint64_t mpidr_read_val(CPUARMState *env)
4306 {
4307     ARMCPU *cpu = env_archcpu(env);
4308     uint64_t mpidr = cpu->mp_affinity;
4309 
4310     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4311         mpidr |= (1U << 31);
4312         /* Cores which are uniprocessor (non-coherent)
4313          * but still implement the MP extensions set
4314          * bit 30. (For instance, Cortex-R5).
4315          */
4316         if (cpu->mp_is_up) {
4317             mpidr |= (1u << 30);
4318         }
4319     }
4320     return mpidr;
4321 }
4322 
4323 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4324 {
4325     unsigned int cur_el = arm_current_el(env);
4326 
4327     if (arm_is_el2_enabled(env) && cur_el == 1) {
4328         return env->cp15.vmpidr_el2;
4329     }
4330     return mpidr_read_val(env);
4331 }
4332 
4333 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4334     /* NOP AMAIR0/1 */
4335     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4336       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4337       .access = PL1_RW, .accessfn = access_tvm_trvm,
4338       .type = ARM_CP_CONST, .resetvalue = 0 },
4339     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4340     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4341       .access = PL1_RW, .accessfn = access_tvm_trvm,
4342       .type = ARM_CP_CONST, .resetvalue = 0 },
4343     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4344       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4345       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4346                              offsetof(CPUARMState, cp15.par_ns)} },
4347     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4348       .access = PL1_RW, .accessfn = access_tvm_trvm,
4349       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4350       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4351                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4352       .writefn = vmsa_ttbr_write, },
4353     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4354       .access = PL1_RW, .accessfn = access_tvm_trvm,
4355       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4356       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4357                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4358       .writefn = vmsa_ttbr_write, },
4359     REGINFO_SENTINEL
4360 };
4361 
4362 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4363 {
4364     return vfp_get_fpcr(env);
4365 }
4366 
4367 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4368                             uint64_t value)
4369 {
4370     vfp_set_fpcr(env, value);
4371 }
4372 
4373 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4374 {
4375     return vfp_get_fpsr(env);
4376 }
4377 
4378 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4379                             uint64_t value)
4380 {
4381     vfp_set_fpsr(env, value);
4382 }
4383 
4384 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4385                                        bool isread)
4386 {
4387     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4388         return CP_ACCESS_TRAP;
4389     }
4390     return CP_ACCESS_OK;
4391 }
4392 
4393 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4394                             uint64_t value)
4395 {
4396     env->daif = value & PSTATE_DAIF;
4397 }
4398 
4399 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4400 {
4401     return env->pstate & PSTATE_PAN;
4402 }
4403 
4404 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4405                            uint64_t value)
4406 {
4407     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4408 }
4409 
4410 static const ARMCPRegInfo pan_reginfo = {
4411     .name = "PAN", .state = ARM_CP_STATE_AA64,
4412     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4413     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4414     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4415 };
4416 
4417 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4418 {
4419     return env->pstate & PSTATE_UAO;
4420 }
4421 
4422 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4423                            uint64_t value)
4424 {
4425     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4426 }
4427 
4428 static const ARMCPRegInfo uao_reginfo = {
4429     .name = "UAO", .state = ARM_CP_STATE_AA64,
4430     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4431     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4432     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4433 };
4434 
4435 static uint64_t aa64_dit_read(CPUARMState *env, const ARMCPRegInfo *ri)
4436 {
4437     return env->pstate & PSTATE_DIT;
4438 }
4439 
4440 static void aa64_dit_write(CPUARMState *env, const ARMCPRegInfo *ri,
4441                            uint64_t value)
4442 {
4443     env->pstate = (env->pstate & ~PSTATE_DIT) | (value & PSTATE_DIT);
4444 }
4445 
4446 static const ARMCPRegInfo dit_reginfo = {
4447     .name = "DIT", .state = ARM_CP_STATE_AA64,
4448     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 5,
4449     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4450     .readfn = aa64_dit_read, .writefn = aa64_dit_write
4451 };
4452 
4453 static uint64_t aa64_ssbs_read(CPUARMState *env, const ARMCPRegInfo *ri)
4454 {
4455     return env->pstate & PSTATE_SSBS;
4456 }
4457 
4458 static void aa64_ssbs_write(CPUARMState *env, const ARMCPRegInfo *ri,
4459                            uint64_t value)
4460 {
4461     env->pstate = (env->pstate & ~PSTATE_SSBS) | (value & PSTATE_SSBS);
4462 }
4463 
4464 static const ARMCPRegInfo ssbs_reginfo = {
4465     .name = "SSBS", .state = ARM_CP_STATE_AA64,
4466     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 6,
4467     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4468     .readfn = aa64_ssbs_read, .writefn = aa64_ssbs_write
4469 };
4470 
4471 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4472                                               const ARMCPRegInfo *ri,
4473                                               bool isread)
4474 {
4475     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4476     switch (arm_current_el(env)) {
4477     case 0:
4478         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4479         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4480             return CP_ACCESS_TRAP;
4481         }
4482         /* fall through */
4483     case 1:
4484         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4485         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4486             return CP_ACCESS_TRAP_EL2;
4487         }
4488         break;
4489     }
4490     return CP_ACCESS_OK;
4491 }
4492 
4493 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4494                                               const ARMCPRegInfo *ri,
4495                                               bool isread)
4496 {
4497     /* Cache invalidate/clean to Point of Unification... */
4498     switch (arm_current_el(env)) {
4499     case 0:
4500         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4501         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4502             return CP_ACCESS_TRAP;
4503         }
4504         /* fall through */
4505     case 1:
4506         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4507         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4508             return CP_ACCESS_TRAP_EL2;
4509         }
4510         break;
4511     }
4512     return CP_ACCESS_OK;
4513 }
4514 
4515 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4516  * Page D4-1736 (DDI0487A.b)
4517  */
4518 
4519 static int vae1_tlbmask(CPUARMState *env)
4520 {
4521     uint64_t hcr = arm_hcr_el2_eff(env);
4522     uint16_t mask;
4523 
4524     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4525         mask = ARMMMUIdxBit_E20_2 |
4526                ARMMMUIdxBit_E20_2_PAN |
4527                ARMMMUIdxBit_E20_0;
4528     } else {
4529         mask = ARMMMUIdxBit_E10_1 |
4530                ARMMMUIdxBit_E10_1_PAN |
4531                ARMMMUIdxBit_E10_0;
4532     }
4533 
4534     if (arm_is_secure_below_el3(env)) {
4535         mask >>= ARM_MMU_IDX_A_NS;
4536     }
4537 
4538     return mask;
4539 }
4540 
4541 /* Return 56 if TBI is enabled, 64 otherwise. */
4542 static int tlbbits_for_regime(CPUARMState *env, ARMMMUIdx mmu_idx,
4543                               uint64_t addr)
4544 {
4545     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
4546     int tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
4547     int select = extract64(addr, 55, 1);
4548 
4549     return (tbi >> select) & 1 ? 56 : 64;
4550 }
4551 
4552 static int vae1_tlbbits(CPUARMState *env, uint64_t addr)
4553 {
4554     uint64_t hcr = arm_hcr_el2_eff(env);
4555     ARMMMUIdx mmu_idx;
4556 
4557     /* Only the regime of the mmu_idx below is significant. */
4558     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4559         mmu_idx = ARMMMUIdx_E20_0;
4560     } else {
4561         mmu_idx = ARMMMUIdx_E10_0;
4562     }
4563 
4564     if (arm_is_secure_below_el3(env)) {
4565         mmu_idx &= ~ARM_MMU_IDX_A_NS;
4566     }
4567 
4568     return tlbbits_for_regime(env, mmu_idx, addr);
4569 }
4570 
4571 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4572                                       uint64_t value)
4573 {
4574     CPUState *cs = env_cpu(env);
4575     int mask = vae1_tlbmask(env);
4576 
4577     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4578 }
4579 
4580 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4581                                     uint64_t value)
4582 {
4583     CPUState *cs = env_cpu(env);
4584     int mask = vae1_tlbmask(env);
4585 
4586     if (tlb_force_broadcast(env)) {
4587         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4588     } else {
4589         tlb_flush_by_mmuidx(cs, mask);
4590     }
4591 }
4592 
4593 static int alle1_tlbmask(CPUARMState *env)
4594 {
4595     /*
4596      * Note that the 'ALL' scope must invalidate both stage 1 and
4597      * stage 2 translations, whereas most other scopes only invalidate
4598      * stage 1 translations.
4599      */
4600     if (arm_is_secure_below_el3(env)) {
4601         return ARMMMUIdxBit_SE10_1 |
4602                ARMMMUIdxBit_SE10_1_PAN |
4603                ARMMMUIdxBit_SE10_0;
4604     } else {
4605         return ARMMMUIdxBit_E10_1 |
4606                ARMMMUIdxBit_E10_1_PAN |
4607                ARMMMUIdxBit_E10_0;
4608     }
4609 }
4610 
4611 static int e2_tlbmask(CPUARMState *env)
4612 {
4613     if (arm_is_secure_below_el3(env)) {
4614         return ARMMMUIdxBit_SE20_0 |
4615                ARMMMUIdxBit_SE20_2 |
4616                ARMMMUIdxBit_SE20_2_PAN |
4617                ARMMMUIdxBit_SE2;
4618     } else {
4619         return ARMMMUIdxBit_E20_0 |
4620                ARMMMUIdxBit_E20_2 |
4621                ARMMMUIdxBit_E20_2_PAN |
4622                ARMMMUIdxBit_E2;
4623     }
4624 }
4625 
4626 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4627                                   uint64_t value)
4628 {
4629     CPUState *cs = env_cpu(env);
4630     int mask = alle1_tlbmask(env);
4631 
4632     tlb_flush_by_mmuidx(cs, mask);
4633 }
4634 
4635 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4636                                   uint64_t value)
4637 {
4638     CPUState *cs = env_cpu(env);
4639     int mask = e2_tlbmask(env);
4640 
4641     tlb_flush_by_mmuidx(cs, mask);
4642 }
4643 
4644 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4645                                   uint64_t value)
4646 {
4647     ARMCPU *cpu = env_archcpu(env);
4648     CPUState *cs = CPU(cpu);
4649 
4650     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4651 }
4652 
4653 static void tlbi_aa64_alle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4654                                     uint64_t value)
4655 {
4656     CPUState *cs = env_cpu(env);
4657     int mask = alle1_tlbmask(env);
4658 
4659     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4660 }
4661 
4662 static void tlbi_aa64_alle2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4663                                     uint64_t value)
4664 {
4665     CPUState *cs = env_cpu(env);
4666     int mask = e2_tlbmask(env);
4667 
4668     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4669 }
4670 
4671 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4672                                     uint64_t value)
4673 {
4674     CPUState *cs = env_cpu(env);
4675 
4676     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4677 }
4678 
4679 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4680                                  uint64_t value)
4681 {
4682     /* Invalidate by VA, EL2
4683      * Currently handles both VAE2 and VALE2, since we don't support
4684      * flush-last-level-only.
4685      */
4686     CPUState *cs = env_cpu(env);
4687     int mask = e2_tlbmask(env);
4688     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4689 
4690     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4691 }
4692 
4693 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4694                                  uint64_t value)
4695 {
4696     /* Invalidate by VA, EL3
4697      * Currently handles both VAE3 and VALE3, since we don't support
4698      * flush-last-level-only.
4699      */
4700     ARMCPU *cpu = env_archcpu(env);
4701     CPUState *cs = CPU(cpu);
4702     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4703 
4704     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4705 }
4706 
4707 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4708                                    uint64_t value)
4709 {
4710     CPUState *cs = env_cpu(env);
4711     int mask = vae1_tlbmask(env);
4712     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4713     int bits = vae1_tlbbits(env, pageaddr);
4714 
4715     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4716 }
4717 
4718 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4719                                  uint64_t value)
4720 {
4721     /* Invalidate by VA, EL1&0 (AArch64 version).
4722      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4723      * since we don't support flush-for-specific-ASID-only or
4724      * flush-last-level-only.
4725      */
4726     CPUState *cs = env_cpu(env);
4727     int mask = vae1_tlbmask(env);
4728     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4729     int bits = vae1_tlbbits(env, pageaddr);
4730 
4731     if (tlb_force_broadcast(env)) {
4732         tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4733     } else {
4734         tlb_flush_page_bits_by_mmuidx(cs, pageaddr, mask, bits);
4735     }
4736 }
4737 
4738 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4739                                    uint64_t value)
4740 {
4741     CPUState *cs = env_cpu(env);
4742     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4743     bool secure = arm_is_secure_below_el3(env);
4744     int mask = secure ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2;
4745     int bits = tlbbits_for_regime(env, secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2,
4746                                   pageaddr);
4747 
4748     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4749 }
4750 
4751 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4752                                    uint64_t value)
4753 {
4754     CPUState *cs = env_cpu(env);
4755     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4756     int bits = tlbbits_for_regime(env, ARMMMUIdx_SE3, pageaddr);
4757 
4758     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr,
4759                                                   ARMMMUIdxBit_SE3, bits);
4760 }
4761 
4762 #ifdef TARGET_AARCH64
4763 static uint64_t tlbi_aa64_range_get_length(CPUARMState *env,
4764                                            uint64_t value)
4765 {
4766     unsigned int page_shift;
4767     unsigned int page_size_granule;
4768     uint64_t num;
4769     uint64_t scale;
4770     uint64_t exponent;
4771     uint64_t length;
4772 
4773     num = extract64(value, 39, 4);
4774     scale = extract64(value, 44, 2);
4775     page_size_granule = extract64(value, 46, 2);
4776 
4777     page_shift = page_size_granule * 2 + 12;
4778 
4779     if (page_size_granule == 0) {
4780         qemu_log_mask(LOG_GUEST_ERROR, "Invalid page size granule %d\n",
4781                       page_size_granule);
4782         return 0;
4783     }
4784 
4785     exponent = (5 * scale) + 1;
4786     length = (num + 1) << (exponent + page_shift);
4787 
4788     return length;
4789 }
4790 
4791 static uint64_t tlbi_aa64_range_get_base(CPUARMState *env, uint64_t value,
4792                                         bool two_ranges)
4793 {
4794     /* TODO: ARMv8.7 FEAT_LPA2 */
4795     uint64_t pageaddr;
4796 
4797     if (two_ranges) {
4798         pageaddr = sextract64(value, 0, 37) << TARGET_PAGE_BITS;
4799     } else {
4800         pageaddr = extract64(value, 0, 37) << TARGET_PAGE_BITS;
4801     }
4802 
4803     return pageaddr;
4804 }
4805 
4806 static void do_rvae_write(CPUARMState *env, uint64_t value,
4807                           int idxmap, bool synced)
4808 {
4809     ARMMMUIdx one_idx = ARM_MMU_IDX_A | ctz32(idxmap);
4810     bool two_ranges = regime_has_2_ranges(one_idx);
4811     uint64_t baseaddr, length;
4812     int bits;
4813 
4814     baseaddr = tlbi_aa64_range_get_base(env, value, two_ranges);
4815     length = tlbi_aa64_range_get_length(env, value);
4816     bits = tlbbits_for_regime(env, one_idx, baseaddr);
4817 
4818     if (synced) {
4819         tlb_flush_range_by_mmuidx_all_cpus_synced(env_cpu(env),
4820                                                   baseaddr,
4821                                                   length,
4822                                                   idxmap,
4823                                                   bits);
4824     } else {
4825         tlb_flush_range_by_mmuidx(env_cpu(env), baseaddr,
4826                                   length, idxmap, bits);
4827     }
4828 }
4829 
4830 static void tlbi_aa64_rvae1_write(CPUARMState *env,
4831                                   const ARMCPRegInfo *ri,
4832                                   uint64_t value)
4833 {
4834     /*
4835      * Invalidate by VA range, EL1&0.
4836      * Currently handles all of RVAE1, RVAAE1, RVAALE1 and RVALE1,
4837      * since we don't support flush-for-specific-ASID-only or
4838      * flush-last-level-only.
4839      */
4840 
4841     do_rvae_write(env, value, vae1_tlbmask(env),
4842                   tlb_force_broadcast(env));
4843 }
4844 
4845 static void tlbi_aa64_rvae1is_write(CPUARMState *env,
4846                                     const ARMCPRegInfo *ri,
4847                                     uint64_t value)
4848 {
4849     /*
4850      * Invalidate by VA range, Inner/Outer Shareable EL1&0.
4851      * Currently handles all of RVAE1IS, RVAE1OS, RVAAE1IS, RVAAE1OS,
4852      * RVAALE1IS, RVAALE1OS, RVALE1IS and RVALE1OS, since we don't support
4853      * flush-for-specific-ASID-only, flush-last-level-only or inner/outer
4854      * shareable specific flushes.
4855      */
4856 
4857     do_rvae_write(env, value, vae1_tlbmask(env), true);
4858 }
4859 
4860 static int vae2_tlbmask(CPUARMState *env)
4861 {
4862     return (arm_is_secure_below_el3(env)
4863             ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2);
4864 }
4865 
4866 static void tlbi_aa64_rvae2_write(CPUARMState *env,
4867                                   const ARMCPRegInfo *ri,
4868                                   uint64_t value)
4869 {
4870     /*
4871      * Invalidate by VA range, EL2.
4872      * Currently handles all of RVAE2 and RVALE2,
4873      * since we don't support flush-for-specific-ASID-only or
4874      * flush-last-level-only.
4875      */
4876 
4877     do_rvae_write(env, value, vae2_tlbmask(env),
4878                   tlb_force_broadcast(env));
4879 
4880 
4881 }
4882 
4883 static void tlbi_aa64_rvae2is_write(CPUARMState *env,
4884                                     const ARMCPRegInfo *ri,
4885                                     uint64_t value)
4886 {
4887     /*
4888      * Invalidate by VA range, Inner/Outer Shareable, EL2.
4889      * Currently handles all of RVAE2IS, RVAE2OS, RVALE2IS and RVALE2OS,
4890      * since we don't support flush-for-specific-ASID-only,
4891      * flush-last-level-only or inner/outer shareable specific flushes.
4892      */
4893 
4894     do_rvae_write(env, value, vae2_tlbmask(env), true);
4895 
4896 }
4897 
4898 static void tlbi_aa64_rvae3_write(CPUARMState *env,
4899                                   const ARMCPRegInfo *ri,
4900                                   uint64_t value)
4901 {
4902     /*
4903      * Invalidate by VA range, EL3.
4904      * Currently handles all of RVAE3 and RVALE3,
4905      * since we don't support flush-for-specific-ASID-only or
4906      * flush-last-level-only.
4907      */
4908 
4909     do_rvae_write(env, value, ARMMMUIdxBit_SE3,
4910                   tlb_force_broadcast(env));
4911 }
4912 
4913 static void tlbi_aa64_rvae3is_write(CPUARMState *env,
4914                                     const ARMCPRegInfo *ri,
4915                                     uint64_t value)
4916 {
4917     /*
4918      * Invalidate by VA range, EL3, Inner/Outer Shareable.
4919      * Currently handles all of RVAE3IS, RVAE3OS, RVALE3IS and RVALE3OS,
4920      * since we don't support flush-for-specific-ASID-only,
4921      * flush-last-level-only or inner/outer specific flushes.
4922      */
4923 
4924     do_rvae_write(env, value, ARMMMUIdxBit_SE3, true);
4925 }
4926 #endif
4927 
4928 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4929                                       bool isread)
4930 {
4931     int cur_el = arm_current_el(env);
4932 
4933     if (cur_el < 2) {
4934         uint64_t hcr = arm_hcr_el2_eff(env);
4935 
4936         if (cur_el == 0) {
4937             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4938                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4939                     return CP_ACCESS_TRAP_EL2;
4940                 }
4941             } else {
4942                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4943                     return CP_ACCESS_TRAP;
4944                 }
4945                 if (hcr & HCR_TDZ) {
4946                     return CP_ACCESS_TRAP_EL2;
4947                 }
4948             }
4949         } else if (hcr & HCR_TDZ) {
4950             return CP_ACCESS_TRAP_EL2;
4951         }
4952     }
4953     return CP_ACCESS_OK;
4954 }
4955 
4956 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4957 {
4958     ARMCPU *cpu = env_archcpu(env);
4959     int dzp_bit = 1 << 4;
4960 
4961     /* DZP indicates whether DC ZVA access is allowed */
4962     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4963         dzp_bit = 0;
4964     }
4965     return cpu->dcz_blocksize | dzp_bit;
4966 }
4967 
4968 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4969                                     bool isread)
4970 {
4971     if (!(env->pstate & PSTATE_SP)) {
4972         /* Access to SP_EL0 is undefined if it's being used as
4973          * the stack pointer.
4974          */
4975         return CP_ACCESS_TRAP_UNCATEGORIZED;
4976     }
4977     return CP_ACCESS_OK;
4978 }
4979 
4980 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4981 {
4982     return env->pstate & PSTATE_SP;
4983 }
4984 
4985 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4986 {
4987     update_spsel(env, val);
4988 }
4989 
4990 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4991                         uint64_t value)
4992 {
4993     ARMCPU *cpu = env_archcpu(env);
4994 
4995     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4996         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4997         value &= ~SCTLR_M;
4998     }
4999 
5000     /* ??? Lots of these bits are not implemented.  */
5001 
5002     if (ri->state == ARM_CP_STATE_AA64 && !cpu_isar_feature(aa64_mte, cpu)) {
5003         if (ri->opc1 == 6) { /* SCTLR_EL3 */
5004             value &= ~(SCTLR_ITFSB | SCTLR_TCF | SCTLR_ATA);
5005         } else {
5006             value &= ~(SCTLR_ITFSB | SCTLR_TCF0 | SCTLR_TCF |
5007                        SCTLR_ATA0 | SCTLR_ATA);
5008         }
5009     }
5010 
5011     if (raw_read(env, ri) == value) {
5012         /* Skip the TLB flush if nothing actually changed; Linux likes
5013          * to do a lot of pointless SCTLR writes.
5014          */
5015         return;
5016     }
5017 
5018     raw_write(env, ri, value);
5019 
5020     /* This may enable/disable the MMU, so do a TLB flush.  */
5021     tlb_flush(CPU(cpu));
5022 
5023     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
5024         /*
5025          * Normally we would always end the TB on an SCTLR write; see the
5026          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
5027          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
5028          * of hflags from the translator, so do it here.
5029          */
5030         arm_rebuild_hflags(env);
5031     }
5032 }
5033 
5034 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
5035                                      bool isread)
5036 {
5037     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
5038         return CP_ACCESS_TRAP_FP_EL2;
5039     }
5040     if (env->cp15.cptr_el[3] & CPTR_TFP) {
5041         return CP_ACCESS_TRAP_FP_EL3;
5042     }
5043     return CP_ACCESS_OK;
5044 }
5045 
5046 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5047                        uint64_t value)
5048 {
5049     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
5050 }
5051 
5052 static const ARMCPRegInfo v8_cp_reginfo[] = {
5053     /* Minimal set of EL0-visible registers. This will need to be expanded
5054      * significantly for system emulation of AArch64 CPUs.
5055      */
5056     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
5057       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
5058       .access = PL0_RW, .type = ARM_CP_NZCV },
5059     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
5060       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
5061       .type = ARM_CP_NO_RAW,
5062       .access = PL0_RW, .accessfn = aa64_daif_access,
5063       .fieldoffset = offsetof(CPUARMState, daif),
5064       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
5065     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
5066       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
5067       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
5068       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
5069     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
5070       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
5071       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
5072       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
5073     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
5074       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
5075       .access = PL0_R, .type = ARM_CP_NO_RAW,
5076       .readfn = aa64_dczid_read },
5077     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
5078       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
5079       .access = PL0_W, .type = ARM_CP_DC_ZVA,
5080 #ifndef CONFIG_USER_ONLY
5081       /* Avoid overhead of an access check that always passes in user-mode */
5082       .accessfn = aa64_zva_access,
5083 #endif
5084     },
5085     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
5086       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
5087       .access = PL1_R, .type = ARM_CP_CURRENTEL },
5088     /* Cache ops: all NOPs since we don't emulate caches */
5089     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
5090       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5091       .access = PL1_W, .type = ARM_CP_NOP,
5092       .accessfn = aa64_cacheop_pou_access },
5093     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
5094       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5095       .access = PL1_W, .type = ARM_CP_NOP,
5096       .accessfn = aa64_cacheop_pou_access },
5097     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
5098       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
5099       .access = PL0_W, .type = ARM_CP_NOP,
5100       .accessfn = aa64_cacheop_pou_access },
5101     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
5102       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5103       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
5104       .type = ARM_CP_NOP },
5105     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
5106       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5107       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
5108     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
5109       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
5110       .access = PL0_W, .type = ARM_CP_NOP,
5111       .accessfn = aa64_cacheop_poc_access },
5112     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
5113       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5114       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
5115     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
5116       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
5117       .access = PL0_W, .type = ARM_CP_NOP,
5118       .accessfn = aa64_cacheop_pou_access },
5119     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
5120       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
5121       .access = PL0_W, .type = ARM_CP_NOP,
5122       .accessfn = aa64_cacheop_poc_access },
5123     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
5124       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5125       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
5126     /* TLBI operations */
5127     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
5128       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
5129       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5130       .writefn = tlbi_aa64_vmalle1is_write },
5131     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
5132       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
5133       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5134       .writefn = tlbi_aa64_vae1is_write },
5135     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
5136       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
5137       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5138       .writefn = tlbi_aa64_vmalle1is_write },
5139     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
5140       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
5141       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5142       .writefn = tlbi_aa64_vae1is_write },
5143     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
5144       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
5145       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5146       .writefn = tlbi_aa64_vae1is_write },
5147     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
5148       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
5149       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5150       .writefn = tlbi_aa64_vae1is_write },
5151     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
5152       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
5153       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5154       .writefn = tlbi_aa64_vmalle1_write },
5155     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
5156       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
5157       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5158       .writefn = tlbi_aa64_vae1_write },
5159     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
5160       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
5161       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5162       .writefn = tlbi_aa64_vmalle1_write },
5163     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
5164       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
5165       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5166       .writefn = tlbi_aa64_vae1_write },
5167     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
5168       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
5169       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5170       .writefn = tlbi_aa64_vae1_write },
5171     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
5172       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
5173       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5174       .writefn = tlbi_aa64_vae1_write },
5175     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
5176       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5177       .access = PL2_W, .type = ARM_CP_NOP },
5178     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
5179       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5180       .access = PL2_W, .type = ARM_CP_NOP },
5181     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
5182       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5183       .access = PL2_W, .type = ARM_CP_NO_RAW,
5184       .writefn = tlbi_aa64_alle1is_write },
5185     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
5186       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
5187       .access = PL2_W, .type = ARM_CP_NO_RAW,
5188       .writefn = tlbi_aa64_alle1is_write },
5189     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
5190       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5191       .access = PL2_W, .type = ARM_CP_NOP },
5192     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
5193       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5194       .access = PL2_W, .type = ARM_CP_NOP },
5195     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
5196       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5197       .access = PL2_W, .type = ARM_CP_NO_RAW,
5198       .writefn = tlbi_aa64_alle1_write },
5199     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
5200       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
5201       .access = PL2_W, .type = ARM_CP_NO_RAW,
5202       .writefn = tlbi_aa64_alle1is_write },
5203 #ifndef CONFIG_USER_ONLY
5204     /* 64 bit address translation operations */
5205     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
5206       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
5207       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5208       .writefn = ats_write64 },
5209     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
5210       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
5211       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5212       .writefn = ats_write64 },
5213     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
5214       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
5215       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5216       .writefn = ats_write64 },
5217     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
5218       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
5219       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5220       .writefn = ats_write64 },
5221     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
5222       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
5223       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5224       .writefn = ats_write64 },
5225     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
5226       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
5227       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5228       .writefn = ats_write64 },
5229     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
5230       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
5231       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5232       .writefn = ats_write64 },
5233     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
5234       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
5235       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5236       .writefn = ats_write64 },
5237     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
5238     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
5239       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
5240       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5241       .writefn = ats_write64 },
5242     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
5243       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
5244       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5245       .writefn = ats_write64 },
5246     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
5247       .type = ARM_CP_ALIAS,
5248       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
5249       .access = PL1_RW, .resetvalue = 0,
5250       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
5251       .writefn = par_write },
5252 #endif
5253     /* TLB invalidate last level of translation table walk */
5254     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
5255       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5256       .writefn = tlbimva_is_write },
5257     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
5258       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5259       .writefn = tlbimvaa_is_write },
5260     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
5261       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5262       .writefn = tlbimva_write },
5263     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
5264       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5265       .writefn = tlbimvaa_write },
5266     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5267       .type = ARM_CP_NO_RAW, .access = PL2_W,
5268       .writefn = tlbimva_hyp_write },
5269     { .name = "TLBIMVALHIS",
5270       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5271       .type = ARM_CP_NO_RAW, .access = PL2_W,
5272       .writefn = tlbimva_hyp_is_write },
5273     { .name = "TLBIIPAS2",
5274       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5275       .type = ARM_CP_NOP, .access = PL2_W },
5276     { .name = "TLBIIPAS2IS",
5277       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5278       .type = ARM_CP_NOP, .access = PL2_W },
5279     { .name = "TLBIIPAS2L",
5280       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5281       .type = ARM_CP_NOP, .access = PL2_W },
5282     { .name = "TLBIIPAS2LIS",
5283       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5284       .type = ARM_CP_NOP, .access = PL2_W },
5285     /* 32 bit cache operations */
5286     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5287       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5288     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5289       .type = ARM_CP_NOP, .access = PL1_W },
5290     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5291       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5292     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5293       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5294     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5295       .type = ARM_CP_NOP, .access = PL1_W },
5296     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5297       .type = ARM_CP_NOP, .access = PL1_W },
5298     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5299       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5300     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5301       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5302     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5303       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5304     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5305       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5306     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5307       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5308     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5309       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5310     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5311       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5312     /* MMU Domain access control / MPU write buffer control */
5313     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5314       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5315       .writefn = dacr_write, .raw_writefn = raw_write,
5316       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5317                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5318     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5319       .type = ARM_CP_ALIAS,
5320       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5321       .access = PL1_RW,
5322       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5323     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5324       .type = ARM_CP_ALIAS,
5325       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5326       .access = PL1_RW,
5327       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5328     /* We rely on the access checks not allowing the guest to write to the
5329      * state field when SPSel indicates that it's being used as the stack
5330      * pointer.
5331      */
5332     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5333       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5334       .access = PL1_RW, .accessfn = sp_el0_access,
5335       .type = ARM_CP_ALIAS,
5336       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5337     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5338       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5339       .access = PL2_RW, .type = ARM_CP_ALIAS,
5340       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5341     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5342       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5343       .type = ARM_CP_NO_RAW,
5344       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5345     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5346       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5347       .type = ARM_CP_ALIAS,
5348       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
5349       .access = PL2_RW, .accessfn = fpexc32_access },
5350     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5351       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5352       .access = PL2_RW, .resetvalue = 0,
5353       .writefn = dacr_write, .raw_writefn = raw_write,
5354       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5355     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5356       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5357       .access = PL2_RW, .resetvalue = 0,
5358       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5359     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5360       .type = ARM_CP_ALIAS,
5361       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5362       .access = PL2_RW,
5363       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5364     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5365       .type = ARM_CP_ALIAS,
5366       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5367       .access = PL2_RW,
5368       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5369     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5370       .type = ARM_CP_ALIAS,
5371       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5372       .access = PL2_RW,
5373       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5374     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5375       .type = ARM_CP_ALIAS,
5376       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5377       .access = PL2_RW,
5378       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5379     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5380       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5381       .resetvalue = 0,
5382       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5383     { .name = "SDCR", .type = ARM_CP_ALIAS,
5384       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5385       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5386       .writefn = sdcr_write,
5387       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5388     REGINFO_SENTINEL
5389 };
5390 
5391 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
5392 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
5393     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5394       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5395       .access = PL2_RW,
5396       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
5397     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
5398       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5399       .access = PL2_RW,
5400       .type = ARM_CP_CONST, .resetvalue = 0 },
5401     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5402       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5403       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5404     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5405       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5406       .access = PL2_RW,
5407       .type = ARM_CP_CONST, .resetvalue = 0 },
5408     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5409       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5410       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5411     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5412       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5413       .access = PL2_RW, .type = ARM_CP_CONST,
5414       .resetvalue = 0 },
5415     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5416       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5417       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5418     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5419       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5420       .access = PL2_RW, .type = ARM_CP_CONST,
5421       .resetvalue = 0 },
5422     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5423       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5424       .access = PL2_RW, .type = ARM_CP_CONST,
5425       .resetvalue = 0 },
5426     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5427       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5428       .access = PL2_RW, .type = ARM_CP_CONST,
5429       .resetvalue = 0 },
5430     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5431       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5432       .access = PL2_RW, .type = ARM_CP_CONST,
5433       .resetvalue = 0 },
5434     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5435       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5436       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5437     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
5438       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5439       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5440       .type = ARM_CP_CONST, .resetvalue = 0 },
5441     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5442       .cp = 15, .opc1 = 6, .crm = 2,
5443       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5444       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
5445     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5446       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5447       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5448     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5449       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5450       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5451     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5452       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5453       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5454     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5455       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5456       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5457     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5458       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5459       .resetvalue = 0 },
5460     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5461       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5462       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5463     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5464       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5465       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5466     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5467       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5468       .resetvalue = 0 },
5469     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5470       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5471       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5472     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5473       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5474       .resetvalue = 0 },
5475     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5476       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5477       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5478     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5479       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5480       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5481     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5482       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5483       .access = PL2_RW, .accessfn = access_tda,
5484       .type = ARM_CP_CONST, .resetvalue = 0 },
5485     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
5486       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5487       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5488       .type = ARM_CP_CONST, .resetvalue = 0 },
5489     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5490       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5491       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5492     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5493       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5494       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5495     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5496       .type = ARM_CP_CONST,
5497       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5498       .access = PL2_RW, .resetvalue = 0 },
5499     REGINFO_SENTINEL
5500 };
5501 
5502 /* Ditto, but for registers which exist in ARMv8 but not v7 */
5503 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
5504     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5505       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5506       .access = PL2_RW,
5507       .type = ARM_CP_CONST, .resetvalue = 0 },
5508     REGINFO_SENTINEL
5509 };
5510 
5511 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5512 {
5513     ARMCPU *cpu = env_archcpu(env);
5514 
5515     if (arm_feature(env, ARM_FEATURE_V8)) {
5516         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5517     } else {
5518         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5519     }
5520 
5521     if (arm_feature(env, ARM_FEATURE_EL3)) {
5522         valid_mask &= ~HCR_HCD;
5523     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5524         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5525          * However, if we're using the SMC PSCI conduit then QEMU is
5526          * effectively acting like EL3 firmware and so the guest at
5527          * EL2 should retain the ability to prevent EL1 from being
5528          * able to make SMC calls into the ersatz firmware, so in
5529          * that case HCR.TSC should be read/write.
5530          */
5531         valid_mask &= ~HCR_TSC;
5532     }
5533 
5534     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5535         if (cpu_isar_feature(aa64_vh, cpu)) {
5536             valid_mask |= HCR_E2H;
5537         }
5538         if (cpu_isar_feature(aa64_lor, cpu)) {
5539             valid_mask |= HCR_TLOR;
5540         }
5541         if (cpu_isar_feature(aa64_pauth, cpu)) {
5542             valid_mask |= HCR_API | HCR_APK;
5543         }
5544         if (cpu_isar_feature(aa64_mte, cpu)) {
5545             valid_mask |= HCR_ATA | HCR_DCT | HCR_TID5;
5546         }
5547     }
5548 
5549     /* Clear RES0 bits.  */
5550     value &= valid_mask;
5551 
5552     /*
5553      * These bits change the MMU setup:
5554      * HCR_VM enables stage 2 translation
5555      * HCR_PTW forbids certain page-table setups
5556      * HCR_DC disables stage1 and enables stage2 translation
5557      * HCR_DCT enables tagging on (disabled) stage1 translation
5558      */
5559     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC | HCR_DCT)) {
5560         tlb_flush(CPU(cpu));
5561     }
5562     env->cp15.hcr_el2 = value;
5563 
5564     /*
5565      * Updates to VI and VF require us to update the status of
5566      * virtual interrupts, which are the logical OR of these bits
5567      * and the state of the input lines from the GIC. (This requires
5568      * that we have the iothread lock, which is done by marking the
5569      * reginfo structs as ARM_CP_IO.)
5570      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5571      * possible for it to be taken immediately, because VIRQ and
5572      * VFIQ are masked unless running at EL0 or EL1, and HCR
5573      * can only be written at EL2.
5574      */
5575     g_assert(qemu_mutex_iothread_locked());
5576     arm_cpu_update_virq(cpu);
5577     arm_cpu_update_vfiq(cpu);
5578 }
5579 
5580 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5581 {
5582     do_hcr_write(env, value, 0);
5583 }
5584 
5585 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5586                           uint64_t value)
5587 {
5588     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5589     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5590     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5591 }
5592 
5593 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5594                          uint64_t value)
5595 {
5596     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5597     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5598     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5599 }
5600 
5601 /*
5602  * Return the effective value of HCR_EL2.
5603  * Bits that are not included here:
5604  * RW       (read from SCR_EL3.RW as needed)
5605  */
5606 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5607 {
5608     uint64_t ret = env->cp15.hcr_el2;
5609 
5610     if (!arm_is_el2_enabled(env)) {
5611         /*
5612          * "This register has no effect if EL2 is not enabled in the
5613          * current Security state".  This is ARMv8.4-SecEL2 speak for
5614          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5615          *
5616          * Prior to that, the language was "In an implementation that
5617          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5618          * as if this field is 0 for all purposes other than a direct
5619          * read or write access of HCR_EL2".  With lots of enumeration
5620          * on a per-field basis.  In current QEMU, this is condition
5621          * is arm_is_secure_below_el3.
5622          *
5623          * Since the v8.4 language applies to the entire register, and
5624          * appears to be backward compatible, use that.
5625          */
5626         return 0;
5627     }
5628 
5629     /*
5630      * For a cpu that supports both aarch64 and aarch32, we can set bits
5631      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5632      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5633      */
5634     if (!arm_el_is_aa64(env, 2)) {
5635         uint64_t aa32_valid;
5636 
5637         /*
5638          * These bits are up-to-date as of ARMv8.6.
5639          * For HCR, it's easiest to list just the 2 bits that are invalid.
5640          * For HCR2, list those that are valid.
5641          */
5642         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5643         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5644                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5645         ret &= aa32_valid;
5646     }
5647 
5648     if (ret & HCR_TGE) {
5649         /* These bits are up-to-date as of ARMv8.6.  */
5650         if (ret & HCR_E2H) {
5651             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5652                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5653                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5654                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5655                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5656                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5657         } else {
5658             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5659         }
5660         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5661                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5662                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5663                  HCR_TLOR);
5664     }
5665 
5666     return ret;
5667 }
5668 
5669 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5670                            uint64_t value)
5671 {
5672     /*
5673      * For A-profile AArch32 EL3, if NSACR.CP10
5674      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5675      */
5676     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5677         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5678         value &= ~(0x3 << 10);
5679         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5680     }
5681     env->cp15.cptr_el[2] = value;
5682 }
5683 
5684 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5685 {
5686     /*
5687      * For A-profile AArch32 EL3, if NSACR.CP10
5688      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5689      */
5690     uint64_t value = env->cp15.cptr_el[2];
5691 
5692     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5693         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5694         value |= 0x3 << 10;
5695     }
5696     return value;
5697 }
5698 
5699 static const ARMCPRegInfo el2_cp_reginfo[] = {
5700     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5701       .type = ARM_CP_IO,
5702       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5703       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5704       .writefn = hcr_write },
5705     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5706       .type = ARM_CP_ALIAS | ARM_CP_IO,
5707       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5708       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5709       .writefn = hcr_writelow },
5710     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5711       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5712       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5713     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5714       .type = ARM_CP_ALIAS,
5715       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5716       .access = PL2_RW,
5717       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5718     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5719       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5720       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5721     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5722       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5723       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5724     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5725       .type = ARM_CP_ALIAS,
5726       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5727       .access = PL2_RW,
5728       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5729     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5730       .type = ARM_CP_ALIAS,
5731       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5732       .access = PL2_RW,
5733       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5734     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5735       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5736       .access = PL2_RW, .writefn = vbar_write,
5737       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5738       .resetvalue = 0 },
5739     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5740       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5741       .access = PL3_RW, .type = ARM_CP_ALIAS,
5742       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5743     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5744       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5745       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5746       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5747       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5748     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5749       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5750       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5751       .resetvalue = 0 },
5752     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5753       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5754       .access = PL2_RW, .type = ARM_CP_ALIAS,
5755       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5756     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5757       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5758       .access = PL2_RW, .type = ARM_CP_CONST,
5759       .resetvalue = 0 },
5760     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5761     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5762       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5763       .access = PL2_RW, .type = ARM_CP_CONST,
5764       .resetvalue = 0 },
5765     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5766       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5767       .access = PL2_RW, .type = ARM_CP_CONST,
5768       .resetvalue = 0 },
5769     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5770       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5771       .access = PL2_RW, .type = ARM_CP_CONST,
5772       .resetvalue = 0 },
5773     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5774       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5775       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5776       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5777       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5778     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5779       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5780       .type = ARM_CP_ALIAS,
5781       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5782       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5783     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5784       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5785       .access = PL2_RW,
5786       /* no .writefn needed as this can't cause an ASID change;
5787        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5788        */
5789       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5790     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5791       .cp = 15, .opc1 = 6, .crm = 2,
5792       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5793       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5794       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5795       .writefn = vttbr_write },
5796     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5797       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5798       .access = PL2_RW, .writefn = vttbr_write,
5799       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5800     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5801       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5802       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5803       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5804     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5805       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5806       .access = PL2_RW, .resetvalue = 0,
5807       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5808     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5809       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5810       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5811       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5812     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5813       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5814       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5815     { .name = "TLBIALLNSNH",
5816       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5817       .type = ARM_CP_NO_RAW, .access = PL2_W,
5818       .writefn = tlbiall_nsnh_write },
5819     { .name = "TLBIALLNSNHIS",
5820       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5821       .type = ARM_CP_NO_RAW, .access = PL2_W,
5822       .writefn = tlbiall_nsnh_is_write },
5823     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5824       .type = ARM_CP_NO_RAW, .access = PL2_W,
5825       .writefn = tlbiall_hyp_write },
5826     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5827       .type = ARM_CP_NO_RAW, .access = PL2_W,
5828       .writefn = tlbiall_hyp_is_write },
5829     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5830       .type = ARM_CP_NO_RAW, .access = PL2_W,
5831       .writefn = tlbimva_hyp_write },
5832     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5833       .type = ARM_CP_NO_RAW, .access = PL2_W,
5834       .writefn = tlbimva_hyp_is_write },
5835     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5836       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5837       .type = ARM_CP_NO_RAW, .access = PL2_W,
5838       .writefn = tlbi_aa64_alle2_write },
5839     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5840       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5841       .type = ARM_CP_NO_RAW, .access = PL2_W,
5842       .writefn = tlbi_aa64_vae2_write },
5843     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5844       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5845       .access = PL2_W, .type = ARM_CP_NO_RAW,
5846       .writefn = tlbi_aa64_vae2_write },
5847     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5848       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5849       .access = PL2_W, .type = ARM_CP_NO_RAW,
5850       .writefn = tlbi_aa64_alle2is_write },
5851     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5852       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5853       .type = ARM_CP_NO_RAW, .access = PL2_W,
5854       .writefn = tlbi_aa64_vae2is_write },
5855     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5856       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5857       .access = PL2_W, .type = ARM_CP_NO_RAW,
5858       .writefn = tlbi_aa64_vae2is_write },
5859 #ifndef CONFIG_USER_ONLY
5860     /* Unlike the other EL2-related AT operations, these must
5861      * UNDEF from EL3 if EL2 is not implemented, which is why we
5862      * define them here rather than with the rest of the AT ops.
5863      */
5864     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5865       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5866       .access = PL2_W, .accessfn = at_s1e2_access,
5867       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5868     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5869       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5870       .access = PL2_W, .accessfn = at_s1e2_access,
5871       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5872     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5873      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5874      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5875      * to behave as if SCR.NS was 1.
5876      */
5877     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5878       .access = PL2_W,
5879       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5880     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5881       .access = PL2_W,
5882       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5883     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5884       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5885       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5886        * reset values as IMPDEF. We choose to reset to 3 to comply with
5887        * both ARMv7 and ARMv8.
5888        */
5889       .access = PL2_RW, .resetvalue = 3,
5890       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5891     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5892       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5893       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5894       .writefn = gt_cntvoff_write,
5895       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5896     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5897       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5898       .writefn = gt_cntvoff_write,
5899       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5900     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5901       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5902       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5903       .type = ARM_CP_IO, .access = PL2_RW,
5904       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5905     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5906       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5907       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5908       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5909     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5910       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5911       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5912       .resetfn = gt_hyp_timer_reset,
5913       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5914     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5915       .type = ARM_CP_IO,
5916       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5917       .access = PL2_RW,
5918       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5919       .resetvalue = 0,
5920       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5921 #endif
5922     /* The only field of MDCR_EL2 that has a defined architectural reset value
5923      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N.
5924      */
5925     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5926       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5927       .access = PL2_RW, .resetvalue = PMCR_NUM_COUNTERS,
5928       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5929     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5930       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5931       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5932       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5933     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5934       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5935       .access = PL2_RW,
5936       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5937     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5938       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5939       .access = PL2_RW,
5940       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5941     REGINFO_SENTINEL
5942 };
5943 
5944 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5945     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5946       .type = ARM_CP_ALIAS | ARM_CP_IO,
5947       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5948       .access = PL2_RW,
5949       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5950       .writefn = hcr_writehigh },
5951     REGINFO_SENTINEL
5952 };
5953 
5954 static CPAccessResult sel2_access(CPUARMState *env, const ARMCPRegInfo *ri,
5955                                   bool isread)
5956 {
5957     if (arm_current_el(env) == 3 || arm_is_secure_below_el3(env)) {
5958         return CP_ACCESS_OK;
5959     }
5960     return CP_ACCESS_TRAP_UNCATEGORIZED;
5961 }
5962 
5963 static const ARMCPRegInfo el2_sec_cp_reginfo[] = {
5964     { .name = "VSTTBR_EL2", .state = ARM_CP_STATE_AA64,
5965       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 0,
5966       .access = PL2_RW, .accessfn = sel2_access,
5967       .fieldoffset = offsetof(CPUARMState, cp15.vsttbr_el2) },
5968     { .name = "VSTCR_EL2", .state = ARM_CP_STATE_AA64,
5969       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 2,
5970       .access = PL2_RW, .accessfn = sel2_access,
5971       .fieldoffset = offsetof(CPUARMState, cp15.vstcr_el2) },
5972     REGINFO_SENTINEL
5973 };
5974 
5975 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5976                                    bool isread)
5977 {
5978     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5979      * At Secure EL1 it traps to EL3 or EL2.
5980      */
5981     if (arm_current_el(env) == 3) {
5982         return CP_ACCESS_OK;
5983     }
5984     if (arm_is_secure_below_el3(env)) {
5985         if (env->cp15.scr_el3 & SCR_EEL2) {
5986             return CP_ACCESS_TRAP_EL2;
5987         }
5988         return CP_ACCESS_TRAP_EL3;
5989     }
5990     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5991     if (isread) {
5992         return CP_ACCESS_OK;
5993     }
5994     return CP_ACCESS_TRAP_UNCATEGORIZED;
5995 }
5996 
5997 static const ARMCPRegInfo el3_cp_reginfo[] = {
5998     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5999       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
6000       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
6001       .resetfn = scr_reset, .writefn = scr_write },
6002     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
6003       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
6004       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
6005       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
6006       .writefn = scr_write },
6007     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
6008       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
6009       .access = PL3_RW, .resetvalue = 0,
6010       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
6011     { .name = "SDER",
6012       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
6013       .access = PL3_RW, .resetvalue = 0,
6014       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
6015     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
6016       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
6017       .writefn = vbar_write, .resetvalue = 0,
6018       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
6019     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
6020       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
6021       .access = PL3_RW, .resetvalue = 0,
6022       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
6023     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
6024       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
6025       .access = PL3_RW,
6026       /* no .writefn needed as this can't cause an ASID change;
6027        * we must provide a .raw_writefn and .resetfn because we handle
6028        * reset and migration for the AArch32 TTBCR(S), which might be
6029        * using mask and base_mask.
6030        */
6031       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
6032       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
6033     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
6034       .type = ARM_CP_ALIAS,
6035       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
6036       .access = PL3_RW,
6037       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
6038     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
6039       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
6040       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
6041     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
6042       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
6043       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
6044     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
6045       .type = ARM_CP_ALIAS,
6046       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
6047       .access = PL3_RW,
6048       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
6049     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
6050       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
6051       .access = PL3_RW, .writefn = vbar_write,
6052       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
6053       .resetvalue = 0 },
6054     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
6055       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
6056       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
6057       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
6058     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
6059       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
6060       .access = PL3_RW, .resetvalue = 0,
6061       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
6062     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
6063       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
6064       .access = PL3_RW, .type = ARM_CP_CONST,
6065       .resetvalue = 0 },
6066     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
6067       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
6068       .access = PL3_RW, .type = ARM_CP_CONST,
6069       .resetvalue = 0 },
6070     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
6071       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
6072       .access = PL3_RW, .type = ARM_CP_CONST,
6073       .resetvalue = 0 },
6074     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
6075       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
6076       .access = PL3_W, .type = ARM_CP_NO_RAW,
6077       .writefn = tlbi_aa64_alle3is_write },
6078     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
6079       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
6080       .access = PL3_W, .type = ARM_CP_NO_RAW,
6081       .writefn = tlbi_aa64_vae3is_write },
6082     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
6083       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
6084       .access = PL3_W, .type = ARM_CP_NO_RAW,
6085       .writefn = tlbi_aa64_vae3is_write },
6086     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
6087       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
6088       .access = PL3_W, .type = ARM_CP_NO_RAW,
6089       .writefn = tlbi_aa64_alle3_write },
6090     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
6091       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
6092       .access = PL3_W, .type = ARM_CP_NO_RAW,
6093       .writefn = tlbi_aa64_vae3_write },
6094     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
6095       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
6096       .access = PL3_W, .type = ARM_CP_NO_RAW,
6097       .writefn = tlbi_aa64_vae3_write },
6098     REGINFO_SENTINEL
6099 };
6100 
6101 #ifndef CONFIG_USER_ONLY
6102 /* Test if system register redirection is to occur in the current state.  */
6103 static bool redirect_for_e2h(CPUARMState *env)
6104 {
6105     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
6106 }
6107 
6108 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
6109 {
6110     CPReadFn *readfn;
6111 
6112     if (redirect_for_e2h(env)) {
6113         /* Switch to the saved EL2 version of the register.  */
6114         ri = ri->opaque;
6115         readfn = ri->readfn;
6116     } else {
6117         readfn = ri->orig_readfn;
6118     }
6119     if (readfn == NULL) {
6120         readfn = raw_read;
6121     }
6122     return readfn(env, ri);
6123 }
6124 
6125 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
6126                           uint64_t value)
6127 {
6128     CPWriteFn *writefn;
6129 
6130     if (redirect_for_e2h(env)) {
6131         /* Switch to the saved EL2 version of the register.  */
6132         ri = ri->opaque;
6133         writefn = ri->writefn;
6134     } else {
6135         writefn = ri->orig_writefn;
6136     }
6137     if (writefn == NULL) {
6138         writefn = raw_write;
6139     }
6140     writefn(env, ri, value);
6141 }
6142 
6143 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
6144 {
6145     struct E2HAlias {
6146         uint32_t src_key, dst_key, new_key;
6147         const char *src_name, *dst_name, *new_name;
6148         bool (*feature)(const ARMISARegisters *id);
6149     };
6150 
6151 #define K(op0, op1, crn, crm, op2) \
6152     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
6153 
6154     static const struct E2HAlias aliases[] = {
6155         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
6156           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
6157         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
6158           "CPACR", "CPTR_EL2", "CPACR_EL12" },
6159         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
6160           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
6161         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
6162           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
6163         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
6164           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
6165         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
6166           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
6167         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
6168           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
6169         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
6170           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
6171         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
6172           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
6173         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
6174           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
6175         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
6176           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
6177         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
6178           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
6179         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
6180           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
6181         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
6182           "VBAR", "VBAR_EL2", "VBAR_EL12" },
6183         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
6184           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
6185         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
6186           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
6187 
6188         /*
6189          * Note that redirection of ZCR is mentioned in the description
6190          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
6191          * not in the summary table.
6192          */
6193         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
6194           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
6195 
6196         { K(3, 0,  5, 6, 0), K(3, 4,  5, 6, 0), K(3, 5, 5, 6, 0),
6197           "TFSR_EL1", "TFSR_EL2", "TFSR_EL12", isar_feature_aa64_mte },
6198 
6199         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
6200         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
6201     };
6202 #undef K
6203 
6204     size_t i;
6205 
6206     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
6207         const struct E2HAlias *a = &aliases[i];
6208         ARMCPRegInfo *src_reg, *dst_reg;
6209 
6210         if (a->feature && !a->feature(&cpu->isar)) {
6211             continue;
6212         }
6213 
6214         src_reg = g_hash_table_lookup(cpu->cp_regs, &a->src_key);
6215         dst_reg = g_hash_table_lookup(cpu->cp_regs, &a->dst_key);
6216         g_assert(src_reg != NULL);
6217         g_assert(dst_reg != NULL);
6218 
6219         /* Cross-compare names to detect typos in the keys.  */
6220         g_assert(strcmp(src_reg->name, a->src_name) == 0);
6221         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
6222 
6223         /* None of the core system registers use opaque; we will.  */
6224         g_assert(src_reg->opaque == NULL);
6225 
6226         /* Create alias before redirection so we dup the right data. */
6227         if (a->new_key) {
6228             ARMCPRegInfo *new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
6229             uint32_t *new_key = g_memdup(&a->new_key, sizeof(uint32_t));
6230             bool ok;
6231 
6232             new_reg->name = a->new_name;
6233             new_reg->type |= ARM_CP_ALIAS;
6234             /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
6235             new_reg->access &= PL2_RW | PL3_RW;
6236 
6237             ok = g_hash_table_insert(cpu->cp_regs, new_key, new_reg);
6238             g_assert(ok);
6239         }
6240 
6241         src_reg->opaque = dst_reg;
6242         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
6243         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
6244         if (!src_reg->raw_readfn) {
6245             src_reg->raw_readfn = raw_read;
6246         }
6247         if (!src_reg->raw_writefn) {
6248             src_reg->raw_writefn = raw_write;
6249         }
6250         src_reg->readfn = el2_e2h_read;
6251         src_reg->writefn = el2_e2h_write;
6252     }
6253 }
6254 #endif
6255 
6256 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
6257                                      bool isread)
6258 {
6259     int cur_el = arm_current_el(env);
6260 
6261     if (cur_el < 2) {
6262         uint64_t hcr = arm_hcr_el2_eff(env);
6263 
6264         if (cur_el == 0) {
6265             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
6266                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
6267                     return CP_ACCESS_TRAP_EL2;
6268                 }
6269             } else {
6270                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
6271                     return CP_ACCESS_TRAP;
6272                 }
6273                 if (hcr & HCR_TID2) {
6274                     return CP_ACCESS_TRAP_EL2;
6275                 }
6276             }
6277         } else if (hcr & HCR_TID2) {
6278             return CP_ACCESS_TRAP_EL2;
6279         }
6280     }
6281 
6282     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
6283         return CP_ACCESS_TRAP_EL2;
6284     }
6285 
6286     return CP_ACCESS_OK;
6287 }
6288 
6289 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
6290                         uint64_t value)
6291 {
6292     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
6293      * read via a bit in OSLSR_EL1.
6294      */
6295     int oslock;
6296 
6297     if (ri->state == ARM_CP_STATE_AA32) {
6298         oslock = (value == 0xC5ACCE55);
6299     } else {
6300         oslock = value & 1;
6301     }
6302 
6303     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
6304 }
6305 
6306 static const ARMCPRegInfo debug_cp_reginfo[] = {
6307     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
6308      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
6309      * unlike DBGDRAR it is never accessible from EL0.
6310      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
6311      * accessor.
6312      */
6313     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
6314       .access = PL0_R, .accessfn = access_tdra,
6315       .type = ARM_CP_CONST, .resetvalue = 0 },
6316     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
6317       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6318       .access = PL1_R, .accessfn = access_tdra,
6319       .type = ARM_CP_CONST, .resetvalue = 0 },
6320     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
6321       .access = PL0_R, .accessfn = access_tdra,
6322       .type = ARM_CP_CONST, .resetvalue = 0 },
6323     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
6324     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
6325       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
6326       .access = PL1_RW, .accessfn = access_tda,
6327       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
6328       .resetvalue = 0 },
6329     /*
6330      * MDCCSR_EL0[30:29] map to EDSCR[30:29].  Simply RAZ as the external
6331      * Debug Communication Channel is not implemented.
6332      */
6333     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_AA64,
6334       .opc0 = 2, .opc1 = 3, .crn = 0, .crm = 1, .opc2 = 0,
6335       .access = PL0_R, .accessfn = access_tda,
6336       .type = ARM_CP_CONST, .resetvalue = 0 },
6337     /*
6338      * DBGDSCRint[15,12,5:2] map to MDSCR_EL1[15,12,5:2].  Map all bits as
6339      * it is unlikely a guest will care.
6340      * We don't implement the configurable EL0 access.
6341      */
6342     { .name = "DBGDSCRint", .state = ARM_CP_STATE_AA32,
6343       .cp = 14, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6344       .type = ARM_CP_ALIAS,
6345       .access = PL1_R, .accessfn = access_tda,
6346       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
6347     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
6348       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
6349       .access = PL1_W, .type = ARM_CP_NO_RAW,
6350       .accessfn = access_tdosa,
6351       .writefn = oslar_write },
6352     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
6353       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
6354       .access = PL1_R, .resetvalue = 10,
6355       .accessfn = access_tdosa,
6356       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
6357     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
6358     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
6359       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
6360       .access = PL1_RW, .accessfn = access_tdosa,
6361       .type = ARM_CP_NOP },
6362     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
6363      * implement vector catch debug events yet.
6364      */
6365     { .name = "DBGVCR",
6366       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6367       .access = PL1_RW, .accessfn = access_tda,
6368       .type = ARM_CP_NOP },
6369     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
6370      * to save and restore a 32-bit guest's DBGVCR)
6371      */
6372     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
6373       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
6374       .access = PL2_RW, .accessfn = access_tda,
6375       .type = ARM_CP_NOP },
6376     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6377      * Channel but Linux may try to access this register. The 32-bit
6378      * alias is DBGDCCINT.
6379      */
6380     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6381       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6382       .access = PL1_RW, .accessfn = access_tda,
6383       .type = ARM_CP_NOP },
6384     REGINFO_SENTINEL
6385 };
6386 
6387 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6388     /* 64 bit access versions of the (dummy) debug registers */
6389     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6390       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6391     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6392       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6393     REGINFO_SENTINEL
6394 };
6395 
6396 /* Return the exception level to which exceptions should be taken
6397  * via SVEAccessTrap.  If an exception should be routed through
6398  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6399  * take care of raising that exception.
6400  * C.f. the ARM pseudocode function CheckSVEEnabled.
6401  */
6402 int sve_exception_el(CPUARMState *env, int el)
6403 {
6404 #ifndef CONFIG_USER_ONLY
6405     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6406 
6407     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6408         bool disabled = false;
6409 
6410         /* The CPACR.ZEN controls traps to EL1:
6411          * 0, 2 : trap EL0 and EL1 accesses
6412          * 1    : trap only EL0 accesses
6413          * 3    : trap no accesses
6414          */
6415         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
6416             disabled = true;
6417         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
6418             disabled = el == 0;
6419         }
6420         if (disabled) {
6421             /* route_to_el2 */
6422             return hcr_el2 & HCR_TGE ? 2 : 1;
6423         }
6424 
6425         /* Check CPACR.FPEN.  */
6426         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
6427             disabled = true;
6428         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
6429             disabled = el == 0;
6430         }
6431         if (disabled) {
6432             return 0;
6433         }
6434     }
6435 
6436     /* CPTR_EL2.  Since TZ and TFP are positive,
6437      * they will be zero when EL2 is not present.
6438      */
6439     if (el <= 2 && arm_is_el2_enabled(env)) {
6440         if (env->cp15.cptr_el[2] & CPTR_TZ) {
6441             return 2;
6442         }
6443         if (env->cp15.cptr_el[2] & CPTR_TFP) {
6444             return 0;
6445         }
6446     }
6447 
6448     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6449     if (arm_feature(env, ARM_FEATURE_EL3)
6450         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6451         return 3;
6452     }
6453 #endif
6454     return 0;
6455 }
6456 
6457 static uint32_t sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6458 {
6459     uint32_t end_len;
6460 
6461     end_len = start_len &= 0xf;
6462     if (!test_bit(start_len, cpu->sve_vq_map)) {
6463         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6464         assert(end_len < start_len);
6465     }
6466     return end_len;
6467 }
6468 
6469 /*
6470  * Given that SVE is enabled, return the vector length for EL.
6471  */
6472 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6473 {
6474     ARMCPU *cpu = env_archcpu(env);
6475     uint32_t zcr_len = cpu->sve_max_vq - 1;
6476 
6477     if (el <= 1) {
6478         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6479     }
6480     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6481         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6482     }
6483     if (arm_feature(env, ARM_FEATURE_EL3)) {
6484         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6485     }
6486 
6487     return sve_zcr_get_valid_len(cpu, zcr_len);
6488 }
6489 
6490 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6491                       uint64_t value)
6492 {
6493     int cur_el = arm_current_el(env);
6494     int old_len = sve_zcr_len_for_el(env, cur_el);
6495     int new_len;
6496 
6497     /* Bits other than [3:0] are RAZ/WI.  */
6498     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6499     raw_write(env, ri, value & 0xf);
6500 
6501     /*
6502      * Because we arrived here, we know both FP and SVE are enabled;
6503      * otherwise we would have trapped access to the ZCR_ELn register.
6504      */
6505     new_len = sve_zcr_len_for_el(env, cur_el);
6506     if (new_len < old_len) {
6507         aarch64_sve_narrow_vq(env, new_len + 1);
6508     }
6509 }
6510 
6511 static const ARMCPRegInfo zcr_el1_reginfo = {
6512     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6513     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6514     .access = PL1_RW, .type = ARM_CP_SVE,
6515     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6516     .writefn = zcr_write, .raw_writefn = raw_write
6517 };
6518 
6519 static const ARMCPRegInfo zcr_el2_reginfo = {
6520     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6521     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6522     .access = PL2_RW, .type = ARM_CP_SVE,
6523     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6524     .writefn = zcr_write, .raw_writefn = raw_write
6525 };
6526 
6527 static const ARMCPRegInfo zcr_no_el2_reginfo = {
6528     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6529     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6530     .access = PL2_RW, .type = ARM_CP_SVE,
6531     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
6532 };
6533 
6534 static const ARMCPRegInfo zcr_el3_reginfo = {
6535     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6536     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6537     .access = PL3_RW, .type = ARM_CP_SVE,
6538     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6539     .writefn = zcr_write, .raw_writefn = raw_write
6540 };
6541 
6542 void hw_watchpoint_update(ARMCPU *cpu, int n)
6543 {
6544     CPUARMState *env = &cpu->env;
6545     vaddr len = 0;
6546     vaddr wvr = env->cp15.dbgwvr[n];
6547     uint64_t wcr = env->cp15.dbgwcr[n];
6548     int mask;
6549     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6550 
6551     if (env->cpu_watchpoint[n]) {
6552         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6553         env->cpu_watchpoint[n] = NULL;
6554     }
6555 
6556     if (!extract64(wcr, 0, 1)) {
6557         /* E bit clear : watchpoint disabled */
6558         return;
6559     }
6560 
6561     switch (extract64(wcr, 3, 2)) {
6562     case 0:
6563         /* LSC 00 is reserved and must behave as if the wp is disabled */
6564         return;
6565     case 1:
6566         flags |= BP_MEM_READ;
6567         break;
6568     case 2:
6569         flags |= BP_MEM_WRITE;
6570         break;
6571     case 3:
6572         flags |= BP_MEM_ACCESS;
6573         break;
6574     }
6575 
6576     /* Attempts to use both MASK and BAS fields simultaneously are
6577      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6578      * thus generating a watchpoint for every byte in the masked region.
6579      */
6580     mask = extract64(wcr, 24, 4);
6581     if (mask == 1 || mask == 2) {
6582         /* Reserved values of MASK; we must act as if the mask value was
6583          * some non-reserved value, or as if the watchpoint were disabled.
6584          * We choose the latter.
6585          */
6586         return;
6587     } else if (mask) {
6588         /* Watchpoint covers an aligned area up to 2GB in size */
6589         len = 1ULL << mask;
6590         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6591          * whether the watchpoint fires when the unmasked bits match; we opt
6592          * to generate the exceptions.
6593          */
6594         wvr &= ~(len - 1);
6595     } else {
6596         /* Watchpoint covers bytes defined by the byte address select bits */
6597         int bas = extract64(wcr, 5, 8);
6598         int basstart;
6599 
6600         if (extract64(wvr, 2, 1)) {
6601             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6602              * ignored, and BAS[3:0] define which bytes to watch.
6603              */
6604             bas &= 0xf;
6605         }
6606 
6607         if (bas == 0) {
6608             /* This must act as if the watchpoint is disabled */
6609             return;
6610         }
6611 
6612         /* The BAS bits are supposed to be programmed to indicate a contiguous
6613          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6614          * we fire for each byte in the word/doubleword addressed by the WVR.
6615          * We choose to ignore any non-zero bits after the first range of 1s.
6616          */
6617         basstart = ctz32(bas);
6618         len = cto32(bas >> basstart);
6619         wvr += basstart;
6620     }
6621 
6622     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6623                           &env->cpu_watchpoint[n]);
6624 }
6625 
6626 void hw_watchpoint_update_all(ARMCPU *cpu)
6627 {
6628     int i;
6629     CPUARMState *env = &cpu->env;
6630 
6631     /* Completely clear out existing QEMU watchpoints and our array, to
6632      * avoid possible stale entries following migration load.
6633      */
6634     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6635     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6636 
6637     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6638         hw_watchpoint_update(cpu, i);
6639     }
6640 }
6641 
6642 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6643                          uint64_t value)
6644 {
6645     ARMCPU *cpu = env_archcpu(env);
6646     int i = ri->crm;
6647 
6648     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
6649      * register reads and behaves as if values written are sign extended.
6650      * Bits [1:0] are RES0.
6651      */
6652     value = sextract64(value, 0, 49) & ~3ULL;
6653 
6654     raw_write(env, ri, value);
6655     hw_watchpoint_update(cpu, i);
6656 }
6657 
6658 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6659                          uint64_t value)
6660 {
6661     ARMCPU *cpu = env_archcpu(env);
6662     int i = ri->crm;
6663 
6664     raw_write(env, ri, value);
6665     hw_watchpoint_update(cpu, i);
6666 }
6667 
6668 void hw_breakpoint_update(ARMCPU *cpu, int n)
6669 {
6670     CPUARMState *env = &cpu->env;
6671     uint64_t bvr = env->cp15.dbgbvr[n];
6672     uint64_t bcr = env->cp15.dbgbcr[n];
6673     vaddr addr;
6674     int bt;
6675     int flags = BP_CPU;
6676 
6677     if (env->cpu_breakpoint[n]) {
6678         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6679         env->cpu_breakpoint[n] = NULL;
6680     }
6681 
6682     if (!extract64(bcr, 0, 1)) {
6683         /* E bit clear : watchpoint disabled */
6684         return;
6685     }
6686 
6687     bt = extract64(bcr, 20, 4);
6688 
6689     switch (bt) {
6690     case 4: /* unlinked address mismatch (reserved if AArch64) */
6691     case 5: /* linked address mismatch (reserved if AArch64) */
6692         qemu_log_mask(LOG_UNIMP,
6693                       "arm: address mismatch breakpoint types not implemented\n");
6694         return;
6695     case 0: /* unlinked address match */
6696     case 1: /* linked address match */
6697     {
6698         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
6699          * we behave as if the register was sign extended. Bits [1:0] are
6700          * RES0. The BAS field is used to allow setting breakpoints on 16
6701          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6702          * a bp will fire if the addresses covered by the bp and the addresses
6703          * covered by the insn overlap but the insn doesn't start at the
6704          * start of the bp address range. We choose to require the insn and
6705          * the bp to have the same address. The constraints on writing to
6706          * BAS enforced in dbgbcr_write mean we have only four cases:
6707          *  0b0000  => no breakpoint
6708          *  0b0011  => breakpoint on addr
6709          *  0b1100  => breakpoint on addr + 2
6710          *  0b1111  => breakpoint on addr
6711          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6712          */
6713         int bas = extract64(bcr, 5, 4);
6714         addr = sextract64(bvr, 0, 49) & ~3ULL;
6715         if (bas == 0) {
6716             return;
6717         }
6718         if (bas == 0xc) {
6719             addr += 2;
6720         }
6721         break;
6722     }
6723     case 2: /* unlinked context ID match */
6724     case 8: /* unlinked VMID match (reserved if no EL2) */
6725     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6726         qemu_log_mask(LOG_UNIMP,
6727                       "arm: unlinked context breakpoint types not implemented\n");
6728         return;
6729     case 9: /* linked VMID match (reserved if no EL2) */
6730     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6731     case 3: /* linked context ID match */
6732     default:
6733         /* We must generate no events for Linked context matches (unless
6734          * they are linked to by some other bp/wp, which is handled in
6735          * updates for the linking bp/wp). We choose to also generate no events
6736          * for reserved values.
6737          */
6738         return;
6739     }
6740 
6741     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6742 }
6743 
6744 void hw_breakpoint_update_all(ARMCPU *cpu)
6745 {
6746     int i;
6747     CPUARMState *env = &cpu->env;
6748 
6749     /* Completely clear out existing QEMU breakpoints and our array, to
6750      * avoid possible stale entries following migration load.
6751      */
6752     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6753     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6754 
6755     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6756         hw_breakpoint_update(cpu, i);
6757     }
6758 }
6759 
6760 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6761                          uint64_t value)
6762 {
6763     ARMCPU *cpu = env_archcpu(env);
6764     int i = ri->crm;
6765 
6766     raw_write(env, ri, value);
6767     hw_breakpoint_update(cpu, i);
6768 }
6769 
6770 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6771                          uint64_t value)
6772 {
6773     ARMCPU *cpu = env_archcpu(env);
6774     int i = ri->crm;
6775 
6776     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6777      * copy of BAS[0].
6778      */
6779     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6780     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6781 
6782     raw_write(env, ri, value);
6783     hw_breakpoint_update(cpu, i);
6784 }
6785 
6786 static void define_debug_regs(ARMCPU *cpu)
6787 {
6788     /* Define v7 and v8 architectural debug registers.
6789      * These are just dummy implementations for now.
6790      */
6791     int i;
6792     int wrps, brps, ctx_cmps;
6793 
6794     /*
6795      * The Arm ARM says DBGDIDR is optional and deprecated if EL1 cannot
6796      * use AArch32.  Given that bit 15 is RES1, if the value is 0 then
6797      * the register must not exist for this cpu.
6798      */
6799     if (cpu->isar.dbgdidr != 0) {
6800         ARMCPRegInfo dbgdidr = {
6801             .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0,
6802             .opc1 = 0, .opc2 = 0,
6803             .access = PL0_R, .accessfn = access_tda,
6804             .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6805         };
6806         define_one_arm_cp_reg(cpu, &dbgdidr);
6807     }
6808 
6809     /* Note that all these register fields hold "number of Xs minus 1". */
6810     brps = arm_num_brps(cpu);
6811     wrps = arm_num_wrps(cpu);
6812     ctx_cmps = arm_num_ctx_cmps(cpu);
6813 
6814     assert(ctx_cmps <= brps);
6815 
6816     define_arm_cp_regs(cpu, debug_cp_reginfo);
6817 
6818     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6819         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6820     }
6821 
6822     for (i = 0; i < brps; i++) {
6823         ARMCPRegInfo dbgregs[] = {
6824             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6825               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6826               .access = PL1_RW, .accessfn = access_tda,
6827               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6828               .writefn = dbgbvr_write, .raw_writefn = raw_write
6829             },
6830             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6831               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6832               .access = PL1_RW, .accessfn = access_tda,
6833               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6834               .writefn = dbgbcr_write, .raw_writefn = raw_write
6835             },
6836             REGINFO_SENTINEL
6837         };
6838         define_arm_cp_regs(cpu, dbgregs);
6839     }
6840 
6841     for (i = 0; i < wrps; i++) {
6842         ARMCPRegInfo dbgregs[] = {
6843             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6844               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6845               .access = PL1_RW, .accessfn = access_tda,
6846               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6847               .writefn = dbgwvr_write, .raw_writefn = raw_write
6848             },
6849             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6850               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6851               .access = PL1_RW, .accessfn = access_tda,
6852               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6853               .writefn = dbgwcr_write, .raw_writefn = raw_write
6854             },
6855             REGINFO_SENTINEL
6856         };
6857         define_arm_cp_regs(cpu, dbgregs);
6858     }
6859 }
6860 
6861 static void define_pmu_regs(ARMCPU *cpu)
6862 {
6863     /*
6864      * v7 performance monitor control register: same implementor
6865      * field as main ID register, and we implement four counters in
6866      * addition to the cycle count register.
6867      */
6868     unsigned int i, pmcrn = PMCR_NUM_COUNTERS;
6869     ARMCPRegInfo pmcr = {
6870         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6871         .access = PL0_RW,
6872         .type = ARM_CP_IO | ARM_CP_ALIAS,
6873         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6874         .accessfn = pmreg_access, .writefn = pmcr_write,
6875         .raw_writefn = raw_write,
6876     };
6877     ARMCPRegInfo pmcr64 = {
6878         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6879         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6880         .access = PL0_RW, .accessfn = pmreg_access,
6881         .type = ARM_CP_IO,
6882         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6883         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6884                       PMCRLC,
6885         .writefn = pmcr_write, .raw_writefn = raw_write,
6886     };
6887     define_one_arm_cp_reg(cpu, &pmcr);
6888     define_one_arm_cp_reg(cpu, &pmcr64);
6889     for (i = 0; i < pmcrn; i++) {
6890         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6891         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6892         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6893         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6894         ARMCPRegInfo pmev_regs[] = {
6895             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6896               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6897               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6898               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6899               .accessfn = pmreg_access },
6900             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6901               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6902               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6903               .type = ARM_CP_IO,
6904               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6905               .raw_readfn = pmevcntr_rawread,
6906               .raw_writefn = pmevcntr_rawwrite },
6907             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6908               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6909               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6910               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6911               .accessfn = pmreg_access },
6912             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6913               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6914               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6915               .type = ARM_CP_IO,
6916               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6917               .raw_writefn = pmevtyper_rawwrite },
6918             REGINFO_SENTINEL
6919         };
6920         define_arm_cp_regs(cpu, pmev_regs);
6921         g_free(pmevcntr_name);
6922         g_free(pmevcntr_el0_name);
6923         g_free(pmevtyper_name);
6924         g_free(pmevtyper_el0_name);
6925     }
6926     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6927         ARMCPRegInfo v81_pmu_regs[] = {
6928             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6929               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6930               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6931               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6932             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6933               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6934               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6935               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6936             REGINFO_SENTINEL
6937         };
6938         define_arm_cp_regs(cpu, v81_pmu_regs);
6939     }
6940     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6941         static const ARMCPRegInfo v84_pmmir = {
6942             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6943             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6944             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6945             .resetvalue = 0
6946         };
6947         define_one_arm_cp_reg(cpu, &v84_pmmir);
6948     }
6949 }
6950 
6951 /* We don't know until after realize whether there's a GICv3
6952  * attached, and that is what registers the gicv3 sysregs.
6953  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6954  * at runtime.
6955  */
6956 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6957 {
6958     ARMCPU *cpu = env_archcpu(env);
6959     uint64_t pfr1 = cpu->isar.id_pfr1;
6960 
6961     if (env->gicv3state) {
6962         pfr1 |= 1 << 28;
6963     }
6964     return pfr1;
6965 }
6966 
6967 #ifndef CONFIG_USER_ONLY
6968 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6969 {
6970     ARMCPU *cpu = env_archcpu(env);
6971     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6972 
6973     if (env->gicv3state) {
6974         pfr0 |= 1 << 24;
6975     }
6976     return pfr0;
6977 }
6978 #endif
6979 
6980 /* Shared logic between LORID and the rest of the LOR* registers.
6981  * Secure state exclusion has already been dealt with.
6982  */
6983 static CPAccessResult access_lor_ns(CPUARMState *env,
6984                                     const ARMCPRegInfo *ri, bool isread)
6985 {
6986     int el = arm_current_el(env);
6987 
6988     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6989         return CP_ACCESS_TRAP_EL2;
6990     }
6991     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6992         return CP_ACCESS_TRAP_EL3;
6993     }
6994     return CP_ACCESS_OK;
6995 }
6996 
6997 static CPAccessResult access_lor_other(CPUARMState *env,
6998                                        const ARMCPRegInfo *ri, bool isread)
6999 {
7000     if (arm_is_secure_below_el3(env)) {
7001         /* Access denied in secure mode.  */
7002         return CP_ACCESS_TRAP;
7003     }
7004     return access_lor_ns(env, ri, isread);
7005 }
7006 
7007 /*
7008  * A trivial implementation of ARMv8.1-LOR leaves all of these
7009  * registers fixed at 0, which indicates that there are zero
7010  * supported Limited Ordering regions.
7011  */
7012 static const ARMCPRegInfo lor_reginfo[] = {
7013     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
7014       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
7015       .access = PL1_RW, .accessfn = access_lor_other,
7016       .type = ARM_CP_CONST, .resetvalue = 0 },
7017     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
7018       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
7019       .access = PL1_RW, .accessfn = access_lor_other,
7020       .type = ARM_CP_CONST, .resetvalue = 0 },
7021     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
7022       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
7023       .access = PL1_RW, .accessfn = access_lor_other,
7024       .type = ARM_CP_CONST, .resetvalue = 0 },
7025     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
7026       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
7027       .access = PL1_RW, .accessfn = access_lor_other,
7028       .type = ARM_CP_CONST, .resetvalue = 0 },
7029     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
7030       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
7031       .access = PL1_R, .accessfn = access_lor_ns,
7032       .type = ARM_CP_CONST, .resetvalue = 0 },
7033     REGINFO_SENTINEL
7034 };
7035 
7036 #ifdef TARGET_AARCH64
7037 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
7038                                    bool isread)
7039 {
7040     int el = arm_current_el(env);
7041 
7042     if (el < 2 &&
7043         arm_feature(env, ARM_FEATURE_EL2) &&
7044         !(arm_hcr_el2_eff(env) & HCR_APK)) {
7045         return CP_ACCESS_TRAP_EL2;
7046     }
7047     if (el < 3 &&
7048         arm_feature(env, ARM_FEATURE_EL3) &&
7049         !(env->cp15.scr_el3 & SCR_APK)) {
7050         return CP_ACCESS_TRAP_EL3;
7051     }
7052     return CP_ACCESS_OK;
7053 }
7054 
7055 static const ARMCPRegInfo pauth_reginfo[] = {
7056     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
7057       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
7058       .access = PL1_RW, .accessfn = access_pauth,
7059       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
7060     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
7061       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
7062       .access = PL1_RW, .accessfn = access_pauth,
7063       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
7064     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
7065       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
7066       .access = PL1_RW, .accessfn = access_pauth,
7067       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
7068     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
7069       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
7070       .access = PL1_RW, .accessfn = access_pauth,
7071       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
7072     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
7073       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
7074       .access = PL1_RW, .accessfn = access_pauth,
7075       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
7076     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
7077       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
7078       .access = PL1_RW, .accessfn = access_pauth,
7079       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
7080     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
7081       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
7082       .access = PL1_RW, .accessfn = access_pauth,
7083       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
7084     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
7085       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
7086       .access = PL1_RW, .accessfn = access_pauth,
7087       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
7088     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
7089       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
7090       .access = PL1_RW, .accessfn = access_pauth,
7091       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
7092     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
7093       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
7094       .access = PL1_RW, .accessfn = access_pauth,
7095       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
7096     REGINFO_SENTINEL
7097 };
7098 
7099 static const ARMCPRegInfo tlbirange_reginfo[] = {
7100     { .name = "TLBI_RVAE1IS", .state = ARM_CP_STATE_AA64,
7101       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 1,
7102       .access = PL1_W, .type = ARM_CP_NO_RAW,
7103       .writefn = tlbi_aa64_rvae1is_write },
7104     { .name = "TLBI_RVAAE1IS", .state = ARM_CP_STATE_AA64,
7105       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 3,
7106       .access = PL1_W, .type = ARM_CP_NO_RAW,
7107       .writefn = tlbi_aa64_rvae1is_write },
7108    { .name = "TLBI_RVALE1IS", .state = ARM_CP_STATE_AA64,
7109       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 5,
7110       .access = PL1_W, .type = ARM_CP_NO_RAW,
7111       .writefn = tlbi_aa64_rvae1is_write },
7112     { .name = "TLBI_RVAALE1IS", .state = ARM_CP_STATE_AA64,
7113       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 7,
7114       .access = PL1_W, .type = ARM_CP_NO_RAW,
7115       .writefn = tlbi_aa64_rvae1is_write },
7116     { .name = "TLBI_RVAE1OS", .state = ARM_CP_STATE_AA64,
7117       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
7118       .access = PL1_W, .type = ARM_CP_NO_RAW,
7119       .writefn = tlbi_aa64_rvae1is_write },
7120     { .name = "TLBI_RVAAE1OS", .state = ARM_CP_STATE_AA64,
7121       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 3,
7122       .access = PL1_W, .type = ARM_CP_NO_RAW,
7123       .writefn = tlbi_aa64_rvae1is_write },
7124    { .name = "TLBI_RVALE1OS", .state = ARM_CP_STATE_AA64,
7125       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 5,
7126       .access = PL1_W, .type = ARM_CP_NO_RAW,
7127       .writefn = tlbi_aa64_rvae1is_write },
7128     { .name = "TLBI_RVAALE1OS", .state = ARM_CP_STATE_AA64,
7129       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 7,
7130       .access = PL1_W, .type = ARM_CP_NO_RAW,
7131       .writefn = tlbi_aa64_rvae1is_write },
7132     { .name = "TLBI_RVAE1", .state = ARM_CP_STATE_AA64,
7133       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
7134       .access = PL1_W, .type = ARM_CP_NO_RAW,
7135       .writefn = tlbi_aa64_rvae1_write },
7136     { .name = "TLBI_RVAAE1", .state = ARM_CP_STATE_AA64,
7137       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 3,
7138       .access = PL1_W, .type = ARM_CP_NO_RAW,
7139       .writefn = tlbi_aa64_rvae1_write },
7140    { .name = "TLBI_RVALE1", .state = ARM_CP_STATE_AA64,
7141       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 5,
7142       .access = PL1_W, .type = ARM_CP_NO_RAW,
7143       .writefn = tlbi_aa64_rvae1_write },
7144     { .name = "TLBI_RVAALE1", .state = ARM_CP_STATE_AA64,
7145       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 7,
7146       .access = PL1_W, .type = ARM_CP_NO_RAW,
7147       .writefn = tlbi_aa64_rvae1_write },
7148     { .name = "TLBI_RIPAS2E1IS", .state = ARM_CP_STATE_AA64,
7149       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 2,
7150       .access = PL2_W, .type = ARM_CP_NOP },
7151     { .name = "TLBI_RIPAS2LE1IS", .state = ARM_CP_STATE_AA64,
7152       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 6,
7153       .access = PL2_W, .type = ARM_CP_NOP },
7154     { .name = "TLBI_RVAE2IS", .state = ARM_CP_STATE_AA64,
7155       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 1,
7156       .access = PL2_W, .type = ARM_CP_NO_RAW,
7157       .writefn = tlbi_aa64_rvae2is_write },
7158    { .name = "TLBI_RVALE2IS", .state = ARM_CP_STATE_AA64,
7159       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 5,
7160       .access = PL2_W, .type = ARM_CP_NO_RAW,
7161       .writefn = tlbi_aa64_rvae2is_write },
7162     { .name = "TLBI_RIPAS2E1", .state = ARM_CP_STATE_AA64,
7163       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 2,
7164       .access = PL2_W, .type = ARM_CP_NOP },
7165    { .name = "TLBI_RIPAS2LE1", .state = ARM_CP_STATE_AA64,
7166       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 6,
7167       .access = PL2_W, .type = ARM_CP_NOP },
7168    { .name = "TLBI_RVAE2OS", .state = ARM_CP_STATE_AA64,
7169       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 1,
7170       .access = PL2_W, .type = ARM_CP_NO_RAW,
7171       .writefn = tlbi_aa64_rvae2is_write },
7172    { .name = "TLBI_RVALE2OS", .state = ARM_CP_STATE_AA64,
7173       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 5,
7174       .access = PL2_W, .type = ARM_CP_NO_RAW,
7175       .writefn = tlbi_aa64_rvae2is_write },
7176     { .name = "TLBI_RVAE2", .state = ARM_CP_STATE_AA64,
7177       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 1,
7178       .access = PL2_W, .type = ARM_CP_NO_RAW,
7179       .writefn = tlbi_aa64_rvae2_write },
7180    { .name = "TLBI_RVALE2", .state = ARM_CP_STATE_AA64,
7181       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 5,
7182       .access = PL2_W, .type = ARM_CP_NO_RAW,
7183       .writefn = tlbi_aa64_rvae2_write },
7184    { .name = "TLBI_RVAE3IS", .state = ARM_CP_STATE_AA64,
7185       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 1,
7186       .access = PL3_W, .type = ARM_CP_NO_RAW,
7187       .writefn = tlbi_aa64_rvae3is_write },
7188    { .name = "TLBI_RVALE3IS", .state = ARM_CP_STATE_AA64,
7189       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 5,
7190       .access = PL3_W, .type = ARM_CP_NO_RAW,
7191       .writefn = tlbi_aa64_rvae3is_write },
7192    { .name = "TLBI_RVAE3OS", .state = ARM_CP_STATE_AA64,
7193       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 1,
7194       .access = PL3_W, .type = ARM_CP_NO_RAW,
7195       .writefn = tlbi_aa64_rvae3is_write },
7196    { .name = "TLBI_RVALE3OS", .state = ARM_CP_STATE_AA64,
7197       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 5,
7198       .access = PL3_W, .type = ARM_CP_NO_RAW,
7199       .writefn = tlbi_aa64_rvae3is_write },
7200    { .name = "TLBI_RVAE3", .state = ARM_CP_STATE_AA64,
7201       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 1,
7202       .access = PL3_W, .type = ARM_CP_NO_RAW,
7203       .writefn = tlbi_aa64_rvae3_write },
7204    { .name = "TLBI_RVALE3", .state = ARM_CP_STATE_AA64,
7205       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 5,
7206       .access = PL3_W, .type = ARM_CP_NO_RAW,
7207       .writefn = tlbi_aa64_rvae3_write },
7208     REGINFO_SENTINEL
7209 };
7210 
7211 static const ARMCPRegInfo tlbios_reginfo[] = {
7212     { .name = "TLBI_VMALLE1OS", .state = ARM_CP_STATE_AA64,
7213       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 0,
7214       .access = PL1_W, .type = ARM_CP_NO_RAW,
7215       .writefn = tlbi_aa64_vmalle1is_write },
7216     { .name = "TLBI_ASIDE1OS", .state = ARM_CP_STATE_AA64,
7217       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 2,
7218       .access = PL1_W, .type = ARM_CP_NO_RAW,
7219       .writefn = tlbi_aa64_vmalle1is_write },
7220     { .name = "TLBI_ALLE2OS", .state = ARM_CP_STATE_AA64,
7221       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 0,
7222       .access = PL2_W, .type = ARM_CP_NO_RAW,
7223       .writefn = tlbi_aa64_alle2is_write },
7224    { .name = "TLBI_ALLE1OS", .state = ARM_CP_STATE_AA64,
7225       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 4,
7226       .access = PL2_W, .type = ARM_CP_NO_RAW,
7227       .writefn = tlbi_aa64_alle1is_write },
7228     { .name = "TLBI_VMALLS12E1OS", .state = ARM_CP_STATE_AA64,
7229       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 6,
7230       .access = PL2_W, .type = ARM_CP_NO_RAW,
7231       .writefn = tlbi_aa64_alle1is_write },
7232     { .name = "TLBI_IPAS2E1OS", .state = ARM_CP_STATE_AA64,
7233       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 0,
7234       .access = PL2_W, .type = ARM_CP_NOP },
7235     { .name = "TLBI_RIPAS2E1OS", .state = ARM_CP_STATE_AA64,
7236       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 3,
7237       .access = PL2_W, .type = ARM_CP_NOP },
7238     { .name = "TLBI_IPAS2LE1OS", .state = ARM_CP_STATE_AA64,
7239       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 4,
7240       .access = PL2_W, .type = ARM_CP_NOP },
7241     { .name = "TLBI_RIPAS2LE1OS", .state = ARM_CP_STATE_AA64,
7242       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 7,
7243       .access = PL2_W, .type = ARM_CP_NOP },
7244     { .name = "TLBI_ALLE3OS", .state = ARM_CP_STATE_AA64,
7245       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 0,
7246       .access = PL3_W, .type = ARM_CP_NO_RAW,
7247       .writefn = tlbi_aa64_alle3is_write },
7248     REGINFO_SENTINEL
7249 };
7250 
7251 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
7252 {
7253     Error *err = NULL;
7254     uint64_t ret;
7255 
7256     /* Success sets NZCV = 0000.  */
7257     env->NF = env->CF = env->VF = 0, env->ZF = 1;
7258 
7259     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
7260         /*
7261          * ??? Failed, for unknown reasons in the crypto subsystem.
7262          * The best we can do is log the reason and return the
7263          * timed-out indication to the guest.  There is no reason
7264          * we know to expect this failure to be transitory, so the
7265          * guest may well hang retrying the operation.
7266          */
7267         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
7268                       ri->name, error_get_pretty(err));
7269         error_free(err);
7270 
7271         env->ZF = 0; /* NZCF = 0100 */
7272         return 0;
7273     }
7274     return ret;
7275 }
7276 
7277 /* We do not support re-seeding, so the two registers operate the same.  */
7278 static const ARMCPRegInfo rndr_reginfo[] = {
7279     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
7280       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7281       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
7282       .access = PL0_R, .readfn = rndr_readfn },
7283     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
7284       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7285       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
7286       .access = PL0_R, .readfn = rndr_readfn },
7287     REGINFO_SENTINEL
7288 };
7289 
7290 #ifndef CONFIG_USER_ONLY
7291 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
7292                           uint64_t value)
7293 {
7294     ARMCPU *cpu = env_archcpu(env);
7295     /* CTR_EL0 System register -> DminLine, bits [19:16] */
7296     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
7297     uint64_t vaddr_in = (uint64_t) value;
7298     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
7299     void *haddr;
7300     int mem_idx = cpu_mmu_index(env, false);
7301 
7302     /* This won't be crossing page boundaries */
7303     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
7304     if (haddr) {
7305 
7306         ram_addr_t offset;
7307         MemoryRegion *mr;
7308 
7309         /* RCU lock is already being held */
7310         mr = memory_region_from_host(haddr, &offset);
7311 
7312         if (mr) {
7313             memory_region_writeback(mr, offset, dline_size);
7314         }
7315     }
7316 }
7317 
7318 static const ARMCPRegInfo dcpop_reg[] = {
7319     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
7320       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
7321       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7322       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7323     REGINFO_SENTINEL
7324 };
7325 
7326 static const ARMCPRegInfo dcpodp_reg[] = {
7327     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
7328       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
7329       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7330       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7331     REGINFO_SENTINEL
7332 };
7333 #endif /*CONFIG_USER_ONLY*/
7334 
7335 static CPAccessResult access_aa64_tid5(CPUARMState *env, const ARMCPRegInfo *ri,
7336                                        bool isread)
7337 {
7338     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID5)) {
7339         return CP_ACCESS_TRAP_EL2;
7340     }
7341 
7342     return CP_ACCESS_OK;
7343 }
7344 
7345 static CPAccessResult access_mte(CPUARMState *env, const ARMCPRegInfo *ri,
7346                                  bool isread)
7347 {
7348     int el = arm_current_el(env);
7349 
7350     if (el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
7351         uint64_t hcr = arm_hcr_el2_eff(env);
7352         if (!(hcr & HCR_ATA) && (!(hcr & HCR_E2H) || !(hcr & HCR_TGE))) {
7353             return CP_ACCESS_TRAP_EL2;
7354         }
7355     }
7356     if (el < 3 &&
7357         arm_feature(env, ARM_FEATURE_EL3) &&
7358         !(env->cp15.scr_el3 & SCR_ATA)) {
7359         return CP_ACCESS_TRAP_EL3;
7360     }
7361     return CP_ACCESS_OK;
7362 }
7363 
7364 static uint64_t tco_read(CPUARMState *env, const ARMCPRegInfo *ri)
7365 {
7366     return env->pstate & PSTATE_TCO;
7367 }
7368 
7369 static void tco_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
7370 {
7371     env->pstate = (env->pstate & ~PSTATE_TCO) | (val & PSTATE_TCO);
7372 }
7373 
7374 static const ARMCPRegInfo mte_reginfo[] = {
7375     { .name = "TFSRE0_EL1", .state = ARM_CP_STATE_AA64,
7376       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 1,
7377       .access = PL1_RW, .accessfn = access_mte,
7378       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[0]) },
7379     { .name = "TFSR_EL1", .state = ARM_CP_STATE_AA64,
7380       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 0,
7381       .access = PL1_RW, .accessfn = access_mte,
7382       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[1]) },
7383     { .name = "TFSR_EL2", .state = ARM_CP_STATE_AA64,
7384       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 6, .opc2 = 0,
7385       .access = PL2_RW, .accessfn = access_mte,
7386       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[2]) },
7387     { .name = "TFSR_EL3", .state = ARM_CP_STATE_AA64,
7388       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 6, .opc2 = 0,
7389       .access = PL3_RW,
7390       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[3]) },
7391     { .name = "RGSR_EL1", .state = ARM_CP_STATE_AA64,
7392       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 5,
7393       .access = PL1_RW, .accessfn = access_mte,
7394       .fieldoffset = offsetof(CPUARMState, cp15.rgsr_el1) },
7395     { .name = "GCR_EL1", .state = ARM_CP_STATE_AA64,
7396       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 6,
7397       .access = PL1_RW, .accessfn = access_mte,
7398       .fieldoffset = offsetof(CPUARMState, cp15.gcr_el1) },
7399     { .name = "GMID_EL1", .state = ARM_CP_STATE_AA64,
7400       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 4,
7401       .access = PL1_R, .accessfn = access_aa64_tid5,
7402       .type = ARM_CP_CONST, .resetvalue = GMID_EL1_BS },
7403     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7404       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7405       .type = ARM_CP_NO_RAW,
7406       .access = PL0_RW, .readfn = tco_read, .writefn = tco_write },
7407     { .name = "DC_IGVAC", .state = ARM_CP_STATE_AA64,
7408       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 3,
7409       .type = ARM_CP_NOP, .access = PL1_W,
7410       .accessfn = aa64_cacheop_poc_access },
7411     { .name = "DC_IGSW", .state = ARM_CP_STATE_AA64,
7412       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 4,
7413       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7414     { .name = "DC_IGDVAC", .state = ARM_CP_STATE_AA64,
7415       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 5,
7416       .type = ARM_CP_NOP, .access = PL1_W,
7417       .accessfn = aa64_cacheop_poc_access },
7418     { .name = "DC_IGDSW", .state = ARM_CP_STATE_AA64,
7419       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 6,
7420       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7421     { .name = "DC_CGSW", .state = ARM_CP_STATE_AA64,
7422       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 4,
7423       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7424     { .name = "DC_CGDSW", .state = ARM_CP_STATE_AA64,
7425       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 6,
7426       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7427     { .name = "DC_CIGSW", .state = ARM_CP_STATE_AA64,
7428       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 4,
7429       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7430     { .name = "DC_CIGDSW", .state = ARM_CP_STATE_AA64,
7431       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 6,
7432       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7433     REGINFO_SENTINEL
7434 };
7435 
7436 static const ARMCPRegInfo mte_tco_ro_reginfo[] = {
7437     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7438       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7439       .type = ARM_CP_CONST, .access = PL0_RW, },
7440     REGINFO_SENTINEL
7441 };
7442 
7443 static const ARMCPRegInfo mte_el0_cacheop_reginfo[] = {
7444     { .name = "DC_CGVAC", .state = ARM_CP_STATE_AA64,
7445       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 3,
7446       .type = ARM_CP_NOP, .access = PL0_W,
7447       .accessfn = aa64_cacheop_poc_access },
7448     { .name = "DC_CGDVAC", .state = ARM_CP_STATE_AA64,
7449       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 5,
7450       .type = ARM_CP_NOP, .access = PL0_W,
7451       .accessfn = aa64_cacheop_poc_access },
7452     { .name = "DC_CGVAP", .state = ARM_CP_STATE_AA64,
7453       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 3,
7454       .type = ARM_CP_NOP, .access = PL0_W,
7455       .accessfn = aa64_cacheop_poc_access },
7456     { .name = "DC_CGDVAP", .state = ARM_CP_STATE_AA64,
7457       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 5,
7458       .type = ARM_CP_NOP, .access = PL0_W,
7459       .accessfn = aa64_cacheop_poc_access },
7460     { .name = "DC_CGVADP", .state = ARM_CP_STATE_AA64,
7461       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 3,
7462       .type = ARM_CP_NOP, .access = PL0_W,
7463       .accessfn = aa64_cacheop_poc_access },
7464     { .name = "DC_CGDVADP", .state = ARM_CP_STATE_AA64,
7465       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 5,
7466       .type = ARM_CP_NOP, .access = PL0_W,
7467       .accessfn = aa64_cacheop_poc_access },
7468     { .name = "DC_CIGVAC", .state = ARM_CP_STATE_AA64,
7469       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 3,
7470       .type = ARM_CP_NOP, .access = PL0_W,
7471       .accessfn = aa64_cacheop_poc_access },
7472     { .name = "DC_CIGDVAC", .state = ARM_CP_STATE_AA64,
7473       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 5,
7474       .type = ARM_CP_NOP, .access = PL0_W,
7475       .accessfn = aa64_cacheop_poc_access },
7476     { .name = "DC_GVA", .state = ARM_CP_STATE_AA64,
7477       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 3,
7478       .access = PL0_W, .type = ARM_CP_DC_GVA,
7479 #ifndef CONFIG_USER_ONLY
7480       /* Avoid overhead of an access check that always passes in user-mode */
7481       .accessfn = aa64_zva_access,
7482 #endif
7483     },
7484     { .name = "DC_GZVA", .state = ARM_CP_STATE_AA64,
7485       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 4,
7486       .access = PL0_W, .type = ARM_CP_DC_GZVA,
7487 #ifndef CONFIG_USER_ONLY
7488       /* Avoid overhead of an access check that always passes in user-mode */
7489       .accessfn = aa64_zva_access,
7490 #endif
7491     },
7492     REGINFO_SENTINEL
7493 };
7494 
7495 #endif
7496 
7497 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
7498                                      bool isread)
7499 {
7500     int el = arm_current_el(env);
7501 
7502     if (el == 0) {
7503         uint64_t sctlr = arm_sctlr(env, el);
7504         if (!(sctlr & SCTLR_EnRCTX)) {
7505             return CP_ACCESS_TRAP;
7506         }
7507     } else if (el == 1) {
7508         uint64_t hcr = arm_hcr_el2_eff(env);
7509         if (hcr & HCR_NV) {
7510             return CP_ACCESS_TRAP_EL2;
7511         }
7512     }
7513     return CP_ACCESS_OK;
7514 }
7515 
7516 static const ARMCPRegInfo predinv_reginfo[] = {
7517     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
7518       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
7519       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7520     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
7521       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
7522       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7523     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
7524       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
7525       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7526     /*
7527      * Note the AArch32 opcodes have a different OPC1.
7528      */
7529     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
7530       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
7531       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7532     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
7533       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
7534       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7535     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
7536       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
7537       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7538     REGINFO_SENTINEL
7539 };
7540 
7541 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
7542 {
7543     /* Read the high 32 bits of the current CCSIDR */
7544     return extract64(ccsidr_read(env, ri), 32, 32);
7545 }
7546 
7547 static const ARMCPRegInfo ccsidr2_reginfo[] = {
7548     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
7549       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
7550       .access = PL1_R,
7551       .accessfn = access_aa64_tid2,
7552       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7553     REGINFO_SENTINEL
7554 };
7555 
7556 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7557                                        bool isread)
7558 {
7559     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7560         return CP_ACCESS_TRAP_EL2;
7561     }
7562 
7563     return CP_ACCESS_OK;
7564 }
7565 
7566 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7567                                        bool isread)
7568 {
7569     if (arm_feature(env, ARM_FEATURE_V8)) {
7570         return access_aa64_tid3(env, ri, isread);
7571     }
7572 
7573     return CP_ACCESS_OK;
7574 }
7575 
7576 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7577                                      bool isread)
7578 {
7579     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7580         return CP_ACCESS_TRAP_EL2;
7581     }
7582 
7583     return CP_ACCESS_OK;
7584 }
7585 
7586 static const ARMCPRegInfo jazelle_regs[] = {
7587     { .name = "JIDR",
7588       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7589       .access = PL1_R, .accessfn = access_jazelle,
7590       .type = ARM_CP_CONST, .resetvalue = 0 },
7591     { .name = "JOSCR",
7592       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7593       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7594     { .name = "JMCR",
7595       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7596       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7597     REGINFO_SENTINEL
7598 };
7599 
7600 static const ARMCPRegInfo vhe_reginfo[] = {
7601     { .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7602       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7603       .access = PL2_RW,
7604       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2]) },
7605     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7606       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7607       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7608       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7609 #ifndef CONFIG_USER_ONLY
7610     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7611       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7612       .fieldoffset =
7613         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7614       .type = ARM_CP_IO, .access = PL2_RW,
7615       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7616     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7617       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7618       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7619       .resetfn = gt_hv_timer_reset,
7620       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7621     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7622       .type = ARM_CP_IO,
7623       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7624       .access = PL2_RW,
7625       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7626       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7627     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7628       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7629       .type = ARM_CP_IO | ARM_CP_ALIAS,
7630       .access = PL2_RW, .accessfn = e2h_access,
7631       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7632       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7633     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7634       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7635       .type = ARM_CP_IO | ARM_CP_ALIAS,
7636       .access = PL2_RW, .accessfn = e2h_access,
7637       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7638       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7639     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7640       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7641       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7642       .access = PL2_RW, .accessfn = e2h_access,
7643       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7644     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7645       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7646       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7647       .access = PL2_RW, .accessfn = e2h_access,
7648       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7649     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7650       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7651       .type = ARM_CP_IO | ARM_CP_ALIAS,
7652       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7653       .access = PL2_RW, .accessfn = e2h_access,
7654       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7655     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7656       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7657       .type = ARM_CP_IO | ARM_CP_ALIAS,
7658       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7659       .access = PL2_RW, .accessfn = e2h_access,
7660       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7661 #endif
7662     REGINFO_SENTINEL
7663 };
7664 
7665 #ifndef CONFIG_USER_ONLY
7666 static const ARMCPRegInfo ats1e1_reginfo[] = {
7667     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7668       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7669       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7670       .writefn = ats_write64 },
7671     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7672       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7673       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7674       .writefn = ats_write64 },
7675     REGINFO_SENTINEL
7676 };
7677 
7678 static const ARMCPRegInfo ats1cp_reginfo[] = {
7679     { .name = "ATS1CPRP",
7680       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7681       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7682       .writefn = ats_write },
7683     { .name = "ATS1CPWP",
7684       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7685       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7686       .writefn = ats_write },
7687     REGINFO_SENTINEL
7688 };
7689 #endif
7690 
7691 /*
7692  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7693  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7694  * is non-zero, which is never for ARMv7, optionally in ARMv8
7695  * and mandatorily for ARMv8.2 and up.
7696  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7697  * implementation is RAZ/WI we can ignore this detail, as we
7698  * do for ACTLR.
7699  */
7700 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7701     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7702       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7703       .access = PL1_RW, .accessfn = access_tacr,
7704       .type = ARM_CP_CONST, .resetvalue = 0 },
7705     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7706       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7707       .access = PL2_RW, .type = ARM_CP_CONST,
7708       .resetvalue = 0 },
7709     REGINFO_SENTINEL
7710 };
7711 
7712 void register_cp_regs_for_features(ARMCPU *cpu)
7713 {
7714     /* Register all the coprocessor registers based on feature bits */
7715     CPUARMState *env = &cpu->env;
7716     if (arm_feature(env, ARM_FEATURE_M)) {
7717         /* M profile has no coprocessor registers */
7718         return;
7719     }
7720 
7721     define_arm_cp_regs(cpu, cp_reginfo);
7722     if (!arm_feature(env, ARM_FEATURE_V8)) {
7723         /* Must go early as it is full of wildcards that may be
7724          * overridden by later definitions.
7725          */
7726         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7727     }
7728 
7729     if (arm_feature(env, ARM_FEATURE_V6)) {
7730         /* The ID registers all have impdef reset values */
7731         ARMCPRegInfo v6_idregs[] = {
7732             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7733               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7734               .access = PL1_R, .type = ARM_CP_CONST,
7735               .accessfn = access_aa32_tid3,
7736               .resetvalue = cpu->isar.id_pfr0 },
7737             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7738              * the value of the GIC field until after we define these regs.
7739              */
7740             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7741               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7742               .access = PL1_R, .type = ARM_CP_NO_RAW,
7743               .accessfn = access_aa32_tid3,
7744               .readfn = id_pfr1_read,
7745               .writefn = arm_cp_write_ignore },
7746             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7747               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7748               .access = PL1_R, .type = ARM_CP_CONST,
7749               .accessfn = access_aa32_tid3,
7750               .resetvalue = cpu->isar.id_dfr0 },
7751             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7752               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7753               .access = PL1_R, .type = ARM_CP_CONST,
7754               .accessfn = access_aa32_tid3,
7755               .resetvalue = cpu->id_afr0 },
7756             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7757               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7758               .access = PL1_R, .type = ARM_CP_CONST,
7759               .accessfn = access_aa32_tid3,
7760               .resetvalue = cpu->isar.id_mmfr0 },
7761             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7762               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7763               .access = PL1_R, .type = ARM_CP_CONST,
7764               .accessfn = access_aa32_tid3,
7765               .resetvalue = cpu->isar.id_mmfr1 },
7766             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7767               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7768               .access = PL1_R, .type = ARM_CP_CONST,
7769               .accessfn = access_aa32_tid3,
7770               .resetvalue = cpu->isar.id_mmfr2 },
7771             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7772               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7773               .access = PL1_R, .type = ARM_CP_CONST,
7774               .accessfn = access_aa32_tid3,
7775               .resetvalue = cpu->isar.id_mmfr3 },
7776             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7777               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7778               .access = PL1_R, .type = ARM_CP_CONST,
7779               .accessfn = access_aa32_tid3,
7780               .resetvalue = cpu->isar.id_isar0 },
7781             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7782               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7783               .access = PL1_R, .type = ARM_CP_CONST,
7784               .accessfn = access_aa32_tid3,
7785               .resetvalue = cpu->isar.id_isar1 },
7786             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7787               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7788               .access = PL1_R, .type = ARM_CP_CONST,
7789               .accessfn = access_aa32_tid3,
7790               .resetvalue = cpu->isar.id_isar2 },
7791             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7792               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7793               .access = PL1_R, .type = ARM_CP_CONST,
7794               .accessfn = access_aa32_tid3,
7795               .resetvalue = cpu->isar.id_isar3 },
7796             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7797               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7798               .access = PL1_R, .type = ARM_CP_CONST,
7799               .accessfn = access_aa32_tid3,
7800               .resetvalue = cpu->isar.id_isar4 },
7801             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7802               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7803               .access = PL1_R, .type = ARM_CP_CONST,
7804               .accessfn = access_aa32_tid3,
7805               .resetvalue = cpu->isar.id_isar5 },
7806             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7807               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7808               .access = PL1_R, .type = ARM_CP_CONST,
7809               .accessfn = access_aa32_tid3,
7810               .resetvalue = cpu->isar.id_mmfr4 },
7811             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7812               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7813               .access = PL1_R, .type = ARM_CP_CONST,
7814               .accessfn = access_aa32_tid3,
7815               .resetvalue = cpu->isar.id_isar6 },
7816             REGINFO_SENTINEL
7817         };
7818         define_arm_cp_regs(cpu, v6_idregs);
7819         define_arm_cp_regs(cpu, v6_cp_reginfo);
7820     } else {
7821         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7822     }
7823     if (arm_feature(env, ARM_FEATURE_V6K)) {
7824         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7825     }
7826     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7827         !arm_feature(env, ARM_FEATURE_PMSA)) {
7828         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7829     }
7830     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7831         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7832     }
7833     if (arm_feature(env, ARM_FEATURE_V7)) {
7834         ARMCPRegInfo clidr = {
7835             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7836             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7837             .access = PL1_R, .type = ARM_CP_CONST,
7838             .accessfn = access_aa64_tid2,
7839             .resetvalue = cpu->clidr
7840         };
7841         define_one_arm_cp_reg(cpu, &clidr);
7842         define_arm_cp_regs(cpu, v7_cp_reginfo);
7843         define_debug_regs(cpu);
7844         define_pmu_regs(cpu);
7845     } else {
7846         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7847     }
7848     if (arm_feature(env, ARM_FEATURE_V8)) {
7849         /* AArch64 ID registers, which all have impdef reset values.
7850          * Note that within the ID register ranges the unused slots
7851          * must all RAZ, not UNDEF; future architecture versions may
7852          * define new registers here.
7853          */
7854         ARMCPRegInfo v8_idregs[] = {
7855             /*
7856              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7857              * emulation because we don't know the right value for the
7858              * GIC field until after we define these regs.
7859              */
7860             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7861               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7862               .access = PL1_R,
7863 #ifdef CONFIG_USER_ONLY
7864               .type = ARM_CP_CONST,
7865               .resetvalue = cpu->isar.id_aa64pfr0
7866 #else
7867               .type = ARM_CP_NO_RAW,
7868               .accessfn = access_aa64_tid3,
7869               .readfn = id_aa64pfr0_read,
7870               .writefn = arm_cp_write_ignore
7871 #endif
7872             },
7873             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7874               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7875               .access = PL1_R, .type = ARM_CP_CONST,
7876               .accessfn = access_aa64_tid3,
7877               .resetvalue = cpu->isar.id_aa64pfr1},
7878             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7879               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7880               .access = PL1_R, .type = ARM_CP_CONST,
7881               .accessfn = access_aa64_tid3,
7882               .resetvalue = 0 },
7883             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7884               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7885               .access = PL1_R, .type = ARM_CP_CONST,
7886               .accessfn = access_aa64_tid3,
7887               .resetvalue = 0 },
7888             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7889               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7890               .access = PL1_R, .type = ARM_CP_CONST,
7891               .accessfn = access_aa64_tid3,
7892               .resetvalue = cpu->isar.id_aa64zfr0 },
7893             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7894               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7895               .access = PL1_R, .type = ARM_CP_CONST,
7896               .accessfn = access_aa64_tid3,
7897               .resetvalue = 0 },
7898             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7899               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7900               .access = PL1_R, .type = ARM_CP_CONST,
7901               .accessfn = access_aa64_tid3,
7902               .resetvalue = 0 },
7903             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7904               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7905               .access = PL1_R, .type = ARM_CP_CONST,
7906               .accessfn = access_aa64_tid3,
7907               .resetvalue = 0 },
7908             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7909               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7910               .access = PL1_R, .type = ARM_CP_CONST,
7911               .accessfn = access_aa64_tid3,
7912               .resetvalue = cpu->isar.id_aa64dfr0 },
7913             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7914               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7915               .access = PL1_R, .type = ARM_CP_CONST,
7916               .accessfn = access_aa64_tid3,
7917               .resetvalue = cpu->isar.id_aa64dfr1 },
7918             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7919               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7920               .access = PL1_R, .type = ARM_CP_CONST,
7921               .accessfn = access_aa64_tid3,
7922               .resetvalue = 0 },
7923             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7924               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7925               .access = PL1_R, .type = ARM_CP_CONST,
7926               .accessfn = access_aa64_tid3,
7927               .resetvalue = 0 },
7928             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7929               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7930               .access = PL1_R, .type = ARM_CP_CONST,
7931               .accessfn = access_aa64_tid3,
7932               .resetvalue = cpu->id_aa64afr0 },
7933             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7934               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7935               .access = PL1_R, .type = ARM_CP_CONST,
7936               .accessfn = access_aa64_tid3,
7937               .resetvalue = cpu->id_aa64afr1 },
7938             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7939               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7940               .access = PL1_R, .type = ARM_CP_CONST,
7941               .accessfn = access_aa64_tid3,
7942               .resetvalue = 0 },
7943             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7944               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7945               .access = PL1_R, .type = ARM_CP_CONST,
7946               .accessfn = access_aa64_tid3,
7947               .resetvalue = 0 },
7948             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7949               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7950               .access = PL1_R, .type = ARM_CP_CONST,
7951               .accessfn = access_aa64_tid3,
7952               .resetvalue = cpu->isar.id_aa64isar0 },
7953             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7954               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7955               .access = PL1_R, .type = ARM_CP_CONST,
7956               .accessfn = access_aa64_tid3,
7957               .resetvalue = cpu->isar.id_aa64isar1 },
7958             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7959               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7960               .access = PL1_R, .type = ARM_CP_CONST,
7961               .accessfn = access_aa64_tid3,
7962               .resetvalue = 0 },
7963             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7964               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7965               .access = PL1_R, .type = ARM_CP_CONST,
7966               .accessfn = access_aa64_tid3,
7967               .resetvalue = 0 },
7968             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7969               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7970               .access = PL1_R, .type = ARM_CP_CONST,
7971               .accessfn = access_aa64_tid3,
7972               .resetvalue = 0 },
7973             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7974               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7975               .access = PL1_R, .type = ARM_CP_CONST,
7976               .accessfn = access_aa64_tid3,
7977               .resetvalue = 0 },
7978             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7979               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7980               .access = PL1_R, .type = ARM_CP_CONST,
7981               .accessfn = access_aa64_tid3,
7982               .resetvalue = 0 },
7983             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7984               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7985               .access = PL1_R, .type = ARM_CP_CONST,
7986               .accessfn = access_aa64_tid3,
7987               .resetvalue = 0 },
7988             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7989               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7990               .access = PL1_R, .type = ARM_CP_CONST,
7991               .accessfn = access_aa64_tid3,
7992               .resetvalue = cpu->isar.id_aa64mmfr0 },
7993             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7994               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7995               .access = PL1_R, .type = ARM_CP_CONST,
7996               .accessfn = access_aa64_tid3,
7997               .resetvalue = cpu->isar.id_aa64mmfr1 },
7998             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7999               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
8000               .access = PL1_R, .type = ARM_CP_CONST,
8001               .accessfn = access_aa64_tid3,
8002               .resetvalue = cpu->isar.id_aa64mmfr2 },
8003             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8004               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
8005               .access = PL1_R, .type = ARM_CP_CONST,
8006               .accessfn = access_aa64_tid3,
8007               .resetvalue = 0 },
8008             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8009               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
8010               .access = PL1_R, .type = ARM_CP_CONST,
8011               .accessfn = access_aa64_tid3,
8012               .resetvalue = 0 },
8013             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8014               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
8015               .access = PL1_R, .type = ARM_CP_CONST,
8016               .accessfn = access_aa64_tid3,
8017               .resetvalue = 0 },
8018             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8019               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
8020               .access = PL1_R, .type = ARM_CP_CONST,
8021               .accessfn = access_aa64_tid3,
8022               .resetvalue = 0 },
8023             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8024               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
8025               .access = PL1_R, .type = ARM_CP_CONST,
8026               .accessfn = access_aa64_tid3,
8027               .resetvalue = 0 },
8028             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
8029               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
8030               .access = PL1_R, .type = ARM_CP_CONST,
8031               .accessfn = access_aa64_tid3,
8032               .resetvalue = cpu->isar.mvfr0 },
8033             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
8034               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
8035               .access = PL1_R, .type = ARM_CP_CONST,
8036               .accessfn = access_aa64_tid3,
8037               .resetvalue = cpu->isar.mvfr1 },
8038             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
8039               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
8040               .access = PL1_R, .type = ARM_CP_CONST,
8041               .accessfn = access_aa64_tid3,
8042               .resetvalue = cpu->isar.mvfr2 },
8043             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8044               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
8045               .access = PL1_R, .type = ARM_CP_CONST,
8046               .accessfn = access_aa64_tid3,
8047               .resetvalue = 0 },
8048             { .name = "ID_PFR2", .state = ARM_CP_STATE_BOTH,
8049               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
8050               .access = PL1_R, .type = ARM_CP_CONST,
8051               .accessfn = access_aa64_tid3,
8052               .resetvalue = cpu->isar.id_pfr2 },
8053             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8054               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
8055               .access = PL1_R, .type = ARM_CP_CONST,
8056               .accessfn = access_aa64_tid3,
8057               .resetvalue = 0 },
8058             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8059               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
8060               .access = PL1_R, .type = ARM_CP_CONST,
8061               .accessfn = access_aa64_tid3,
8062               .resetvalue = 0 },
8063             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8064               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
8065               .access = PL1_R, .type = ARM_CP_CONST,
8066               .accessfn = access_aa64_tid3,
8067               .resetvalue = 0 },
8068             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
8069               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
8070               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
8071               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
8072             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
8073               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
8074               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
8075               .resetvalue = cpu->pmceid0 },
8076             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
8077               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
8078               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
8079               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
8080             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
8081               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
8082               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
8083               .resetvalue = cpu->pmceid1 },
8084             REGINFO_SENTINEL
8085         };
8086 #ifdef CONFIG_USER_ONLY
8087         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
8088             { .name = "ID_AA64PFR0_EL1",
8089               .exported_bits = 0x000f000f00ff0000,
8090               .fixed_bits    = 0x0000000000000011 },
8091             { .name = "ID_AA64PFR1_EL1",
8092               .exported_bits = 0x00000000000000f0 },
8093             { .name = "ID_AA64PFR*_EL1_RESERVED",
8094               .is_glob = true                     },
8095             { .name = "ID_AA64ZFR0_EL1"           },
8096             { .name = "ID_AA64MMFR0_EL1",
8097               .fixed_bits    = 0x00000000ff000000 },
8098             { .name = "ID_AA64MMFR1_EL1"          },
8099             { .name = "ID_AA64MMFR*_EL1_RESERVED",
8100               .is_glob = true                     },
8101             { .name = "ID_AA64DFR0_EL1",
8102               .fixed_bits    = 0x0000000000000006 },
8103             { .name = "ID_AA64DFR1_EL1"           },
8104             { .name = "ID_AA64DFR*_EL1_RESERVED",
8105               .is_glob = true                     },
8106             { .name = "ID_AA64AFR*",
8107               .is_glob = true                     },
8108             { .name = "ID_AA64ISAR0_EL1",
8109               .exported_bits = 0x00fffffff0fffff0 },
8110             { .name = "ID_AA64ISAR1_EL1",
8111               .exported_bits = 0x000000f0ffffffff },
8112             { .name = "ID_AA64ISAR*_EL1_RESERVED",
8113               .is_glob = true                     },
8114             REGUSERINFO_SENTINEL
8115         };
8116         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
8117 #endif
8118         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
8119         if (!arm_feature(env, ARM_FEATURE_EL3) &&
8120             !arm_feature(env, ARM_FEATURE_EL2)) {
8121             ARMCPRegInfo rvbar = {
8122                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
8123                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
8124                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
8125             };
8126             define_one_arm_cp_reg(cpu, &rvbar);
8127         }
8128         define_arm_cp_regs(cpu, v8_idregs);
8129         define_arm_cp_regs(cpu, v8_cp_reginfo);
8130     }
8131     if (arm_feature(env, ARM_FEATURE_EL2)) {
8132         uint64_t vmpidr_def = mpidr_read_val(env);
8133         ARMCPRegInfo vpidr_regs[] = {
8134             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
8135               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
8136               .access = PL2_RW, .accessfn = access_el3_aa32ns,
8137               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
8138               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
8139             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
8140               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
8141               .access = PL2_RW, .resetvalue = cpu->midr,
8142               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
8143             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
8144               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
8145               .access = PL2_RW, .accessfn = access_el3_aa32ns,
8146               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
8147               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
8148             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
8149               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
8150               .access = PL2_RW,
8151               .resetvalue = vmpidr_def,
8152               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
8153             REGINFO_SENTINEL
8154         };
8155         define_arm_cp_regs(cpu, vpidr_regs);
8156         define_arm_cp_regs(cpu, el2_cp_reginfo);
8157         if (arm_feature(env, ARM_FEATURE_V8)) {
8158             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
8159         }
8160         if (cpu_isar_feature(aa64_sel2, cpu)) {
8161             define_arm_cp_regs(cpu, el2_sec_cp_reginfo);
8162         }
8163         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
8164         if (!arm_feature(env, ARM_FEATURE_EL3)) {
8165             ARMCPRegInfo rvbar = {
8166                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
8167                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
8168                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
8169             };
8170             define_one_arm_cp_reg(cpu, &rvbar);
8171         }
8172     } else {
8173         /* If EL2 is missing but higher ELs are enabled, we need to
8174          * register the no_el2 reginfos.
8175          */
8176         if (arm_feature(env, ARM_FEATURE_EL3)) {
8177             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
8178              * of MIDR_EL1 and MPIDR_EL1.
8179              */
8180             ARMCPRegInfo vpidr_regs[] = {
8181                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
8182                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
8183                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
8184                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
8185                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
8186                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
8187                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
8188                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
8189                   .type = ARM_CP_NO_RAW,
8190                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
8191                 REGINFO_SENTINEL
8192             };
8193             define_arm_cp_regs(cpu, vpidr_regs);
8194             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
8195             if (arm_feature(env, ARM_FEATURE_V8)) {
8196                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
8197             }
8198         }
8199     }
8200     if (arm_feature(env, ARM_FEATURE_EL3)) {
8201         define_arm_cp_regs(cpu, el3_cp_reginfo);
8202         ARMCPRegInfo el3_regs[] = {
8203             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
8204               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
8205               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
8206             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
8207               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
8208               .access = PL3_RW,
8209               .raw_writefn = raw_write, .writefn = sctlr_write,
8210               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
8211               .resetvalue = cpu->reset_sctlr },
8212             REGINFO_SENTINEL
8213         };
8214 
8215         define_arm_cp_regs(cpu, el3_regs);
8216     }
8217     /* The behaviour of NSACR is sufficiently various that we don't
8218      * try to describe it in a single reginfo:
8219      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
8220      *     reads as constant 0xc00 from NS EL1 and NS EL2
8221      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
8222      *  if v7 without EL3, register doesn't exist
8223      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
8224      */
8225     if (arm_feature(env, ARM_FEATURE_EL3)) {
8226         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8227             ARMCPRegInfo nsacr = {
8228                 .name = "NSACR", .type = ARM_CP_CONST,
8229                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8230                 .access = PL1_RW, .accessfn = nsacr_access,
8231                 .resetvalue = 0xc00
8232             };
8233             define_one_arm_cp_reg(cpu, &nsacr);
8234         } else {
8235             ARMCPRegInfo nsacr = {
8236                 .name = "NSACR",
8237                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8238                 .access = PL3_RW | PL1_R,
8239                 .resetvalue = 0,
8240                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
8241             };
8242             define_one_arm_cp_reg(cpu, &nsacr);
8243         }
8244     } else {
8245         if (arm_feature(env, ARM_FEATURE_V8)) {
8246             ARMCPRegInfo nsacr = {
8247                 .name = "NSACR", .type = ARM_CP_CONST,
8248                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8249                 .access = PL1_R,
8250                 .resetvalue = 0xc00
8251             };
8252             define_one_arm_cp_reg(cpu, &nsacr);
8253         }
8254     }
8255 
8256     if (arm_feature(env, ARM_FEATURE_PMSA)) {
8257         if (arm_feature(env, ARM_FEATURE_V6)) {
8258             /* PMSAv6 not implemented */
8259             assert(arm_feature(env, ARM_FEATURE_V7));
8260             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8261             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
8262         } else {
8263             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
8264         }
8265     } else {
8266         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8267         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
8268         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
8269         if (cpu_isar_feature(aa32_hpd, cpu)) {
8270             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
8271         }
8272     }
8273     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
8274         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
8275     }
8276     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
8277         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
8278     }
8279     if (arm_feature(env, ARM_FEATURE_VAPA)) {
8280         define_arm_cp_regs(cpu, vapa_cp_reginfo);
8281     }
8282     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
8283         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
8284     }
8285     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
8286         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
8287     }
8288     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
8289         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
8290     }
8291     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
8292         define_arm_cp_regs(cpu, omap_cp_reginfo);
8293     }
8294     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
8295         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
8296     }
8297     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8298         define_arm_cp_regs(cpu, xscale_cp_reginfo);
8299     }
8300     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
8301         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
8302     }
8303     if (arm_feature(env, ARM_FEATURE_LPAE)) {
8304         define_arm_cp_regs(cpu, lpae_cp_reginfo);
8305     }
8306     if (cpu_isar_feature(aa32_jazelle, cpu)) {
8307         define_arm_cp_regs(cpu, jazelle_regs);
8308     }
8309     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
8310      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
8311      * be read-only (ie write causes UNDEF exception).
8312      */
8313     {
8314         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
8315             /* Pre-v8 MIDR space.
8316              * Note that the MIDR isn't a simple constant register because
8317              * of the TI925 behaviour where writes to another register can
8318              * cause the MIDR value to change.
8319              *
8320              * Unimplemented registers in the c15 0 0 0 space default to
8321              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
8322              * and friends override accordingly.
8323              */
8324             { .name = "MIDR",
8325               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
8326               .access = PL1_R, .resetvalue = cpu->midr,
8327               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
8328               .readfn = midr_read,
8329               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8330               .type = ARM_CP_OVERRIDE },
8331             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
8332             { .name = "DUMMY",
8333               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
8334               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8335             { .name = "DUMMY",
8336               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
8337               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8338             { .name = "DUMMY",
8339               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
8340               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8341             { .name = "DUMMY",
8342               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
8343               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8344             { .name = "DUMMY",
8345               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
8346               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8347             REGINFO_SENTINEL
8348         };
8349         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
8350             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
8351               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
8352               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
8353               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8354               .readfn = midr_read },
8355             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
8356             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8357               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8358               .access = PL1_R, .resetvalue = cpu->midr },
8359             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8360               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
8361               .access = PL1_R, .resetvalue = cpu->midr },
8362             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
8363               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
8364               .access = PL1_R,
8365               .accessfn = access_aa64_tid1,
8366               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
8367             REGINFO_SENTINEL
8368         };
8369         ARMCPRegInfo id_cp_reginfo[] = {
8370             /* These are common to v8 and pre-v8 */
8371             { .name = "CTR",
8372               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
8373               .access = PL1_R, .accessfn = ctr_el0_access,
8374               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8375             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
8376               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
8377               .access = PL0_R, .accessfn = ctr_el0_access,
8378               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8379             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
8380             { .name = "TCMTR",
8381               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
8382               .access = PL1_R,
8383               .accessfn = access_aa32_tid1,
8384               .type = ARM_CP_CONST, .resetvalue = 0 },
8385             REGINFO_SENTINEL
8386         };
8387         /* TLBTR is specific to VMSA */
8388         ARMCPRegInfo id_tlbtr_reginfo = {
8389               .name = "TLBTR",
8390               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
8391               .access = PL1_R,
8392               .accessfn = access_aa32_tid1,
8393               .type = ARM_CP_CONST, .resetvalue = 0,
8394         };
8395         /* MPUIR is specific to PMSA V6+ */
8396         ARMCPRegInfo id_mpuir_reginfo = {
8397               .name = "MPUIR",
8398               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8399               .access = PL1_R, .type = ARM_CP_CONST,
8400               .resetvalue = cpu->pmsav7_dregion << 8
8401         };
8402         ARMCPRegInfo crn0_wi_reginfo = {
8403             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
8404             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
8405             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
8406         };
8407 #ifdef CONFIG_USER_ONLY
8408         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
8409             { .name = "MIDR_EL1",
8410               .exported_bits = 0x00000000ffffffff },
8411             { .name = "REVIDR_EL1"                },
8412             REGUSERINFO_SENTINEL
8413         };
8414         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
8415 #endif
8416         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
8417             arm_feature(env, ARM_FEATURE_STRONGARM)) {
8418             ARMCPRegInfo *r;
8419             /* Register the blanket "writes ignored" value first to cover the
8420              * whole space. Then update the specific ID registers to allow write
8421              * access, so that they ignore writes rather than causing them to
8422              * UNDEF.
8423              */
8424             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
8425             for (r = id_pre_v8_midr_cp_reginfo;
8426                  r->type != ARM_CP_SENTINEL; r++) {
8427                 r->access = PL1_RW;
8428             }
8429             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
8430                 r->access = PL1_RW;
8431             }
8432             id_mpuir_reginfo.access = PL1_RW;
8433             id_tlbtr_reginfo.access = PL1_RW;
8434         }
8435         if (arm_feature(env, ARM_FEATURE_V8)) {
8436             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
8437         } else {
8438             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
8439         }
8440         define_arm_cp_regs(cpu, id_cp_reginfo);
8441         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
8442             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
8443         } else if (arm_feature(env, ARM_FEATURE_V7)) {
8444             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
8445         }
8446     }
8447 
8448     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
8449         ARMCPRegInfo mpidr_cp_reginfo[] = {
8450             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
8451               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
8452               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
8453             REGINFO_SENTINEL
8454         };
8455 #ifdef CONFIG_USER_ONLY
8456         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
8457             { .name = "MPIDR_EL1",
8458               .fixed_bits = 0x0000000080000000 },
8459             REGUSERINFO_SENTINEL
8460         };
8461         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
8462 #endif
8463         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
8464     }
8465 
8466     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
8467         ARMCPRegInfo auxcr_reginfo[] = {
8468             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
8469               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
8470               .access = PL1_RW, .accessfn = access_tacr,
8471               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
8472             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
8473               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
8474               .access = PL2_RW, .type = ARM_CP_CONST,
8475               .resetvalue = 0 },
8476             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
8477               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
8478               .access = PL3_RW, .type = ARM_CP_CONST,
8479               .resetvalue = 0 },
8480             REGINFO_SENTINEL
8481         };
8482         define_arm_cp_regs(cpu, auxcr_reginfo);
8483         if (cpu_isar_feature(aa32_ac2, cpu)) {
8484             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
8485         }
8486     }
8487 
8488     if (arm_feature(env, ARM_FEATURE_CBAR)) {
8489         /*
8490          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
8491          * There are two flavours:
8492          *  (1) older 32-bit only cores have a simple 32-bit CBAR
8493          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
8494          *      32-bit register visible to AArch32 at a different encoding
8495          *      to the "flavour 1" register and with the bits rearranged to
8496          *      be able to squash a 64-bit address into the 32-bit view.
8497          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
8498          * in future if we support AArch32-only configs of some of the
8499          * AArch64 cores we might need to add a specific feature flag
8500          * to indicate cores with "flavour 2" CBAR.
8501          */
8502         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8503             /* 32 bit view is [31:18] 0...0 [43:32]. */
8504             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
8505                 | extract64(cpu->reset_cbar, 32, 12);
8506             ARMCPRegInfo cbar_reginfo[] = {
8507                 { .name = "CBAR",
8508                   .type = ARM_CP_CONST,
8509                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
8510                   .access = PL1_R, .resetvalue = cbar32 },
8511                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
8512                   .type = ARM_CP_CONST,
8513                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
8514                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
8515                 REGINFO_SENTINEL
8516             };
8517             /* We don't implement a r/w 64 bit CBAR currently */
8518             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
8519             define_arm_cp_regs(cpu, cbar_reginfo);
8520         } else {
8521             ARMCPRegInfo cbar = {
8522                 .name = "CBAR",
8523                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
8524                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
8525                 .fieldoffset = offsetof(CPUARMState,
8526                                         cp15.c15_config_base_address)
8527             };
8528             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
8529                 cbar.access = PL1_R;
8530                 cbar.fieldoffset = 0;
8531                 cbar.type = ARM_CP_CONST;
8532             }
8533             define_one_arm_cp_reg(cpu, &cbar);
8534         }
8535     }
8536 
8537     if (arm_feature(env, ARM_FEATURE_VBAR)) {
8538         ARMCPRegInfo vbar_cp_reginfo[] = {
8539             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
8540               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
8541               .access = PL1_RW, .writefn = vbar_write,
8542               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
8543                                      offsetof(CPUARMState, cp15.vbar_ns) },
8544               .resetvalue = 0 },
8545             REGINFO_SENTINEL
8546         };
8547         define_arm_cp_regs(cpu, vbar_cp_reginfo);
8548     }
8549 
8550     /* Generic registers whose values depend on the implementation */
8551     {
8552         ARMCPRegInfo sctlr = {
8553             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8554             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8555             .access = PL1_RW, .accessfn = access_tvm_trvm,
8556             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8557                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8558             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8559             .raw_writefn = raw_write,
8560         };
8561         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8562             /* Normally we would always end the TB on an SCTLR write, but Linux
8563              * arch/arm/mach-pxa/sleep.S expects two instructions following
8564              * an MMU enable to execute from cache.  Imitate this behaviour.
8565              */
8566             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8567         }
8568         define_one_arm_cp_reg(cpu, &sctlr);
8569     }
8570 
8571     if (cpu_isar_feature(aa64_lor, cpu)) {
8572         define_arm_cp_regs(cpu, lor_reginfo);
8573     }
8574     if (cpu_isar_feature(aa64_pan, cpu)) {
8575         define_one_arm_cp_reg(cpu, &pan_reginfo);
8576     }
8577 #ifndef CONFIG_USER_ONLY
8578     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8579         define_arm_cp_regs(cpu, ats1e1_reginfo);
8580     }
8581     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8582         define_arm_cp_regs(cpu, ats1cp_reginfo);
8583     }
8584 #endif
8585     if (cpu_isar_feature(aa64_uao, cpu)) {
8586         define_one_arm_cp_reg(cpu, &uao_reginfo);
8587     }
8588 
8589     if (cpu_isar_feature(aa64_dit, cpu)) {
8590         define_one_arm_cp_reg(cpu, &dit_reginfo);
8591     }
8592     if (cpu_isar_feature(aa64_ssbs, cpu)) {
8593         define_one_arm_cp_reg(cpu, &ssbs_reginfo);
8594     }
8595 
8596     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8597         define_arm_cp_regs(cpu, vhe_reginfo);
8598     }
8599 
8600     if (cpu_isar_feature(aa64_sve, cpu)) {
8601         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
8602         if (arm_feature(env, ARM_FEATURE_EL2)) {
8603             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
8604         } else {
8605             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
8606         }
8607         if (arm_feature(env, ARM_FEATURE_EL3)) {
8608             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
8609         }
8610     }
8611 
8612 #ifdef TARGET_AARCH64
8613     if (cpu_isar_feature(aa64_pauth, cpu)) {
8614         define_arm_cp_regs(cpu, pauth_reginfo);
8615     }
8616     if (cpu_isar_feature(aa64_rndr, cpu)) {
8617         define_arm_cp_regs(cpu, rndr_reginfo);
8618     }
8619     if (cpu_isar_feature(aa64_tlbirange, cpu)) {
8620         define_arm_cp_regs(cpu, tlbirange_reginfo);
8621     }
8622     if (cpu_isar_feature(aa64_tlbios, cpu)) {
8623         define_arm_cp_regs(cpu, tlbios_reginfo);
8624     }
8625 #ifndef CONFIG_USER_ONLY
8626     /* Data Cache clean instructions up to PoP */
8627     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8628         define_one_arm_cp_reg(cpu, dcpop_reg);
8629 
8630         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8631             define_one_arm_cp_reg(cpu, dcpodp_reg);
8632         }
8633     }
8634 #endif /*CONFIG_USER_ONLY*/
8635 
8636     /*
8637      * If full MTE is enabled, add all of the system registers.
8638      * If only "instructions available at EL0" are enabled,
8639      * then define only a RAZ/WI version of PSTATE.TCO.
8640      */
8641     if (cpu_isar_feature(aa64_mte, cpu)) {
8642         define_arm_cp_regs(cpu, mte_reginfo);
8643         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8644     } else if (cpu_isar_feature(aa64_mte_insn_reg, cpu)) {
8645         define_arm_cp_regs(cpu, mte_tco_ro_reginfo);
8646         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8647     }
8648 #endif
8649 
8650     if (cpu_isar_feature(any_predinv, cpu)) {
8651         define_arm_cp_regs(cpu, predinv_reginfo);
8652     }
8653 
8654     if (cpu_isar_feature(any_ccidx, cpu)) {
8655         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8656     }
8657 
8658 #ifndef CONFIG_USER_ONLY
8659     /*
8660      * Register redirections and aliases must be done last,
8661      * after the registers from the other extensions have been defined.
8662      */
8663     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8664         define_arm_vh_e2h_redirects_aliases(cpu);
8665     }
8666 #endif
8667 }
8668 
8669 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
8670 {
8671     CPUState *cs = CPU(cpu);
8672     CPUARMState *env = &cpu->env;
8673 
8674     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8675         /*
8676          * The lower part of each SVE register aliases to the FPU
8677          * registers so we don't need to include both.
8678          */
8679 #ifdef TARGET_AARCH64
8680         if (isar_feature_aa64_sve(&cpu->isar)) {
8681             gdb_register_coprocessor(cs, arm_gdb_get_svereg, arm_gdb_set_svereg,
8682                                      arm_gen_dynamic_svereg_xml(cs, cs->gdb_num_regs),
8683                                      "sve-registers.xml", 0);
8684         } else
8685 #endif
8686         {
8687             gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
8688                                      aarch64_fpu_gdb_set_reg,
8689                                      34, "aarch64-fpu.xml", 0);
8690         }
8691     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
8692         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8693                                  51, "arm-neon.xml", 0);
8694     } else if (cpu_isar_feature(aa32_simd_r32, cpu)) {
8695         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8696                                  35, "arm-vfp3.xml", 0);
8697     } else if (cpu_isar_feature(aa32_vfp_simd, cpu)) {
8698         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8699                                  19, "arm-vfp.xml", 0);
8700     }
8701     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
8702                              arm_gen_dynamic_sysreg_xml(cs, cs->gdb_num_regs),
8703                              "system-registers.xml", 0);
8704 
8705 }
8706 
8707 /* Sort alphabetically by type name, except for "any". */
8708 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8709 {
8710     ObjectClass *class_a = (ObjectClass *)a;
8711     ObjectClass *class_b = (ObjectClass *)b;
8712     const char *name_a, *name_b;
8713 
8714     name_a = object_class_get_name(class_a);
8715     name_b = object_class_get_name(class_b);
8716     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8717         return 1;
8718     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8719         return -1;
8720     } else {
8721         return strcmp(name_a, name_b);
8722     }
8723 }
8724 
8725 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8726 {
8727     ObjectClass *oc = data;
8728     const char *typename;
8729     char *name;
8730 
8731     typename = object_class_get_name(oc);
8732     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8733     qemu_printf("  %s\n", name);
8734     g_free(name);
8735 }
8736 
8737 void arm_cpu_list(void)
8738 {
8739     GSList *list;
8740 
8741     list = object_class_get_list(TYPE_ARM_CPU, false);
8742     list = g_slist_sort(list, arm_cpu_list_compare);
8743     qemu_printf("Available CPUs:\n");
8744     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8745     g_slist_free(list);
8746 }
8747 
8748 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8749 {
8750     ObjectClass *oc = data;
8751     CpuDefinitionInfoList **cpu_list = user_data;
8752     CpuDefinitionInfo *info;
8753     const char *typename;
8754 
8755     typename = object_class_get_name(oc);
8756     info = g_malloc0(sizeof(*info));
8757     info->name = g_strndup(typename,
8758                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8759     info->q_typename = g_strdup(typename);
8760 
8761     QAPI_LIST_PREPEND(*cpu_list, info);
8762 }
8763 
8764 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8765 {
8766     CpuDefinitionInfoList *cpu_list = NULL;
8767     GSList *list;
8768 
8769     list = object_class_get_list(TYPE_ARM_CPU, false);
8770     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8771     g_slist_free(list);
8772 
8773     return cpu_list;
8774 }
8775 
8776 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8777                                    void *opaque, int state, int secstate,
8778                                    int crm, int opc1, int opc2,
8779                                    const char *name)
8780 {
8781     /* Private utility function for define_one_arm_cp_reg_with_opaque():
8782      * add a single reginfo struct to the hash table.
8783      */
8784     uint32_t *key = g_new(uint32_t, 1);
8785     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
8786     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
8787     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
8788 
8789     r2->name = g_strdup(name);
8790     /* Reset the secure state to the specific incoming state.  This is
8791      * necessary as the register may have been defined with both states.
8792      */
8793     r2->secure = secstate;
8794 
8795     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8796         /* Register is banked (using both entries in array).
8797          * Overwriting fieldoffset as the array is only used to define
8798          * banked registers but later only fieldoffset is used.
8799          */
8800         r2->fieldoffset = r->bank_fieldoffsets[ns];
8801     }
8802 
8803     if (state == ARM_CP_STATE_AA32) {
8804         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8805             /* If the register is banked then we don't need to migrate or
8806              * reset the 32-bit instance in certain cases:
8807              *
8808              * 1) If the register has both 32-bit and 64-bit instances then we
8809              *    can count on the 64-bit instance taking care of the
8810              *    non-secure bank.
8811              * 2) If ARMv8 is enabled then we can count on a 64-bit version
8812              *    taking care of the secure bank.  This requires that separate
8813              *    32 and 64-bit definitions are provided.
8814              */
8815             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8816                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
8817                 r2->type |= ARM_CP_ALIAS;
8818             }
8819         } else if ((secstate != r->secure) && !ns) {
8820             /* The register is not banked so we only want to allow migration of
8821              * the non-secure instance.
8822              */
8823             r2->type |= ARM_CP_ALIAS;
8824         }
8825 
8826         if (r->state == ARM_CP_STATE_BOTH) {
8827             /* We assume it is a cp15 register if the .cp field is left unset.
8828              */
8829             if (r2->cp == 0) {
8830                 r2->cp = 15;
8831             }
8832 
8833 #ifdef HOST_WORDS_BIGENDIAN
8834             if (r2->fieldoffset) {
8835                 r2->fieldoffset += sizeof(uint32_t);
8836             }
8837 #endif
8838         }
8839     }
8840     if (state == ARM_CP_STATE_AA64) {
8841         /* To allow abbreviation of ARMCPRegInfo
8842          * definitions, we treat cp == 0 as equivalent to
8843          * the value for "standard guest-visible sysreg".
8844          * STATE_BOTH definitions are also always "standard
8845          * sysreg" in their AArch64 view (the .cp value may
8846          * be non-zero for the benefit of the AArch32 view).
8847          */
8848         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8849             r2->cp = CP_REG_ARM64_SYSREG_CP;
8850         }
8851         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
8852                                   r2->opc0, opc1, opc2);
8853     } else {
8854         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
8855     }
8856     if (opaque) {
8857         r2->opaque = opaque;
8858     }
8859     /* reginfo passed to helpers is correct for the actual access,
8860      * and is never ARM_CP_STATE_BOTH:
8861      */
8862     r2->state = state;
8863     /* Make sure reginfo passed to helpers for wildcarded regs
8864      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
8865      */
8866     r2->crm = crm;
8867     r2->opc1 = opc1;
8868     r2->opc2 = opc2;
8869     /* By convention, for wildcarded registers only the first
8870      * entry is used for migration; the others are marked as
8871      * ALIAS so we don't try to transfer the register
8872      * multiple times. Special registers (ie NOP/WFI) are
8873      * never migratable and not even raw-accessible.
8874      */
8875     if ((r->type & ARM_CP_SPECIAL)) {
8876         r2->type |= ARM_CP_NO_RAW;
8877     }
8878     if (((r->crm == CP_ANY) && crm != 0) ||
8879         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8880         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8881         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8882     }
8883 
8884     /* Check that raw accesses are either forbidden or handled. Note that
8885      * we can't assert this earlier because the setup of fieldoffset for
8886      * banked registers has to be done first.
8887      */
8888     if (!(r2->type & ARM_CP_NO_RAW)) {
8889         assert(!raw_accessors_invalid(r2));
8890     }
8891 
8892     /* Overriding of an existing definition must be explicitly
8893      * requested.
8894      */
8895     if (!(r->type & ARM_CP_OVERRIDE)) {
8896         ARMCPRegInfo *oldreg;
8897         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
8898         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
8899             fprintf(stderr, "Register redefined: cp=%d %d bit "
8900                     "crn=%d crm=%d opc1=%d opc2=%d, "
8901                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
8902                     r2->crn, r2->crm, r2->opc1, r2->opc2,
8903                     oldreg->name, r2->name);
8904             g_assert_not_reached();
8905         }
8906     }
8907     g_hash_table_insert(cpu->cp_regs, key, r2);
8908 }
8909 
8910 
8911 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8912                                        const ARMCPRegInfo *r, void *opaque)
8913 {
8914     /* Define implementations of coprocessor registers.
8915      * We store these in a hashtable because typically
8916      * there are less than 150 registers in a space which
8917      * is 16*16*16*8*8 = 262144 in size.
8918      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8919      * If a register is defined twice then the second definition is
8920      * used, so this can be used to define some generic registers and
8921      * then override them with implementation specific variations.
8922      * At least one of the original and the second definition should
8923      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8924      * against accidental use.
8925      *
8926      * The state field defines whether the register is to be
8927      * visible in the AArch32 or AArch64 execution state. If the
8928      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8929      * reginfo structure for the AArch32 view, which sees the lower
8930      * 32 bits of the 64 bit register.
8931      *
8932      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8933      * be wildcarded. AArch64 registers are always considered to be 64
8934      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8935      * the register, if any.
8936      */
8937     int crm, opc1, opc2, state;
8938     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8939     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8940     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8941     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8942     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8943     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8944     /* 64 bit registers have only CRm and Opc1 fields */
8945     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8946     /* op0 only exists in the AArch64 encodings */
8947     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8948     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8949     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8950     /*
8951      * This API is only for Arm's system coprocessors (14 and 15) or
8952      * (M-profile or v7A-and-earlier only) for implementation defined
8953      * coprocessors in the range 0..7.  Our decode assumes this, since
8954      * 8..13 can be used for other insns including VFP and Neon. See
8955      * valid_cp() in translate.c.  Assert here that we haven't tried
8956      * to use an invalid coprocessor number.
8957      */
8958     switch (r->state) {
8959     case ARM_CP_STATE_BOTH:
8960         /* 0 has a special meaning, but otherwise the same rules as AA32. */
8961         if (r->cp == 0) {
8962             break;
8963         }
8964         /* fall through */
8965     case ARM_CP_STATE_AA32:
8966         if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
8967             !arm_feature(&cpu->env, ARM_FEATURE_M)) {
8968             assert(r->cp >= 14 && r->cp <= 15);
8969         } else {
8970             assert(r->cp < 8 || (r->cp >= 14 && r->cp <= 15));
8971         }
8972         break;
8973     case ARM_CP_STATE_AA64:
8974         assert(r->cp == 0 || r->cp == CP_REG_ARM64_SYSREG_CP);
8975         break;
8976     default:
8977         g_assert_not_reached();
8978     }
8979     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8980      * encodes a minimum access level for the register. We roll this
8981      * runtime check into our general permission check code, so check
8982      * here that the reginfo's specified permissions are strict enough
8983      * to encompass the generic architectural permission check.
8984      */
8985     if (r->state != ARM_CP_STATE_AA32) {
8986         int mask = 0;
8987         switch (r->opc1) {
8988         case 0:
8989             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8990             mask = PL0U_R | PL1_RW;
8991             break;
8992         case 1: case 2:
8993             /* min_EL EL1 */
8994             mask = PL1_RW;
8995             break;
8996         case 3:
8997             /* min_EL EL0 */
8998             mask = PL0_RW;
8999             break;
9000         case 4:
9001         case 5:
9002             /* min_EL EL2 */
9003             mask = PL2_RW;
9004             break;
9005         case 6:
9006             /* min_EL EL3 */
9007             mask = PL3_RW;
9008             break;
9009         case 7:
9010             /* min_EL EL1, secure mode only (we don't check the latter) */
9011             mask = PL1_RW;
9012             break;
9013         default:
9014             /* broken reginfo with out-of-range opc1 */
9015             assert(false);
9016             break;
9017         }
9018         /* assert our permissions are not too lax (stricter is fine) */
9019         assert((r->access & ~mask) == 0);
9020     }
9021 
9022     /* Check that the register definition has enough info to handle
9023      * reads and writes if they are permitted.
9024      */
9025     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
9026         if (r->access & PL3_R) {
9027             assert((r->fieldoffset ||
9028                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
9029                    r->readfn);
9030         }
9031         if (r->access & PL3_W) {
9032             assert((r->fieldoffset ||
9033                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
9034                    r->writefn);
9035         }
9036     }
9037     /* Bad type field probably means missing sentinel at end of reg list */
9038     assert(cptype_valid(r->type));
9039     for (crm = crmmin; crm <= crmmax; crm++) {
9040         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
9041             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
9042                 for (state = ARM_CP_STATE_AA32;
9043                      state <= ARM_CP_STATE_AA64; state++) {
9044                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
9045                         continue;
9046                     }
9047                     if (state == ARM_CP_STATE_AA32) {
9048                         /* Under AArch32 CP registers can be common
9049                          * (same for secure and non-secure world) or banked.
9050                          */
9051                         char *name;
9052 
9053                         switch (r->secure) {
9054                         case ARM_CP_SECSTATE_S:
9055                         case ARM_CP_SECSTATE_NS:
9056                             add_cpreg_to_hashtable(cpu, r, opaque, state,
9057                                                    r->secure, crm, opc1, opc2,
9058                                                    r->name);
9059                             break;
9060                         default:
9061                             name = g_strdup_printf("%s_S", r->name);
9062                             add_cpreg_to_hashtable(cpu, r, opaque, state,
9063                                                    ARM_CP_SECSTATE_S,
9064                                                    crm, opc1, opc2, name);
9065                             g_free(name);
9066                             add_cpreg_to_hashtable(cpu, r, opaque, state,
9067                                                    ARM_CP_SECSTATE_NS,
9068                                                    crm, opc1, opc2, r->name);
9069                             break;
9070                         }
9071                     } else {
9072                         /* AArch64 registers get mapped to non-secure instance
9073                          * of AArch32 */
9074                         add_cpreg_to_hashtable(cpu, r, opaque, state,
9075                                                ARM_CP_SECSTATE_NS,
9076                                                crm, opc1, opc2, r->name);
9077                     }
9078                 }
9079             }
9080         }
9081     }
9082 }
9083 
9084 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
9085                                     const ARMCPRegInfo *regs, void *opaque)
9086 {
9087     /* Define a whole list of registers */
9088     const ARMCPRegInfo *r;
9089     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
9090         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
9091     }
9092 }
9093 
9094 /*
9095  * Modify ARMCPRegInfo for access from userspace.
9096  *
9097  * This is a data driven modification directed by
9098  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
9099  * user-space cannot alter any values and dynamic values pertaining to
9100  * execution state are hidden from user space view anyway.
9101  */
9102 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
9103 {
9104     const ARMCPRegUserSpaceInfo *m;
9105     ARMCPRegInfo *r;
9106 
9107     for (m = mods; m->name; m++) {
9108         GPatternSpec *pat = NULL;
9109         if (m->is_glob) {
9110             pat = g_pattern_spec_new(m->name);
9111         }
9112         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
9113             if (pat && g_pattern_match_string(pat, r->name)) {
9114                 r->type = ARM_CP_CONST;
9115                 r->access = PL0U_R;
9116                 r->resetvalue = 0;
9117                 /* continue */
9118             } else if (strcmp(r->name, m->name) == 0) {
9119                 r->type = ARM_CP_CONST;
9120                 r->access = PL0U_R;
9121                 r->resetvalue &= m->exported_bits;
9122                 r->resetvalue |= m->fixed_bits;
9123                 break;
9124             }
9125         }
9126         if (pat) {
9127             g_pattern_spec_free(pat);
9128         }
9129     }
9130 }
9131 
9132 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
9133 {
9134     return g_hash_table_lookup(cpregs, &encoded_cp);
9135 }
9136 
9137 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
9138                          uint64_t value)
9139 {
9140     /* Helper coprocessor write function for write-ignore registers */
9141 }
9142 
9143 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
9144 {
9145     /* Helper coprocessor write function for read-as-zero registers */
9146     return 0;
9147 }
9148 
9149 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
9150 {
9151     /* Helper coprocessor reset function for do-nothing-on-reset registers */
9152 }
9153 
9154 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
9155 {
9156     /* Return true if it is not valid for us to switch to
9157      * this CPU mode (ie all the UNPREDICTABLE cases in
9158      * the ARM ARM CPSRWriteByInstr pseudocode).
9159      */
9160 
9161     /* Changes to or from Hyp via MSR and CPS are illegal. */
9162     if (write_type == CPSRWriteByInstr &&
9163         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
9164          mode == ARM_CPU_MODE_HYP)) {
9165         return 1;
9166     }
9167 
9168     switch (mode) {
9169     case ARM_CPU_MODE_USR:
9170         return 0;
9171     case ARM_CPU_MODE_SYS:
9172     case ARM_CPU_MODE_SVC:
9173     case ARM_CPU_MODE_ABT:
9174     case ARM_CPU_MODE_UND:
9175     case ARM_CPU_MODE_IRQ:
9176     case ARM_CPU_MODE_FIQ:
9177         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
9178          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
9179          */
9180         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
9181          * and CPS are treated as illegal mode changes.
9182          */
9183         if (write_type == CPSRWriteByInstr &&
9184             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
9185             (arm_hcr_el2_eff(env) & HCR_TGE)) {
9186             return 1;
9187         }
9188         return 0;
9189     case ARM_CPU_MODE_HYP:
9190         return !arm_is_el2_enabled(env) || arm_current_el(env) < 2;
9191     case ARM_CPU_MODE_MON:
9192         return arm_current_el(env) < 3;
9193     default:
9194         return 1;
9195     }
9196 }
9197 
9198 uint32_t cpsr_read(CPUARMState *env)
9199 {
9200     int ZF;
9201     ZF = (env->ZF == 0);
9202     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
9203         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
9204         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
9205         | ((env->condexec_bits & 0xfc) << 8)
9206         | (env->GE << 16) | (env->daif & CPSR_AIF);
9207 }
9208 
9209 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
9210                 CPSRWriteType write_type)
9211 {
9212     uint32_t changed_daif;
9213 
9214     if (mask & CPSR_NZCV) {
9215         env->ZF = (~val) & CPSR_Z;
9216         env->NF = val;
9217         env->CF = (val >> 29) & 1;
9218         env->VF = (val << 3) & 0x80000000;
9219     }
9220     if (mask & CPSR_Q)
9221         env->QF = ((val & CPSR_Q) != 0);
9222     if (mask & CPSR_T)
9223         env->thumb = ((val & CPSR_T) != 0);
9224     if (mask & CPSR_IT_0_1) {
9225         env->condexec_bits &= ~3;
9226         env->condexec_bits |= (val >> 25) & 3;
9227     }
9228     if (mask & CPSR_IT_2_7) {
9229         env->condexec_bits &= 3;
9230         env->condexec_bits |= (val >> 8) & 0xfc;
9231     }
9232     if (mask & CPSR_GE) {
9233         env->GE = (val >> 16) & 0xf;
9234     }
9235 
9236     /* In a V7 implementation that includes the security extensions but does
9237      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
9238      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
9239      * bits respectively.
9240      *
9241      * In a V8 implementation, it is permitted for privileged software to
9242      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
9243      */
9244     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
9245         arm_feature(env, ARM_FEATURE_EL3) &&
9246         !arm_feature(env, ARM_FEATURE_EL2) &&
9247         !arm_is_secure(env)) {
9248 
9249         changed_daif = (env->daif ^ val) & mask;
9250 
9251         if (changed_daif & CPSR_A) {
9252             /* Check to see if we are allowed to change the masking of async
9253              * abort exceptions from a non-secure state.
9254              */
9255             if (!(env->cp15.scr_el3 & SCR_AW)) {
9256                 qemu_log_mask(LOG_GUEST_ERROR,
9257                               "Ignoring attempt to switch CPSR_A flag from "
9258                               "non-secure world with SCR.AW bit clear\n");
9259                 mask &= ~CPSR_A;
9260             }
9261         }
9262 
9263         if (changed_daif & CPSR_F) {
9264             /* Check to see if we are allowed to change the masking of FIQ
9265              * exceptions from a non-secure state.
9266              */
9267             if (!(env->cp15.scr_el3 & SCR_FW)) {
9268                 qemu_log_mask(LOG_GUEST_ERROR,
9269                               "Ignoring attempt to switch CPSR_F flag from "
9270                               "non-secure world with SCR.FW bit clear\n");
9271                 mask &= ~CPSR_F;
9272             }
9273 
9274             /* Check whether non-maskable FIQ (NMFI) support is enabled.
9275              * If this bit is set software is not allowed to mask
9276              * FIQs, but is allowed to set CPSR_F to 0.
9277              */
9278             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
9279                 (val & CPSR_F)) {
9280                 qemu_log_mask(LOG_GUEST_ERROR,
9281                               "Ignoring attempt to enable CPSR_F flag "
9282                               "(non-maskable FIQ [NMFI] support enabled)\n");
9283                 mask &= ~CPSR_F;
9284             }
9285         }
9286     }
9287 
9288     env->daif &= ~(CPSR_AIF & mask);
9289     env->daif |= val & CPSR_AIF & mask;
9290 
9291     if (write_type != CPSRWriteRaw &&
9292         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
9293         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
9294             /* Note that we can only get here in USR mode if this is a
9295              * gdb stub write; for this case we follow the architectural
9296              * behaviour for guest writes in USR mode of ignoring an attempt
9297              * to switch mode. (Those are caught by translate.c for writes
9298              * triggered by guest instructions.)
9299              */
9300             mask &= ~CPSR_M;
9301         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
9302             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
9303              * v7, and has defined behaviour in v8:
9304              *  + leave CPSR.M untouched
9305              *  + allow changes to the other CPSR fields
9306              *  + set PSTATE.IL
9307              * For user changes via the GDB stub, we don't set PSTATE.IL,
9308              * as this would be unnecessarily harsh for a user error.
9309              */
9310             mask &= ~CPSR_M;
9311             if (write_type != CPSRWriteByGDBStub &&
9312                 arm_feature(env, ARM_FEATURE_V8)) {
9313                 mask |= CPSR_IL;
9314                 val |= CPSR_IL;
9315             }
9316             qemu_log_mask(LOG_GUEST_ERROR,
9317                           "Illegal AArch32 mode switch attempt from %s to %s\n",
9318                           aarch32_mode_name(env->uncached_cpsr),
9319                           aarch32_mode_name(val));
9320         } else {
9321             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
9322                           write_type == CPSRWriteExceptionReturn ?
9323                           "Exception return from AArch32" :
9324                           "AArch32 mode switch from",
9325                           aarch32_mode_name(env->uncached_cpsr),
9326                           aarch32_mode_name(val), env->regs[15]);
9327             switch_mode(env, val & CPSR_M);
9328         }
9329     }
9330     mask &= ~CACHED_CPSR_BITS;
9331     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
9332 }
9333 
9334 /* Sign/zero extend */
9335 uint32_t HELPER(sxtb16)(uint32_t x)
9336 {
9337     uint32_t res;
9338     res = (uint16_t)(int8_t)x;
9339     res |= (uint32_t)(int8_t)(x >> 16) << 16;
9340     return res;
9341 }
9342 
9343 uint32_t HELPER(uxtb16)(uint32_t x)
9344 {
9345     uint32_t res;
9346     res = (uint16_t)(uint8_t)x;
9347     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
9348     return res;
9349 }
9350 
9351 int32_t HELPER(sdiv)(int32_t num, int32_t den)
9352 {
9353     if (den == 0)
9354       return 0;
9355     if (num == INT_MIN && den == -1)
9356       return INT_MIN;
9357     return num / den;
9358 }
9359 
9360 uint32_t HELPER(udiv)(uint32_t num, uint32_t den)
9361 {
9362     if (den == 0)
9363       return 0;
9364     return num / den;
9365 }
9366 
9367 uint32_t HELPER(rbit)(uint32_t x)
9368 {
9369     return revbit32(x);
9370 }
9371 
9372 #ifdef CONFIG_USER_ONLY
9373 
9374 static void switch_mode(CPUARMState *env, int mode)
9375 {
9376     ARMCPU *cpu = env_archcpu(env);
9377 
9378     if (mode != ARM_CPU_MODE_USR) {
9379         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
9380     }
9381 }
9382 
9383 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9384                                  uint32_t cur_el, bool secure)
9385 {
9386     return 1;
9387 }
9388 
9389 void aarch64_sync_64_to_32(CPUARMState *env)
9390 {
9391     g_assert_not_reached();
9392 }
9393 
9394 #else
9395 
9396 static void switch_mode(CPUARMState *env, int mode)
9397 {
9398     int old_mode;
9399     int i;
9400 
9401     old_mode = env->uncached_cpsr & CPSR_M;
9402     if (mode == old_mode)
9403         return;
9404 
9405     if (old_mode == ARM_CPU_MODE_FIQ) {
9406         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
9407         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
9408     } else if (mode == ARM_CPU_MODE_FIQ) {
9409         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
9410         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
9411     }
9412 
9413     i = bank_number(old_mode);
9414     env->banked_r13[i] = env->regs[13];
9415     env->banked_spsr[i] = env->spsr;
9416 
9417     i = bank_number(mode);
9418     env->regs[13] = env->banked_r13[i];
9419     env->spsr = env->banked_spsr[i];
9420 
9421     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
9422     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
9423 }
9424 
9425 /* Physical Interrupt Target EL Lookup Table
9426  *
9427  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
9428  *
9429  * The below multi-dimensional table is used for looking up the target
9430  * exception level given numerous condition criteria.  Specifically, the
9431  * target EL is based on SCR and HCR routing controls as well as the
9432  * currently executing EL and secure state.
9433  *
9434  *    Dimensions:
9435  *    target_el_table[2][2][2][2][2][4]
9436  *                    |  |  |  |  |  +--- Current EL
9437  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
9438  *                    |  |  |  +--------- HCR mask override
9439  *                    |  |  +------------ SCR exec state control
9440  *                    |  +--------------- SCR mask override
9441  *                    +------------------ 32-bit(0)/64-bit(1) EL3
9442  *
9443  *    The table values are as such:
9444  *    0-3 = EL0-EL3
9445  *     -1 = Cannot occur
9446  *
9447  * The ARM ARM target EL table includes entries indicating that an "exception
9448  * is not taken".  The two cases where this is applicable are:
9449  *    1) An exception is taken from EL3 but the SCR does not have the exception
9450  *    routed to EL3.
9451  *    2) An exception is taken from EL2 but the HCR does not have the exception
9452  *    routed to EL2.
9453  * In these two cases, the below table contain a target of EL1.  This value is
9454  * returned as it is expected that the consumer of the table data will check
9455  * for "target EL >= current EL" to ensure the exception is not taken.
9456  *
9457  *            SCR     HCR
9458  *         64  EA     AMO                 From
9459  *        BIT IRQ     IMO      Non-secure         Secure
9460  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
9461  */
9462 static const int8_t target_el_table[2][2][2][2][2][4] = {
9463     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9464        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
9465       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9466        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
9467      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9468        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
9469       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9470        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
9471     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
9472        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 2,  2, -1,  1 },},},
9473       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1,  1,  1 },},
9474        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 2,  2,  2,  1 },},},},
9475      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
9476        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
9477       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},
9478        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},},},},
9479 };
9480 
9481 /*
9482  * Determine the target EL for physical exceptions
9483  */
9484 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9485                                  uint32_t cur_el, bool secure)
9486 {
9487     CPUARMState *env = cs->env_ptr;
9488     bool rw;
9489     bool scr;
9490     bool hcr;
9491     int target_el;
9492     /* Is the highest EL AArch64? */
9493     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
9494     uint64_t hcr_el2;
9495 
9496     if (arm_feature(env, ARM_FEATURE_EL3)) {
9497         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
9498     } else {
9499         /* Either EL2 is the highest EL (and so the EL2 register width
9500          * is given by is64); or there is no EL2 or EL3, in which case
9501          * the value of 'rw' does not affect the table lookup anyway.
9502          */
9503         rw = is64;
9504     }
9505 
9506     hcr_el2 = arm_hcr_el2_eff(env);
9507     switch (excp_idx) {
9508     case EXCP_IRQ:
9509         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
9510         hcr = hcr_el2 & HCR_IMO;
9511         break;
9512     case EXCP_FIQ:
9513         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
9514         hcr = hcr_el2 & HCR_FMO;
9515         break;
9516     default:
9517         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
9518         hcr = hcr_el2 & HCR_AMO;
9519         break;
9520     };
9521 
9522     /*
9523      * For these purposes, TGE and AMO/IMO/FMO both force the
9524      * interrupt to EL2.  Fold TGE into the bit extracted above.
9525      */
9526     hcr |= (hcr_el2 & HCR_TGE) != 0;
9527 
9528     /* Perform a table-lookup for the target EL given the current state */
9529     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
9530 
9531     assert(target_el > 0);
9532 
9533     return target_el;
9534 }
9535 
9536 void arm_log_exception(int idx)
9537 {
9538     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9539         const char *exc = NULL;
9540         static const char * const excnames[] = {
9541             [EXCP_UDEF] = "Undefined Instruction",
9542             [EXCP_SWI] = "SVC",
9543             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9544             [EXCP_DATA_ABORT] = "Data Abort",
9545             [EXCP_IRQ] = "IRQ",
9546             [EXCP_FIQ] = "FIQ",
9547             [EXCP_BKPT] = "Breakpoint",
9548             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9549             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9550             [EXCP_HVC] = "Hypervisor Call",
9551             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9552             [EXCP_SMC] = "Secure Monitor Call",
9553             [EXCP_VIRQ] = "Virtual IRQ",
9554             [EXCP_VFIQ] = "Virtual FIQ",
9555             [EXCP_SEMIHOST] = "Semihosting call",
9556             [EXCP_NOCP] = "v7M NOCP UsageFault",
9557             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9558             [EXCP_STKOF] = "v8M STKOF UsageFault",
9559             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9560             [EXCP_LSERR] = "v8M LSERR UsageFault",
9561             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9562         };
9563 
9564         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9565             exc = excnames[idx];
9566         }
9567         if (!exc) {
9568             exc = "unknown";
9569         }
9570         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
9571     }
9572 }
9573 
9574 /*
9575  * Function used to synchronize QEMU's AArch64 register set with AArch32
9576  * register set.  This is necessary when switching between AArch32 and AArch64
9577  * execution state.
9578  */
9579 void aarch64_sync_32_to_64(CPUARMState *env)
9580 {
9581     int i;
9582     uint32_t mode = env->uncached_cpsr & CPSR_M;
9583 
9584     /* We can blanket copy R[0:7] to X[0:7] */
9585     for (i = 0; i < 8; i++) {
9586         env->xregs[i] = env->regs[i];
9587     }
9588 
9589     /*
9590      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9591      * Otherwise, they come from the banked user regs.
9592      */
9593     if (mode == ARM_CPU_MODE_FIQ) {
9594         for (i = 8; i < 13; i++) {
9595             env->xregs[i] = env->usr_regs[i - 8];
9596         }
9597     } else {
9598         for (i = 8; i < 13; i++) {
9599             env->xregs[i] = env->regs[i];
9600         }
9601     }
9602 
9603     /*
9604      * Registers x13-x23 are the various mode SP and FP registers. Registers
9605      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9606      * from the mode banked register.
9607      */
9608     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9609         env->xregs[13] = env->regs[13];
9610         env->xregs[14] = env->regs[14];
9611     } else {
9612         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9613         /* HYP is an exception in that it is copied from r14 */
9614         if (mode == ARM_CPU_MODE_HYP) {
9615             env->xregs[14] = env->regs[14];
9616         } else {
9617             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9618         }
9619     }
9620 
9621     if (mode == ARM_CPU_MODE_HYP) {
9622         env->xregs[15] = env->regs[13];
9623     } else {
9624         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9625     }
9626 
9627     if (mode == ARM_CPU_MODE_IRQ) {
9628         env->xregs[16] = env->regs[14];
9629         env->xregs[17] = env->regs[13];
9630     } else {
9631         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9632         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9633     }
9634 
9635     if (mode == ARM_CPU_MODE_SVC) {
9636         env->xregs[18] = env->regs[14];
9637         env->xregs[19] = env->regs[13];
9638     } else {
9639         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9640         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9641     }
9642 
9643     if (mode == ARM_CPU_MODE_ABT) {
9644         env->xregs[20] = env->regs[14];
9645         env->xregs[21] = env->regs[13];
9646     } else {
9647         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9648         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9649     }
9650 
9651     if (mode == ARM_CPU_MODE_UND) {
9652         env->xregs[22] = env->regs[14];
9653         env->xregs[23] = env->regs[13];
9654     } else {
9655         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9656         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9657     }
9658 
9659     /*
9660      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9661      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9662      * FIQ bank for r8-r14.
9663      */
9664     if (mode == ARM_CPU_MODE_FIQ) {
9665         for (i = 24; i < 31; i++) {
9666             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9667         }
9668     } else {
9669         for (i = 24; i < 29; i++) {
9670             env->xregs[i] = env->fiq_regs[i - 24];
9671         }
9672         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9673         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9674     }
9675 
9676     env->pc = env->regs[15];
9677 }
9678 
9679 /*
9680  * Function used to synchronize QEMU's AArch32 register set with AArch64
9681  * register set.  This is necessary when switching between AArch32 and AArch64
9682  * execution state.
9683  */
9684 void aarch64_sync_64_to_32(CPUARMState *env)
9685 {
9686     int i;
9687     uint32_t mode = env->uncached_cpsr & CPSR_M;
9688 
9689     /* We can blanket copy X[0:7] to R[0:7] */
9690     for (i = 0; i < 8; i++) {
9691         env->regs[i] = env->xregs[i];
9692     }
9693 
9694     /*
9695      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9696      * Otherwise, we copy x8-x12 into the banked user regs.
9697      */
9698     if (mode == ARM_CPU_MODE_FIQ) {
9699         for (i = 8; i < 13; i++) {
9700             env->usr_regs[i - 8] = env->xregs[i];
9701         }
9702     } else {
9703         for (i = 8; i < 13; i++) {
9704             env->regs[i] = env->xregs[i];
9705         }
9706     }
9707 
9708     /*
9709      * Registers r13 & r14 depend on the current mode.
9710      * If we are in a given mode, we copy the corresponding x registers to r13
9711      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9712      * for the mode.
9713      */
9714     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9715         env->regs[13] = env->xregs[13];
9716         env->regs[14] = env->xregs[14];
9717     } else {
9718         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9719 
9720         /*
9721          * HYP is an exception in that it does not have its own banked r14 but
9722          * shares the USR r14
9723          */
9724         if (mode == ARM_CPU_MODE_HYP) {
9725             env->regs[14] = env->xregs[14];
9726         } else {
9727             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9728         }
9729     }
9730 
9731     if (mode == ARM_CPU_MODE_HYP) {
9732         env->regs[13] = env->xregs[15];
9733     } else {
9734         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9735     }
9736 
9737     if (mode == ARM_CPU_MODE_IRQ) {
9738         env->regs[14] = env->xregs[16];
9739         env->regs[13] = env->xregs[17];
9740     } else {
9741         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9742         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9743     }
9744 
9745     if (mode == ARM_CPU_MODE_SVC) {
9746         env->regs[14] = env->xregs[18];
9747         env->regs[13] = env->xregs[19];
9748     } else {
9749         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9750         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9751     }
9752 
9753     if (mode == ARM_CPU_MODE_ABT) {
9754         env->regs[14] = env->xregs[20];
9755         env->regs[13] = env->xregs[21];
9756     } else {
9757         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9758         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9759     }
9760 
9761     if (mode == ARM_CPU_MODE_UND) {
9762         env->regs[14] = env->xregs[22];
9763         env->regs[13] = env->xregs[23];
9764     } else {
9765         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9766         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9767     }
9768 
9769     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9770      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9771      * FIQ bank for r8-r14.
9772      */
9773     if (mode == ARM_CPU_MODE_FIQ) {
9774         for (i = 24; i < 31; i++) {
9775             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9776         }
9777     } else {
9778         for (i = 24; i < 29; i++) {
9779             env->fiq_regs[i - 24] = env->xregs[i];
9780         }
9781         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9782         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9783     }
9784 
9785     env->regs[15] = env->pc;
9786 }
9787 
9788 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9789                                    uint32_t mask, uint32_t offset,
9790                                    uint32_t newpc)
9791 {
9792     int new_el;
9793 
9794     /* Change the CPU state so as to actually take the exception. */
9795     switch_mode(env, new_mode);
9796 
9797     /*
9798      * For exceptions taken to AArch32 we must clear the SS bit in both
9799      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9800      */
9801     env->pstate &= ~PSTATE_SS;
9802     env->spsr = cpsr_read(env);
9803     /* Clear IT bits.  */
9804     env->condexec_bits = 0;
9805     /* Switch to the new mode, and to the correct instruction set.  */
9806     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9807 
9808     /* This must be after mode switching. */
9809     new_el = arm_current_el(env);
9810 
9811     /* Set new mode endianness */
9812     env->uncached_cpsr &= ~CPSR_E;
9813     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9814         env->uncached_cpsr |= CPSR_E;
9815     }
9816     /* J and IL must always be cleared for exception entry */
9817     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9818     env->daif |= mask;
9819 
9820     if (cpu_isar_feature(aa32_ssbs, env_archcpu(env))) {
9821         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_32) {
9822             env->uncached_cpsr |= CPSR_SSBS;
9823         } else {
9824             env->uncached_cpsr &= ~CPSR_SSBS;
9825         }
9826     }
9827 
9828     if (new_mode == ARM_CPU_MODE_HYP) {
9829         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9830         env->elr_el[2] = env->regs[15];
9831     } else {
9832         /* CPSR.PAN is normally preserved preserved unless...  */
9833         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9834             switch (new_el) {
9835             case 3:
9836                 if (!arm_is_secure_below_el3(env)) {
9837                     /* ... the target is EL3, from non-secure state.  */
9838                     env->uncached_cpsr &= ~CPSR_PAN;
9839                     break;
9840                 }
9841                 /* ... the target is EL3, from secure state ... */
9842                 /* fall through */
9843             case 1:
9844                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9845                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9846                     env->uncached_cpsr |= CPSR_PAN;
9847                 }
9848                 break;
9849             }
9850         }
9851         /*
9852          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9853          * and we should just guard the thumb mode on V4
9854          */
9855         if (arm_feature(env, ARM_FEATURE_V4T)) {
9856             env->thumb =
9857                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9858         }
9859         env->regs[14] = env->regs[15] + offset;
9860     }
9861     env->regs[15] = newpc;
9862     arm_rebuild_hflags(env);
9863 }
9864 
9865 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9866 {
9867     /*
9868      * Handle exception entry to Hyp mode; this is sufficiently
9869      * different to entry to other AArch32 modes that we handle it
9870      * separately here.
9871      *
9872      * The vector table entry used is always the 0x14 Hyp mode entry point,
9873      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
9874      * The offset applied to the preferred return address is always zero
9875      * (see DDI0487C.a section G1.12.3).
9876      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9877      */
9878     uint32_t addr, mask;
9879     ARMCPU *cpu = ARM_CPU(cs);
9880     CPUARMState *env = &cpu->env;
9881 
9882     switch (cs->exception_index) {
9883     case EXCP_UDEF:
9884         addr = 0x04;
9885         break;
9886     case EXCP_SWI:
9887         addr = 0x14;
9888         break;
9889     case EXCP_BKPT:
9890         /* Fall through to prefetch abort.  */
9891     case EXCP_PREFETCH_ABORT:
9892         env->cp15.ifar_s = env->exception.vaddress;
9893         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9894                       (uint32_t)env->exception.vaddress);
9895         addr = 0x0c;
9896         break;
9897     case EXCP_DATA_ABORT:
9898         env->cp15.dfar_s = env->exception.vaddress;
9899         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9900                       (uint32_t)env->exception.vaddress);
9901         addr = 0x10;
9902         break;
9903     case EXCP_IRQ:
9904         addr = 0x18;
9905         break;
9906     case EXCP_FIQ:
9907         addr = 0x1c;
9908         break;
9909     case EXCP_HVC:
9910         addr = 0x08;
9911         break;
9912     case EXCP_HYP_TRAP:
9913         addr = 0x14;
9914         break;
9915     default:
9916         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9917     }
9918 
9919     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9920         if (!arm_feature(env, ARM_FEATURE_V8)) {
9921             /*
9922              * QEMU syndrome values are v8-style. v7 has the IL bit
9923              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9924              * If this is a v7 CPU, squash the IL bit in those cases.
9925              */
9926             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9927                 (cs->exception_index == EXCP_DATA_ABORT &&
9928                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9929                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9930                 env->exception.syndrome &= ~ARM_EL_IL;
9931             }
9932         }
9933         env->cp15.esr_el[2] = env->exception.syndrome;
9934     }
9935 
9936     if (arm_current_el(env) != 2 && addr < 0x14) {
9937         addr = 0x14;
9938     }
9939 
9940     mask = 0;
9941     if (!(env->cp15.scr_el3 & SCR_EA)) {
9942         mask |= CPSR_A;
9943     }
9944     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9945         mask |= CPSR_I;
9946     }
9947     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9948         mask |= CPSR_F;
9949     }
9950 
9951     addr += env->cp15.hvbar;
9952 
9953     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9954 }
9955 
9956 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9957 {
9958     ARMCPU *cpu = ARM_CPU(cs);
9959     CPUARMState *env = &cpu->env;
9960     uint32_t addr;
9961     uint32_t mask;
9962     int new_mode;
9963     uint32_t offset;
9964     uint32_t moe;
9965 
9966     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9967     switch (syn_get_ec(env->exception.syndrome)) {
9968     case EC_BREAKPOINT:
9969     case EC_BREAKPOINT_SAME_EL:
9970         moe = 1;
9971         break;
9972     case EC_WATCHPOINT:
9973     case EC_WATCHPOINT_SAME_EL:
9974         moe = 10;
9975         break;
9976     case EC_AA32_BKPT:
9977         moe = 3;
9978         break;
9979     case EC_VECTORCATCH:
9980         moe = 5;
9981         break;
9982     default:
9983         moe = 0;
9984         break;
9985     }
9986 
9987     if (moe) {
9988         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
9989     }
9990 
9991     if (env->exception.target_el == 2) {
9992         arm_cpu_do_interrupt_aarch32_hyp(cs);
9993         return;
9994     }
9995 
9996     switch (cs->exception_index) {
9997     case EXCP_UDEF:
9998         new_mode = ARM_CPU_MODE_UND;
9999         addr = 0x04;
10000         mask = CPSR_I;
10001         if (env->thumb)
10002             offset = 2;
10003         else
10004             offset = 4;
10005         break;
10006     case EXCP_SWI:
10007         new_mode = ARM_CPU_MODE_SVC;
10008         addr = 0x08;
10009         mask = CPSR_I;
10010         /* The PC already points to the next instruction.  */
10011         offset = 0;
10012         break;
10013     case EXCP_BKPT:
10014         /* Fall through to prefetch abort.  */
10015     case EXCP_PREFETCH_ABORT:
10016         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
10017         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
10018         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
10019                       env->exception.fsr, (uint32_t)env->exception.vaddress);
10020         new_mode = ARM_CPU_MODE_ABT;
10021         addr = 0x0c;
10022         mask = CPSR_A | CPSR_I;
10023         offset = 4;
10024         break;
10025     case EXCP_DATA_ABORT:
10026         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
10027         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
10028         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
10029                       env->exception.fsr,
10030                       (uint32_t)env->exception.vaddress);
10031         new_mode = ARM_CPU_MODE_ABT;
10032         addr = 0x10;
10033         mask = CPSR_A | CPSR_I;
10034         offset = 8;
10035         break;
10036     case EXCP_IRQ:
10037         new_mode = ARM_CPU_MODE_IRQ;
10038         addr = 0x18;
10039         /* Disable IRQ and imprecise data aborts.  */
10040         mask = CPSR_A | CPSR_I;
10041         offset = 4;
10042         if (env->cp15.scr_el3 & SCR_IRQ) {
10043             /* IRQ routed to monitor mode */
10044             new_mode = ARM_CPU_MODE_MON;
10045             mask |= CPSR_F;
10046         }
10047         break;
10048     case EXCP_FIQ:
10049         new_mode = ARM_CPU_MODE_FIQ;
10050         addr = 0x1c;
10051         /* Disable FIQ, IRQ and imprecise data aborts.  */
10052         mask = CPSR_A | CPSR_I | CPSR_F;
10053         if (env->cp15.scr_el3 & SCR_FIQ) {
10054             /* FIQ routed to monitor mode */
10055             new_mode = ARM_CPU_MODE_MON;
10056         }
10057         offset = 4;
10058         break;
10059     case EXCP_VIRQ:
10060         new_mode = ARM_CPU_MODE_IRQ;
10061         addr = 0x18;
10062         /* Disable IRQ and imprecise data aborts.  */
10063         mask = CPSR_A | CPSR_I;
10064         offset = 4;
10065         break;
10066     case EXCP_VFIQ:
10067         new_mode = ARM_CPU_MODE_FIQ;
10068         addr = 0x1c;
10069         /* Disable FIQ, IRQ and imprecise data aborts.  */
10070         mask = CPSR_A | CPSR_I | CPSR_F;
10071         offset = 4;
10072         break;
10073     case EXCP_SMC:
10074         new_mode = ARM_CPU_MODE_MON;
10075         addr = 0x08;
10076         mask = CPSR_A | CPSR_I | CPSR_F;
10077         offset = 0;
10078         break;
10079     default:
10080         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10081         return; /* Never happens.  Keep compiler happy.  */
10082     }
10083 
10084     if (new_mode == ARM_CPU_MODE_MON) {
10085         addr += env->cp15.mvbar;
10086     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
10087         /* High vectors. When enabled, base address cannot be remapped. */
10088         addr += 0xffff0000;
10089     } else {
10090         /* ARM v7 architectures provide a vector base address register to remap
10091          * the interrupt vector table.
10092          * This register is only followed in non-monitor mode, and is banked.
10093          * Note: only bits 31:5 are valid.
10094          */
10095         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
10096     }
10097 
10098     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
10099         env->cp15.scr_el3 &= ~SCR_NS;
10100     }
10101 
10102     take_aarch32_exception(env, new_mode, mask, offset, addr);
10103 }
10104 
10105 static int aarch64_regnum(CPUARMState *env, int aarch32_reg)
10106 {
10107     /*
10108      * Return the register number of the AArch64 view of the AArch32
10109      * register @aarch32_reg. The CPUARMState CPSR is assumed to still
10110      * be that of the AArch32 mode the exception came from.
10111      */
10112     int mode = env->uncached_cpsr & CPSR_M;
10113 
10114     switch (aarch32_reg) {
10115     case 0 ... 7:
10116         return aarch32_reg;
10117     case 8 ... 12:
10118         return mode == ARM_CPU_MODE_FIQ ? aarch32_reg + 16 : aarch32_reg;
10119     case 13:
10120         switch (mode) {
10121         case ARM_CPU_MODE_USR:
10122         case ARM_CPU_MODE_SYS:
10123             return 13;
10124         case ARM_CPU_MODE_HYP:
10125             return 15;
10126         case ARM_CPU_MODE_IRQ:
10127             return 17;
10128         case ARM_CPU_MODE_SVC:
10129             return 19;
10130         case ARM_CPU_MODE_ABT:
10131             return 21;
10132         case ARM_CPU_MODE_UND:
10133             return 23;
10134         case ARM_CPU_MODE_FIQ:
10135             return 29;
10136         default:
10137             g_assert_not_reached();
10138         }
10139     case 14:
10140         switch (mode) {
10141         case ARM_CPU_MODE_USR:
10142         case ARM_CPU_MODE_SYS:
10143         case ARM_CPU_MODE_HYP:
10144             return 14;
10145         case ARM_CPU_MODE_IRQ:
10146             return 16;
10147         case ARM_CPU_MODE_SVC:
10148             return 18;
10149         case ARM_CPU_MODE_ABT:
10150             return 20;
10151         case ARM_CPU_MODE_UND:
10152             return 22;
10153         case ARM_CPU_MODE_FIQ:
10154             return 30;
10155         default:
10156             g_assert_not_reached();
10157         }
10158     case 15:
10159         return 31;
10160     default:
10161         g_assert_not_reached();
10162     }
10163 }
10164 
10165 static uint32_t cpsr_read_for_spsr_elx(CPUARMState *env)
10166 {
10167     uint32_t ret = cpsr_read(env);
10168 
10169     /* Move DIT to the correct location for SPSR_ELx */
10170     if (ret & CPSR_DIT) {
10171         ret &= ~CPSR_DIT;
10172         ret |= PSTATE_DIT;
10173     }
10174     /* Merge PSTATE.SS into SPSR_ELx */
10175     ret |= env->pstate & PSTATE_SS;
10176 
10177     return ret;
10178 }
10179 
10180 /* Handle exception entry to a target EL which is using AArch64 */
10181 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
10182 {
10183     ARMCPU *cpu = ARM_CPU(cs);
10184     CPUARMState *env = &cpu->env;
10185     unsigned int new_el = env->exception.target_el;
10186     target_ulong addr = env->cp15.vbar_el[new_el];
10187     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
10188     unsigned int old_mode;
10189     unsigned int cur_el = arm_current_el(env);
10190     int rt;
10191 
10192     /*
10193      * Note that new_el can never be 0.  If cur_el is 0, then
10194      * el0_a64 is is_a64(), else el0_a64 is ignored.
10195      */
10196     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
10197 
10198     if (cur_el < new_el) {
10199         /* Entry vector offset depends on whether the implemented EL
10200          * immediately lower than the target level is using AArch32 or AArch64
10201          */
10202         bool is_aa64;
10203         uint64_t hcr;
10204 
10205         switch (new_el) {
10206         case 3:
10207             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
10208             break;
10209         case 2:
10210             hcr = arm_hcr_el2_eff(env);
10211             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
10212                 is_aa64 = (hcr & HCR_RW) != 0;
10213                 break;
10214             }
10215             /* fall through */
10216         case 1:
10217             is_aa64 = is_a64(env);
10218             break;
10219         default:
10220             g_assert_not_reached();
10221         }
10222 
10223         if (is_aa64) {
10224             addr += 0x400;
10225         } else {
10226             addr += 0x600;
10227         }
10228     } else if (pstate_read(env) & PSTATE_SP) {
10229         addr += 0x200;
10230     }
10231 
10232     switch (cs->exception_index) {
10233     case EXCP_PREFETCH_ABORT:
10234     case EXCP_DATA_ABORT:
10235         env->cp15.far_el[new_el] = env->exception.vaddress;
10236         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
10237                       env->cp15.far_el[new_el]);
10238         /* fall through */
10239     case EXCP_BKPT:
10240     case EXCP_UDEF:
10241     case EXCP_SWI:
10242     case EXCP_HVC:
10243     case EXCP_HYP_TRAP:
10244     case EXCP_SMC:
10245         switch (syn_get_ec(env->exception.syndrome)) {
10246         case EC_ADVSIMDFPACCESSTRAP:
10247             /*
10248              * QEMU internal FP/SIMD syndromes from AArch32 include the
10249              * TA and coproc fields which are only exposed if the exception
10250              * is taken to AArch32 Hyp mode. Mask them out to get a valid
10251              * AArch64 format syndrome.
10252              */
10253             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
10254             break;
10255         case EC_CP14RTTRAP:
10256         case EC_CP15RTTRAP:
10257         case EC_CP14DTTRAP:
10258             /*
10259              * For a trap on AArch32 MRC/MCR/LDC/STC the Rt field is currently
10260              * the raw register field from the insn; when taking this to
10261              * AArch64 we must convert it to the AArch64 view of the register
10262              * number. Notice that we read a 4-bit AArch32 register number and
10263              * write back a 5-bit AArch64 one.
10264              */
10265             rt = extract32(env->exception.syndrome, 5, 4);
10266             rt = aarch64_regnum(env, rt);
10267             env->exception.syndrome = deposit32(env->exception.syndrome,
10268                                                 5, 5, rt);
10269             break;
10270         case EC_CP15RRTTRAP:
10271         case EC_CP14RRTTRAP:
10272             /* Similarly for MRRC/MCRR traps for Rt and Rt2 fields */
10273             rt = extract32(env->exception.syndrome, 5, 4);
10274             rt = aarch64_regnum(env, rt);
10275             env->exception.syndrome = deposit32(env->exception.syndrome,
10276                                                 5, 5, rt);
10277             rt = extract32(env->exception.syndrome, 10, 4);
10278             rt = aarch64_regnum(env, rt);
10279             env->exception.syndrome = deposit32(env->exception.syndrome,
10280                                                 10, 5, rt);
10281             break;
10282         }
10283         env->cp15.esr_el[new_el] = env->exception.syndrome;
10284         break;
10285     case EXCP_IRQ:
10286     case EXCP_VIRQ:
10287         addr += 0x80;
10288         break;
10289     case EXCP_FIQ:
10290     case EXCP_VFIQ:
10291         addr += 0x100;
10292         break;
10293     default:
10294         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10295     }
10296 
10297     if (is_a64(env)) {
10298         old_mode = pstate_read(env);
10299         aarch64_save_sp(env, arm_current_el(env));
10300         env->elr_el[new_el] = env->pc;
10301     } else {
10302         old_mode = cpsr_read_for_spsr_elx(env);
10303         env->elr_el[new_el] = env->regs[15];
10304 
10305         aarch64_sync_32_to_64(env);
10306 
10307         env->condexec_bits = 0;
10308     }
10309     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
10310 
10311     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
10312                   env->elr_el[new_el]);
10313 
10314     if (cpu_isar_feature(aa64_pan, cpu)) {
10315         /* The value of PSTATE.PAN is normally preserved, except when ... */
10316         new_mode |= old_mode & PSTATE_PAN;
10317         switch (new_el) {
10318         case 2:
10319             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
10320             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
10321                 != (HCR_E2H | HCR_TGE)) {
10322                 break;
10323             }
10324             /* fall through */
10325         case 1:
10326             /* ... the target is EL1 ... */
10327             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
10328             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
10329                 new_mode |= PSTATE_PAN;
10330             }
10331             break;
10332         }
10333     }
10334     if (cpu_isar_feature(aa64_mte, cpu)) {
10335         new_mode |= PSTATE_TCO;
10336     }
10337 
10338     if (cpu_isar_feature(aa64_ssbs, cpu)) {
10339         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_64) {
10340             new_mode |= PSTATE_SSBS;
10341         } else {
10342             new_mode &= ~PSTATE_SSBS;
10343         }
10344     }
10345 
10346     pstate_write(env, PSTATE_DAIF | new_mode);
10347     env->aarch64 = 1;
10348     aarch64_restore_sp(env, new_el);
10349     helper_rebuild_hflags_a64(env, new_el);
10350 
10351     env->pc = addr;
10352 
10353     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10354                   new_el, env->pc, pstate_read(env));
10355 }
10356 
10357 /*
10358  * Do semihosting call and set the appropriate return value. All the
10359  * permission and validity checks have been done at translate time.
10360  *
10361  * We only see semihosting exceptions in TCG only as they are not
10362  * trapped to the hypervisor in KVM.
10363  */
10364 #ifdef CONFIG_TCG
10365 static void handle_semihosting(CPUState *cs)
10366 {
10367     ARMCPU *cpu = ARM_CPU(cs);
10368     CPUARMState *env = &cpu->env;
10369 
10370     if (is_a64(env)) {
10371         qemu_log_mask(CPU_LOG_INT,
10372                       "...handling as semihosting call 0x%" PRIx64 "\n",
10373                       env->xregs[0]);
10374         env->xregs[0] = do_common_semihosting(cs);
10375         env->pc += 4;
10376     } else {
10377         qemu_log_mask(CPU_LOG_INT,
10378                       "...handling as semihosting call 0x%x\n",
10379                       env->regs[0]);
10380         env->regs[0] = do_common_semihosting(cs);
10381         env->regs[15] += env->thumb ? 2 : 4;
10382     }
10383 }
10384 #endif
10385 
10386 /* Handle a CPU exception for A and R profile CPUs.
10387  * Do any appropriate logging, handle PSCI calls, and then hand off
10388  * to the AArch64-entry or AArch32-entry function depending on the
10389  * target exception level's register width.
10390  *
10391  * Note: this is used for both TCG (as the do_interrupt tcg op),
10392  *       and KVM to re-inject guest debug exceptions, and to
10393  *       inject a Synchronous-External-Abort.
10394  */
10395 void arm_cpu_do_interrupt(CPUState *cs)
10396 {
10397     ARMCPU *cpu = ARM_CPU(cs);
10398     CPUARMState *env = &cpu->env;
10399     unsigned int new_el = env->exception.target_el;
10400 
10401     assert(!arm_feature(env, ARM_FEATURE_M));
10402 
10403     arm_log_exception(cs->exception_index);
10404     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10405                   new_el);
10406     if (qemu_loglevel_mask(CPU_LOG_INT)
10407         && !excp_is_internal(cs->exception_index)) {
10408         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10409                       syn_get_ec(env->exception.syndrome),
10410                       env->exception.syndrome);
10411     }
10412 
10413     if (arm_is_psci_call(cpu, cs->exception_index)) {
10414         arm_handle_psci_call(cpu);
10415         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10416         return;
10417     }
10418 
10419     /*
10420      * Semihosting semantics depend on the register width of the code
10421      * that caused the exception, not the target exception level, so
10422      * must be handled here.
10423      */
10424 #ifdef CONFIG_TCG
10425     if (cs->exception_index == EXCP_SEMIHOST) {
10426         handle_semihosting(cs);
10427         return;
10428     }
10429 #endif
10430 
10431     /* Hooks may change global state so BQL should be held, also the
10432      * BQL needs to be held for any modification of
10433      * cs->interrupt_request.
10434      */
10435     g_assert(qemu_mutex_iothread_locked());
10436 
10437     arm_call_pre_el_change_hook(cpu);
10438 
10439     assert(!excp_is_internal(cs->exception_index));
10440     if (arm_el_is_aa64(env, new_el)) {
10441         arm_cpu_do_interrupt_aarch64(cs);
10442     } else {
10443         arm_cpu_do_interrupt_aarch32(cs);
10444     }
10445 
10446     arm_call_el_change_hook(cpu);
10447 
10448     if (!kvm_enabled()) {
10449         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10450     }
10451 }
10452 #endif /* !CONFIG_USER_ONLY */
10453 
10454 uint64_t arm_sctlr(CPUARMState *env, int el)
10455 {
10456     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
10457     if (el == 0) {
10458         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
10459         el = (mmu_idx == ARMMMUIdx_E20_0 || mmu_idx == ARMMMUIdx_SE20_0)
10460              ? 2 : 1;
10461     }
10462     return env->cp15.sctlr_el[el];
10463 }
10464 
10465 /* Return the SCTLR value which controls this address translation regime */
10466 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10467 {
10468     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10469 }
10470 
10471 #ifndef CONFIG_USER_ONLY
10472 
10473 /* Return true if the specified stage of address translation is disabled */
10474 static inline bool regime_translation_disabled(CPUARMState *env,
10475                                                ARMMMUIdx mmu_idx)
10476 {
10477     uint64_t hcr_el2;
10478 
10479     if (arm_feature(env, ARM_FEATURE_M)) {
10480         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10481                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10482         case R_V7M_MPU_CTRL_ENABLE_MASK:
10483             /* Enabled, but not for HardFault and NMI */
10484             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10485         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10486             /* Enabled for all cases */
10487             return false;
10488         case 0:
10489         default:
10490             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10491              * we warned about that in armv7m_nvic.c when the guest set it.
10492              */
10493             return true;
10494         }
10495     }
10496 
10497     hcr_el2 = arm_hcr_el2_eff(env);
10498 
10499     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10500         /* HCR.DC means HCR.VM behaves as 1 */
10501         return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10502     }
10503 
10504     if (hcr_el2 & HCR_TGE) {
10505         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10506         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10507             return true;
10508         }
10509     }
10510 
10511     if ((hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
10512         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10513         return true;
10514     }
10515 
10516     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10517 }
10518 
10519 static inline bool regime_translation_big_endian(CPUARMState *env,
10520                                                  ARMMMUIdx mmu_idx)
10521 {
10522     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10523 }
10524 
10525 /* Return the TTBR associated with this translation regime */
10526 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10527                                    int ttbrn)
10528 {
10529     if (mmu_idx == ARMMMUIdx_Stage2) {
10530         return env->cp15.vttbr_el2;
10531     }
10532     if (mmu_idx == ARMMMUIdx_Stage2_S) {
10533         return env->cp15.vsttbr_el2;
10534     }
10535     if (ttbrn == 0) {
10536         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10537     } else {
10538         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10539     }
10540 }
10541 
10542 #endif /* !CONFIG_USER_ONLY */
10543 
10544 /* Convert a possible stage1+2 MMU index into the appropriate
10545  * stage 1 MMU index
10546  */
10547 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10548 {
10549     switch (mmu_idx) {
10550     case ARMMMUIdx_SE10_0:
10551         return ARMMMUIdx_Stage1_SE0;
10552     case ARMMMUIdx_SE10_1:
10553         return ARMMMUIdx_Stage1_SE1;
10554     case ARMMMUIdx_SE10_1_PAN:
10555         return ARMMMUIdx_Stage1_SE1_PAN;
10556     case ARMMMUIdx_E10_0:
10557         return ARMMMUIdx_Stage1_E0;
10558     case ARMMMUIdx_E10_1:
10559         return ARMMMUIdx_Stage1_E1;
10560     case ARMMMUIdx_E10_1_PAN:
10561         return ARMMMUIdx_Stage1_E1_PAN;
10562     default:
10563         return mmu_idx;
10564     }
10565 }
10566 
10567 /* Return true if the translation regime is using LPAE format page tables */
10568 static inline bool regime_using_lpae_format(CPUARMState *env,
10569                                             ARMMMUIdx mmu_idx)
10570 {
10571     int el = regime_el(env, mmu_idx);
10572     if (el == 2 || arm_el_is_aa64(env, el)) {
10573         return true;
10574     }
10575     if (arm_feature(env, ARM_FEATURE_LPAE)
10576         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10577         return true;
10578     }
10579     return false;
10580 }
10581 
10582 /* Returns true if the stage 1 translation regime is using LPAE format page
10583  * tables. Used when raising alignment exceptions, whose FSR changes depending
10584  * on whether the long or short descriptor format is in use. */
10585 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10586 {
10587     mmu_idx = stage_1_mmu_idx(mmu_idx);
10588 
10589     return regime_using_lpae_format(env, mmu_idx);
10590 }
10591 
10592 #ifndef CONFIG_USER_ONLY
10593 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10594 {
10595     switch (mmu_idx) {
10596     case ARMMMUIdx_SE10_0:
10597     case ARMMMUIdx_E20_0:
10598     case ARMMMUIdx_SE20_0:
10599     case ARMMMUIdx_Stage1_E0:
10600     case ARMMMUIdx_Stage1_SE0:
10601     case ARMMMUIdx_MUser:
10602     case ARMMMUIdx_MSUser:
10603     case ARMMMUIdx_MUserNegPri:
10604     case ARMMMUIdx_MSUserNegPri:
10605         return true;
10606     default:
10607         return false;
10608     case ARMMMUIdx_E10_0:
10609     case ARMMMUIdx_E10_1:
10610     case ARMMMUIdx_E10_1_PAN:
10611         g_assert_not_reached();
10612     }
10613 }
10614 
10615 /* Translate section/page access permissions to page
10616  * R/W protection flags
10617  *
10618  * @env:         CPUARMState
10619  * @mmu_idx:     MMU index indicating required translation regime
10620  * @ap:          The 3-bit access permissions (AP[2:0])
10621  * @domain_prot: The 2-bit domain access permissions
10622  */
10623 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10624                                 int ap, int domain_prot)
10625 {
10626     bool is_user = regime_is_user(env, mmu_idx);
10627 
10628     if (domain_prot == 3) {
10629         return PAGE_READ | PAGE_WRITE;
10630     }
10631 
10632     switch (ap) {
10633     case 0:
10634         if (arm_feature(env, ARM_FEATURE_V7)) {
10635             return 0;
10636         }
10637         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10638         case SCTLR_S:
10639             return is_user ? 0 : PAGE_READ;
10640         case SCTLR_R:
10641             return PAGE_READ;
10642         default:
10643             return 0;
10644         }
10645     case 1:
10646         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10647     case 2:
10648         if (is_user) {
10649             return PAGE_READ;
10650         } else {
10651             return PAGE_READ | PAGE_WRITE;
10652         }
10653     case 3:
10654         return PAGE_READ | PAGE_WRITE;
10655     case 4: /* Reserved.  */
10656         return 0;
10657     case 5:
10658         return is_user ? 0 : PAGE_READ;
10659     case 6:
10660         return PAGE_READ;
10661     case 7:
10662         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10663             return 0;
10664         }
10665         return PAGE_READ;
10666     default:
10667         g_assert_not_reached();
10668     }
10669 }
10670 
10671 /* Translate section/page access permissions to page
10672  * R/W protection flags.
10673  *
10674  * @ap:      The 2-bit simple AP (AP[2:1])
10675  * @is_user: TRUE if accessing from PL0
10676  */
10677 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10678 {
10679     switch (ap) {
10680     case 0:
10681         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10682     case 1:
10683         return PAGE_READ | PAGE_WRITE;
10684     case 2:
10685         return is_user ? 0 : PAGE_READ;
10686     case 3:
10687         return PAGE_READ;
10688     default:
10689         g_assert_not_reached();
10690     }
10691 }
10692 
10693 static inline int
10694 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10695 {
10696     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10697 }
10698 
10699 /* Translate S2 section/page access permissions to protection flags
10700  *
10701  * @env:     CPUARMState
10702  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10703  * @xn:      XN (execute-never) bits
10704  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
10705  */
10706 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
10707 {
10708     int prot = 0;
10709 
10710     if (s2ap & 1) {
10711         prot |= PAGE_READ;
10712     }
10713     if (s2ap & 2) {
10714         prot |= PAGE_WRITE;
10715     }
10716 
10717     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
10718         switch (xn) {
10719         case 0:
10720             prot |= PAGE_EXEC;
10721             break;
10722         case 1:
10723             if (s1_is_el0) {
10724                 prot |= PAGE_EXEC;
10725             }
10726             break;
10727         case 2:
10728             break;
10729         case 3:
10730             if (!s1_is_el0) {
10731                 prot |= PAGE_EXEC;
10732             }
10733             break;
10734         default:
10735             g_assert_not_reached();
10736         }
10737     } else {
10738         if (!extract32(xn, 1, 1)) {
10739             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10740                 prot |= PAGE_EXEC;
10741             }
10742         }
10743     }
10744     return prot;
10745 }
10746 
10747 /* Translate section/page access permissions to protection flags
10748  *
10749  * @env:     CPUARMState
10750  * @mmu_idx: MMU index indicating required translation regime
10751  * @is_aa64: TRUE if AArch64
10752  * @ap:      The 2-bit simple AP (AP[2:1])
10753  * @ns:      NS (non-secure) bit
10754  * @xn:      XN (execute-never) bit
10755  * @pxn:     PXN (privileged execute-never) bit
10756  */
10757 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10758                       int ap, int ns, int xn, int pxn)
10759 {
10760     bool is_user = regime_is_user(env, mmu_idx);
10761     int prot_rw, user_rw;
10762     bool have_wxn;
10763     int wxn = 0;
10764 
10765     assert(mmu_idx != ARMMMUIdx_Stage2);
10766     assert(mmu_idx != ARMMMUIdx_Stage2_S);
10767 
10768     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10769     if (is_user) {
10770         prot_rw = user_rw;
10771     } else {
10772         if (user_rw && regime_is_pan(env, mmu_idx)) {
10773             /* PAN forbids data accesses but doesn't affect insn fetch */
10774             prot_rw = 0;
10775         } else {
10776             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10777         }
10778     }
10779 
10780     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10781         return prot_rw;
10782     }
10783 
10784     /* TODO have_wxn should be replaced with
10785      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10786      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10787      * compatible processors have EL2, which is required for [U]WXN.
10788      */
10789     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10790 
10791     if (have_wxn) {
10792         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10793     }
10794 
10795     if (is_aa64) {
10796         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10797             xn = pxn || (user_rw & PAGE_WRITE);
10798         }
10799     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10800         switch (regime_el(env, mmu_idx)) {
10801         case 1:
10802         case 3:
10803             if (is_user) {
10804                 xn = xn || !(user_rw & PAGE_READ);
10805             } else {
10806                 int uwxn = 0;
10807                 if (have_wxn) {
10808                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10809                 }
10810                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10811                      (uwxn && (user_rw & PAGE_WRITE));
10812             }
10813             break;
10814         case 2:
10815             break;
10816         }
10817     } else {
10818         xn = wxn = 0;
10819     }
10820 
10821     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10822         return prot_rw;
10823     }
10824     return prot_rw | PAGE_EXEC;
10825 }
10826 
10827 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10828                                      uint32_t *table, uint32_t address)
10829 {
10830     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10831     TCR *tcr = regime_tcr(env, mmu_idx);
10832 
10833     if (address & tcr->mask) {
10834         if (tcr->raw_tcr & TTBCR_PD1) {
10835             /* Translation table walk disabled for TTBR1 */
10836             return false;
10837         }
10838         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10839     } else {
10840         if (tcr->raw_tcr & TTBCR_PD0) {
10841             /* Translation table walk disabled for TTBR0 */
10842             return false;
10843         }
10844         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10845     }
10846     *table |= (address >> 18) & 0x3ffc;
10847     return true;
10848 }
10849 
10850 /* Translate a S1 pagetable walk through S2 if needed.  */
10851 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10852                                hwaddr addr, bool *is_secure,
10853                                ARMMMUFaultInfo *fi)
10854 {
10855     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10856         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10857         target_ulong s2size;
10858         hwaddr s2pa;
10859         int s2prot;
10860         int ret;
10861         ARMMMUIdx s2_mmu_idx = *is_secure ? ARMMMUIdx_Stage2_S
10862                                           : ARMMMUIdx_Stage2;
10863         ARMCacheAttrs cacheattrs = {};
10864         MemTxAttrs txattrs = {};
10865 
10866         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, s2_mmu_idx, false,
10867                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10868                                  &cacheattrs);
10869         if (ret) {
10870             assert(fi->type != ARMFault_None);
10871             fi->s2addr = addr;
10872             fi->stage2 = true;
10873             fi->s1ptw = true;
10874             fi->s1ns = !*is_secure;
10875             return ~0;
10876         }
10877         if ((arm_hcr_el2_eff(env) & HCR_PTW) &&
10878             (cacheattrs.attrs & 0xf0) == 0) {
10879             /*
10880              * PTW set and S1 walk touched S2 Device memory:
10881              * generate Permission fault.
10882              */
10883             fi->type = ARMFault_Permission;
10884             fi->s2addr = addr;
10885             fi->stage2 = true;
10886             fi->s1ptw = true;
10887             fi->s1ns = !*is_secure;
10888             return ~0;
10889         }
10890 
10891         if (arm_is_secure_below_el3(env)) {
10892             /* Check if page table walk is to secure or non-secure PA space. */
10893             if (*is_secure) {
10894                 *is_secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
10895             } else {
10896                 *is_secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
10897             }
10898         } else {
10899             assert(!*is_secure);
10900         }
10901 
10902         addr = s2pa;
10903     }
10904     return addr;
10905 }
10906 
10907 /* All loads done in the course of a page table walk go through here. */
10908 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10909                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10910 {
10911     ARMCPU *cpu = ARM_CPU(cs);
10912     CPUARMState *env = &cpu->env;
10913     MemTxAttrs attrs = {};
10914     MemTxResult result = MEMTX_OK;
10915     AddressSpace *as;
10916     uint32_t data;
10917 
10918     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10919     attrs.secure = is_secure;
10920     as = arm_addressspace(cs, attrs);
10921     if (fi->s1ptw) {
10922         return 0;
10923     }
10924     if (regime_translation_big_endian(env, mmu_idx)) {
10925         data = address_space_ldl_be(as, addr, attrs, &result);
10926     } else {
10927         data = address_space_ldl_le(as, addr, attrs, &result);
10928     }
10929     if (result == MEMTX_OK) {
10930         return data;
10931     }
10932     fi->type = ARMFault_SyncExternalOnWalk;
10933     fi->ea = arm_extabort_type(result);
10934     return 0;
10935 }
10936 
10937 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10938                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10939 {
10940     ARMCPU *cpu = ARM_CPU(cs);
10941     CPUARMState *env = &cpu->env;
10942     MemTxAttrs attrs = {};
10943     MemTxResult result = MEMTX_OK;
10944     AddressSpace *as;
10945     uint64_t data;
10946 
10947     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10948     attrs.secure = is_secure;
10949     as = arm_addressspace(cs, attrs);
10950     if (fi->s1ptw) {
10951         return 0;
10952     }
10953     if (regime_translation_big_endian(env, mmu_idx)) {
10954         data = address_space_ldq_be(as, addr, attrs, &result);
10955     } else {
10956         data = address_space_ldq_le(as, addr, attrs, &result);
10957     }
10958     if (result == MEMTX_OK) {
10959         return data;
10960     }
10961     fi->type = ARMFault_SyncExternalOnWalk;
10962     fi->ea = arm_extabort_type(result);
10963     return 0;
10964 }
10965 
10966 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10967                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10968                              hwaddr *phys_ptr, int *prot,
10969                              target_ulong *page_size,
10970                              ARMMMUFaultInfo *fi)
10971 {
10972     CPUState *cs = env_cpu(env);
10973     int level = 1;
10974     uint32_t table;
10975     uint32_t desc;
10976     int type;
10977     int ap;
10978     int domain = 0;
10979     int domain_prot;
10980     hwaddr phys_addr;
10981     uint32_t dacr;
10982 
10983     /* Pagetable walk.  */
10984     /* Lookup l1 descriptor.  */
10985     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
10986         /* Section translation fault if page walk is disabled by PD0 or PD1 */
10987         fi->type = ARMFault_Translation;
10988         goto do_fault;
10989     }
10990     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
10991                        mmu_idx, fi);
10992     if (fi->type != ARMFault_None) {
10993         goto do_fault;
10994     }
10995     type = (desc & 3);
10996     domain = (desc >> 5) & 0x0f;
10997     if (regime_el(env, mmu_idx) == 1) {
10998         dacr = env->cp15.dacr_ns;
10999     } else {
11000         dacr = env->cp15.dacr_s;
11001     }
11002     domain_prot = (dacr >> (domain * 2)) & 3;
11003     if (type == 0) {
11004         /* Section translation fault.  */
11005         fi->type = ARMFault_Translation;
11006         goto do_fault;
11007     }
11008     if (type != 2) {
11009         level = 2;
11010     }
11011     if (domain_prot == 0 || domain_prot == 2) {
11012         fi->type = ARMFault_Domain;
11013         goto do_fault;
11014     }
11015     if (type == 2) {
11016         /* 1Mb section.  */
11017         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
11018         ap = (desc >> 10) & 3;
11019         *page_size = 1024 * 1024;
11020     } else {
11021         /* Lookup l2 entry.  */
11022         if (type == 1) {
11023             /* Coarse pagetable.  */
11024             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
11025         } else {
11026             /* Fine pagetable.  */
11027             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
11028         }
11029         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11030                            mmu_idx, fi);
11031         if (fi->type != ARMFault_None) {
11032             goto do_fault;
11033         }
11034         switch (desc & 3) {
11035         case 0: /* Page translation fault.  */
11036             fi->type = ARMFault_Translation;
11037             goto do_fault;
11038         case 1: /* 64k page.  */
11039             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11040             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
11041             *page_size = 0x10000;
11042             break;
11043         case 2: /* 4k page.  */
11044             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11045             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
11046             *page_size = 0x1000;
11047             break;
11048         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
11049             if (type == 1) {
11050                 /* ARMv6/XScale extended small page format */
11051                 if (arm_feature(env, ARM_FEATURE_XSCALE)
11052                     || arm_feature(env, ARM_FEATURE_V6)) {
11053                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11054                     *page_size = 0x1000;
11055                 } else {
11056                     /* UNPREDICTABLE in ARMv5; we choose to take a
11057                      * page translation fault.
11058                      */
11059                     fi->type = ARMFault_Translation;
11060                     goto do_fault;
11061                 }
11062             } else {
11063                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
11064                 *page_size = 0x400;
11065             }
11066             ap = (desc >> 4) & 3;
11067             break;
11068         default:
11069             /* Never happens, but compiler isn't smart enough to tell.  */
11070             abort();
11071         }
11072     }
11073     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11074     *prot |= *prot ? PAGE_EXEC : 0;
11075     if (!(*prot & (1 << access_type))) {
11076         /* Access permission fault.  */
11077         fi->type = ARMFault_Permission;
11078         goto do_fault;
11079     }
11080     *phys_ptr = phys_addr;
11081     return false;
11082 do_fault:
11083     fi->domain = domain;
11084     fi->level = level;
11085     return true;
11086 }
11087 
11088 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
11089                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
11090                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
11091                              target_ulong *page_size, ARMMMUFaultInfo *fi)
11092 {
11093     CPUState *cs = env_cpu(env);
11094     ARMCPU *cpu = env_archcpu(env);
11095     int level = 1;
11096     uint32_t table;
11097     uint32_t desc;
11098     uint32_t xn;
11099     uint32_t pxn = 0;
11100     int type;
11101     int ap;
11102     int domain = 0;
11103     int domain_prot;
11104     hwaddr phys_addr;
11105     uint32_t dacr;
11106     bool ns;
11107 
11108     /* Pagetable walk.  */
11109     /* Lookup l1 descriptor.  */
11110     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
11111         /* Section translation fault if page walk is disabled by PD0 or PD1 */
11112         fi->type = ARMFault_Translation;
11113         goto do_fault;
11114     }
11115     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11116                        mmu_idx, fi);
11117     if (fi->type != ARMFault_None) {
11118         goto do_fault;
11119     }
11120     type = (desc & 3);
11121     if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
11122         /* Section translation fault, or attempt to use the encoding
11123          * which is Reserved on implementations without PXN.
11124          */
11125         fi->type = ARMFault_Translation;
11126         goto do_fault;
11127     }
11128     if ((type == 1) || !(desc & (1 << 18))) {
11129         /* Page or Section.  */
11130         domain = (desc >> 5) & 0x0f;
11131     }
11132     if (regime_el(env, mmu_idx) == 1) {
11133         dacr = env->cp15.dacr_ns;
11134     } else {
11135         dacr = env->cp15.dacr_s;
11136     }
11137     if (type == 1) {
11138         level = 2;
11139     }
11140     domain_prot = (dacr >> (domain * 2)) & 3;
11141     if (domain_prot == 0 || domain_prot == 2) {
11142         /* Section or Page domain fault */
11143         fi->type = ARMFault_Domain;
11144         goto do_fault;
11145     }
11146     if (type != 1) {
11147         if (desc & (1 << 18)) {
11148             /* Supersection.  */
11149             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
11150             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
11151             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
11152             *page_size = 0x1000000;
11153         } else {
11154             /* Section.  */
11155             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
11156             *page_size = 0x100000;
11157         }
11158         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
11159         xn = desc & (1 << 4);
11160         pxn = desc & 1;
11161         ns = extract32(desc, 19, 1);
11162     } else {
11163         if (cpu_isar_feature(aa32_pxn, cpu)) {
11164             pxn = (desc >> 2) & 1;
11165         }
11166         ns = extract32(desc, 3, 1);
11167         /* Lookup l2 entry.  */
11168         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
11169         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11170                            mmu_idx, fi);
11171         if (fi->type != ARMFault_None) {
11172             goto do_fault;
11173         }
11174         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
11175         switch (desc & 3) {
11176         case 0: /* Page translation fault.  */
11177             fi->type = ARMFault_Translation;
11178             goto do_fault;
11179         case 1: /* 64k page.  */
11180             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11181             xn = desc & (1 << 15);
11182             *page_size = 0x10000;
11183             break;
11184         case 2: case 3: /* 4k page.  */
11185             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11186             xn = desc & 1;
11187             *page_size = 0x1000;
11188             break;
11189         default:
11190             /* Never happens, but compiler isn't smart enough to tell.  */
11191             abort();
11192         }
11193     }
11194     if (domain_prot == 3) {
11195         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11196     } else {
11197         if (pxn && !regime_is_user(env, mmu_idx)) {
11198             xn = 1;
11199         }
11200         if (xn && access_type == MMU_INST_FETCH) {
11201             fi->type = ARMFault_Permission;
11202             goto do_fault;
11203         }
11204 
11205         if (arm_feature(env, ARM_FEATURE_V6K) &&
11206                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
11207             /* The simplified model uses AP[0] as an access control bit.  */
11208             if ((ap & 1) == 0) {
11209                 /* Access flag fault.  */
11210                 fi->type = ARMFault_AccessFlag;
11211                 goto do_fault;
11212             }
11213             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
11214         } else {
11215             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11216         }
11217         if (*prot && !xn) {
11218             *prot |= PAGE_EXEC;
11219         }
11220         if (!(*prot & (1 << access_type))) {
11221             /* Access permission fault.  */
11222             fi->type = ARMFault_Permission;
11223             goto do_fault;
11224         }
11225     }
11226     if (ns) {
11227         /* The NS bit will (as required by the architecture) have no effect if
11228          * the CPU doesn't support TZ or this is a non-secure translation
11229          * regime, because the attribute will already be non-secure.
11230          */
11231         attrs->secure = false;
11232     }
11233     *phys_ptr = phys_addr;
11234     return false;
11235 do_fault:
11236     fi->domain = domain;
11237     fi->level = level;
11238     return true;
11239 }
11240 
11241 /*
11242  * check_s2_mmu_setup
11243  * @cpu:        ARMCPU
11244  * @is_aa64:    True if the translation regime is in AArch64 state
11245  * @startlevel: Suggested starting level
11246  * @inputsize:  Bitsize of IPAs
11247  * @stride:     Page-table stride (See the ARM ARM)
11248  *
11249  * Returns true if the suggested S2 translation parameters are OK and
11250  * false otherwise.
11251  */
11252 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
11253                                int inputsize, int stride)
11254 {
11255     const int grainsize = stride + 3;
11256     int startsizecheck;
11257 
11258     /* Negative levels are never allowed.  */
11259     if (level < 0) {
11260         return false;
11261     }
11262 
11263     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
11264     if (startsizecheck < 1 || startsizecheck > stride + 4) {
11265         return false;
11266     }
11267 
11268     if (is_aa64) {
11269         CPUARMState *env = &cpu->env;
11270         unsigned int pamax = arm_pamax(cpu);
11271 
11272         switch (stride) {
11273         case 13: /* 64KB Pages.  */
11274             if (level == 0 || (level == 1 && pamax <= 42)) {
11275                 return false;
11276             }
11277             break;
11278         case 11: /* 16KB Pages.  */
11279             if (level == 0 || (level == 1 && pamax <= 40)) {
11280                 return false;
11281             }
11282             break;
11283         case 9: /* 4KB Pages.  */
11284             if (level == 0 && pamax <= 42) {
11285                 return false;
11286             }
11287             break;
11288         default:
11289             g_assert_not_reached();
11290         }
11291 
11292         /* Inputsize checks.  */
11293         if (inputsize > pamax &&
11294             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
11295             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
11296             return false;
11297         }
11298     } else {
11299         /* AArch32 only supports 4KB pages. Assert on that.  */
11300         assert(stride == 9);
11301 
11302         if (level == 0) {
11303             return false;
11304         }
11305     }
11306     return true;
11307 }
11308 
11309 /* Translate from the 4-bit stage 2 representation of
11310  * memory attributes (without cache-allocation hints) to
11311  * the 8-bit representation of the stage 1 MAIR registers
11312  * (which includes allocation hints).
11313  *
11314  * ref: shared/translation/attrs/S2AttrDecode()
11315  *      .../S2ConvertAttrsHints()
11316  */
11317 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
11318 {
11319     uint8_t hiattr = extract32(s2attrs, 2, 2);
11320     uint8_t loattr = extract32(s2attrs, 0, 2);
11321     uint8_t hihint = 0, lohint = 0;
11322 
11323     if (hiattr != 0) { /* normal memory */
11324         if (arm_hcr_el2_eff(env) & HCR_CD) { /* cache disabled */
11325             hiattr = loattr = 1; /* non-cacheable */
11326         } else {
11327             if (hiattr != 1) { /* Write-through or write-back */
11328                 hihint = 3; /* RW allocate */
11329             }
11330             if (loattr != 1) { /* Write-through or write-back */
11331                 lohint = 3; /* RW allocate */
11332             }
11333         }
11334     }
11335 
11336     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11337 }
11338 #endif /* !CONFIG_USER_ONLY */
11339 
11340 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
11341 {
11342     if (regime_has_2_ranges(mmu_idx)) {
11343         return extract64(tcr, 37, 2);
11344     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11345         return 0; /* VTCR_EL2 */
11346     } else {
11347         /* Replicate the single TBI bit so we always have 2 bits.  */
11348         return extract32(tcr, 20, 1) * 3;
11349     }
11350 }
11351 
11352 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
11353 {
11354     if (regime_has_2_ranges(mmu_idx)) {
11355         return extract64(tcr, 51, 2);
11356     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11357         return 0; /* VTCR_EL2 */
11358     } else {
11359         /* Replicate the single TBID bit so we always have 2 bits.  */
11360         return extract32(tcr, 29, 1) * 3;
11361     }
11362 }
11363 
11364 static int aa64_va_parameter_tcma(uint64_t tcr, ARMMMUIdx mmu_idx)
11365 {
11366     if (regime_has_2_ranges(mmu_idx)) {
11367         return extract64(tcr, 57, 2);
11368     } else {
11369         /* Replicate the single TCMA bit so we always have 2 bits.  */
11370         return extract32(tcr, 30, 1) * 3;
11371     }
11372 }
11373 
11374 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11375                                    ARMMMUIdx mmu_idx, bool data)
11376 {
11377     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11378     bool epd, hpd, using16k, using64k;
11379     int select, tsz, tbi, max_tsz;
11380 
11381     if (!regime_has_2_ranges(mmu_idx)) {
11382         select = 0;
11383         tsz = extract32(tcr, 0, 6);
11384         using64k = extract32(tcr, 14, 1);
11385         using16k = extract32(tcr, 15, 1);
11386         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11387             /* VTCR_EL2 */
11388             hpd = false;
11389         } else {
11390             hpd = extract32(tcr, 24, 1);
11391         }
11392         epd = false;
11393     } else {
11394         /*
11395          * Bit 55 is always between the two regions, and is canonical for
11396          * determining if address tagging is enabled.
11397          */
11398         select = extract64(va, 55, 1);
11399         if (!select) {
11400             tsz = extract32(tcr, 0, 6);
11401             epd = extract32(tcr, 7, 1);
11402             using64k = extract32(tcr, 14, 1);
11403             using16k = extract32(tcr, 15, 1);
11404             hpd = extract64(tcr, 41, 1);
11405         } else {
11406             int tg = extract32(tcr, 30, 2);
11407             using16k = tg == 1;
11408             using64k = tg == 3;
11409             tsz = extract32(tcr, 16, 6);
11410             epd = extract32(tcr, 23, 1);
11411             hpd = extract64(tcr, 42, 1);
11412         }
11413     }
11414 
11415     if (cpu_isar_feature(aa64_st, env_archcpu(env))) {
11416         max_tsz = 48 - using64k;
11417     } else {
11418         max_tsz = 39;
11419     }
11420 
11421     tsz = MIN(tsz, max_tsz);
11422     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
11423 
11424     /* Present TBI as a composite with TBID.  */
11425     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11426     if (!data) {
11427         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11428     }
11429     tbi = (tbi >> select) & 1;
11430 
11431     return (ARMVAParameters) {
11432         .tsz = tsz,
11433         .select = select,
11434         .tbi = tbi,
11435         .epd = epd,
11436         .hpd = hpd,
11437         .using16k = using16k,
11438         .using64k = using64k,
11439     };
11440 }
11441 
11442 #ifndef CONFIG_USER_ONLY
11443 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11444                                           ARMMMUIdx mmu_idx)
11445 {
11446     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11447     uint32_t el = regime_el(env, mmu_idx);
11448     int select, tsz;
11449     bool epd, hpd;
11450 
11451     assert(mmu_idx != ARMMMUIdx_Stage2_S);
11452 
11453     if (mmu_idx == ARMMMUIdx_Stage2) {
11454         /* VTCR */
11455         bool sext = extract32(tcr, 4, 1);
11456         bool sign = extract32(tcr, 3, 1);
11457 
11458         /*
11459          * If the sign-extend bit is not the same as t0sz[3], the result
11460          * is unpredictable. Flag this as a guest error.
11461          */
11462         if (sign != sext) {
11463             qemu_log_mask(LOG_GUEST_ERROR,
11464                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11465         }
11466         tsz = sextract32(tcr, 0, 4) + 8;
11467         select = 0;
11468         hpd = false;
11469         epd = false;
11470     } else if (el == 2) {
11471         /* HTCR */
11472         tsz = extract32(tcr, 0, 3);
11473         select = 0;
11474         hpd = extract64(tcr, 24, 1);
11475         epd = false;
11476     } else {
11477         int t0sz = extract32(tcr, 0, 3);
11478         int t1sz = extract32(tcr, 16, 3);
11479 
11480         if (t1sz == 0) {
11481             select = va > (0xffffffffu >> t0sz);
11482         } else {
11483             /* Note that we will detect errors later.  */
11484             select = va >= ~(0xffffffffu >> t1sz);
11485         }
11486         if (!select) {
11487             tsz = t0sz;
11488             epd = extract32(tcr, 7, 1);
11489             hpd = extract64(tcr, 41, 1);
11490         } else {
11491             tsz = t1sz;
11492             epd = extract32(tcr, 23, 1);
11493             hpd = extract64(tcr, 42, 1);
11494         }
11495         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11496         hpd &= extract32(tcr, 6, 1);
11497     }
11498 
11499     return (ARMVAParameters) {
11500         .tsz = tsz,
11501         .select = select,
11502         .epd = epd,
11503         .hpd = hpd,
11504     };
11505 }
11506 
11507 /**
11508  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
11509  *
11510  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11511  * prot and page_size may not be filled in, and the populated fsr value provides
11512  * information on why the translation aborted, in the format of a long-format
11513  * DFSR/IFSR fault register, with the following caveats:
11514  *  * the WnR bit is never set (the caller must do this).
11515  *
11516  * @env: CPUARMState
11517  * @address: virtual address to get physical address for
11518  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
11519  * @mmu_idx: MMU index indicating required translation regime
11520  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
11521  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
11522  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
11523  * @phys_ptr: set to the physical address corresponding to the virtual address
11524  * @attrs: set to the memory transaction attributes to use
11525  * @prot: set to the permissions for the page containing phys_ptr
11526  * @page_size_ptr: set to the size of the page containing phys_ptr
11527  * @fi: set to fault info if the translation fails
11528  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11529  */
11530 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
11531                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11532                                bool s1_is_el0,
11533                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11534                                target_ulong *page_size_ptr,
11535                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11536 {
11537     ARMCPU *cpu = env_archcpu(env);
11538     CPUState *cs = CPU(cpu);
11539     /* Read an LPAE long-descriptor translation table. */
11540     ARMFaultType fault_type = ARMFault_Translation;
11541     uint32_t level;
11542     ARMVAParameters param;
11543     uint64_t ttbr;
11544     hwaddr descaddr, indexmask, indexmask_grainsize;
11545     uint32_t tableattrs;
11546     target_ulong page_size;
11547     uint32_t attrs;
11548     int32_t stride;
11549     int addrsize, inputsize;
11550     TCR *tcr = regime_tcr(env, mmu_idx);
11551     int ap, ns, xn, pxn;
11552     uint32_t el = regime_el(env, mmu_idx);
11553     uint64_t descaddrmask;
11554     bool aarch64 = arm_el_is_aa64(env, el);
11555     bool guarded = false;
11556 
11557     /* TODO: This code does not support shareability levels. */
11558     if (aarch64) {
11559         param = aa64_va_parameters(env, address, mmu_idx,
11560                                    access_type != MMU_INST_FETCH);
11561         level = 0;
11562         addrsize = 64 - 8 * param.tbi;
11563         inputsize = 64 - param.tsz;
11564     } else {
11565         param = aa32_va_parameters(env, address, mmu_idx);
11566         level = 1;
11567         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
11568         inputsize = addrsize - param.tsz;
11569     }
11570 
11571     /*
11572      * We determined the region when collecting the parameters, but we
11573      * have not yet validated that the address is valid for the region.
11574      * Extract the top bits and verify that they all match select.
11575      *
11576      * For aa32, if inputsize == addrsize, then we have selected the
11577      * region by exclusion in aa32_va_parameters and there is no more
11578      * validation to do here.
11579      */
11580     if (inputsize < addrsize) {
11581         target_ulong top_bits = sextract64(address, inputsize,
11582                                            addrsize - inputsize);
11583         if (-top_bits != param.select) {
11584             /* The gap between the two regions is a Translation fault */
11585             fault_type = ARMFault_Translation;
11586             goto do_fault;
11587         }
11588     }
11589 
11590     if (param.using64k) {
11591         stride = 13;
11592     } else if (param.using16k) {
11593         stride = 11;
11594     } else {
11595         stride = 9;
11596     }
11597 
11598     /* Note that QEMU ignores shareability and cacheability attributes,
11599      * so we don't need to do anything with the SH, ORGN, IRGN fields
11600      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11601      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11602      * implement any ASID-like capability so we can ignore it (instead
11603      * we will always flush the TLB any time the ASID is changed).
11604      */
11605     ttbr = regime_ttbr(env, mmu_idx, param.select);
11606 
11607     /* Here we should have set up all the parameters for the translation:
11608      * inputsize, ttbr, epd, stride, tbi
11609      */
11610 
11611     if (param.epd) {
11612         /* Translation table walk disabled => Translation fault on TLB miss
11613          * Note: This is always 0 on 64-bit EL2 and EL3.
11614          */
11615         goto do_fault;
11616     }
11617 
11618     if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
11619         /* The starting level depends on the virtual address size (which can
11620          * be up to 48 bits) and the translation granule size. It indicates
11621          * the number of strides (stride bits at a time) needed to
11622          * consume the bits of the input address. In the pseudocode this is:
11623          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11624          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11625          * our 'stride + 3' and 'stride' is our 'stride'.
11626          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11627          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11628          * = 4 - (inputsize - 4) / stride;
11629          */
11630         level = 4 - (inputsize - 4) / stride;
11631     } else {
11632         /* For stage 2 translations the starting level is specified by the
11633          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11634          */
11635         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11636         uint32_t startlevel;
11637         bool ok;
11638 
11639         if (!aarch64 || stride == 9) {
11640             /* AArch32 or 4KB pages */
11641             startlevel = 2 - sl0;
11642 
11643             if (cpu_isar_feature(aa64_st, cpu)) {
11644                 startlevel &= 3;
11645             }
11646         } else {
11647             /* 16KB or 64KB pages */
11648             startlevel = 3 - sl0;
11649         }
11650 
11651         /* Check that the starting level is valid. */
11652         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11653                                 inputsize, stride);
11654         if (!ok) {
11655             fault_type = ARMFault_Translation;
11656             goto do_fault;
11657         }
11658         level = startlevel;
11659     }
11660 
11661     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
11662     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
11663 
11664     /* Now we can extract the actual base address from the TTBR */
11665     descaddr = extract64(ttbr, 0, 48);
11666     /*
11667      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
11668      * and also to mask out CnP (bit 0) which could validly be non-zero.
11669      */
11670     descaddr &= ~indexmask;
11671 
11672     /* The address field in the descriptor goes up to bit 39 for ARMv7
11673      * but up to bit 47 for ARMv8, but we use the descaddrmask
11674      * up to bit 39 for AArch32, because we don't need other bits in that case
11675      * to construct next descriptor address (anyway they should be all zeroes).
11676      */
11677     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
11678                    ~indexmask_grainsize;
11679 
11680     /* Secure accesses start with the page table in secure memory and
11681      * can be downgraded to non-secure at any step. Non-secure accesses
11682      * remain non-secure. We implement this by just ORing in the NSTable/NS
11683      * bits at each step.
11684      */
11685     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11686     for (;;) {
11687         uint64_t descriptor;
11688         bool nstable;
11689 
11690         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11691         descaddr &= ~7ULL;
11692         nstable = extract32(tableattrs, 4, 1);
11693         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11694         if (fi->type != ARMFault_None) {
11695             goto do_fault;
11696         }
11697 
11698         if (!(descriptor & 1) ||
11699             (!(descriptor & 2) && (level == 3))) {
11700             /* Invalid, or the Reserved level 3 encoding */
11701             goto do_fault;
11702         }
11703         descaddr = descriptor & descaddrmask;
11704 
11705         if ((descriptor & 2) && (level < 3)) {
11706             /* Table entry. The top five bits are attributes which may
11707              * propagate down through lower levels of the table (and
11708              * which are all arranged so that 0 means "no effect", so
11709              * we can gather them up by ORing in the bits at each level).
11710              */
11711             tableattrs |= extract64(descriptor, 59, 5);
11712             level++;
11713             indexmask = indexmask_grainsize;
11714             continue;
11715         }
11716         /* Block entry at level 1 or 2, or page entry at level 3.
11717          * These are basically the same thing, although the number
11718          * of bits we pull in from the vaddr varies.
11719          */
11720         page_size = (1ULL << ((stride * (4 - level)) + 3));
11721         descaddr |= (address & (page_size - 1));
11722         /* Extract attributes from the descriptor */
11723         attrs = extract64(descriptor, 2, 10)
11724             | (extract64(descriptor, 52, 12) << 10);
11725 
11726         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11727             /* Stage 2 table descriptors do not include any attribute fields */
11728             break;
11729         }
11730         /* Merge in attributes from table descriptors */
11731         attrs |= nstable << 3; /* NS */
11732         guarded = extract64(descriptor, 50, 1);  /* GP */
11733         if (param.hpd) {
11734             /* HPD disables all the table attributes except NSTable.  */
11735             break;
11736         }
11737         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11738         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11739          * means "force PL1 access only", which means forcing AP[1] to 0.
11740          */
11741         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11742         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11743         break;
11744     }
11745     /* Here descaddr is the final physical address, and attributes
11746      * are all in attrs.
11747      */
11748     fault_type = ARMFault_AccessFlag;
11749     if ((attrs & (1 << 8)) == 0) {
11750         /* Access flag */
11751         goto do_fault;
11752     }
11753 
11754     ap = extract32(attrs, 4, 2);
11755 
11756     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11757         ns = mmu_idx == ARMMMUIdx_Stage2;
11758         xn = extract32(attrs, 11, 2);
11759         *prot = get_S2prot(env, ap, xn, s1_is_el0);
11760     } else {
11761         ns = extract32(attrs, 3, 1);
11762         xn = extract32(attrs, 12, 1);
11763         pxn = extract32(attrs, 11, 1);
11764         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11765     }
11766 
11767     fault_type = ARMFault_Permission;
11768     if (!(*prot & (1 << access_type))) {
11769         goto do_fault;
11770     }
11771 
11772     if (ns) {
11773         /* The NS bit will (as required by the architecture) have no effect if
11774          * the CPU doesn't support TZ or this is a non-secure translation
11775          * regime, because the attribute will already be non-secure.
11776          */
11777         txattrs->secure = false;
11778     }
11779     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11780     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11781         arm_tlb_bti_gp(txattrs) = true;
11782     }
11783 
11784     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11785         cacheattrs->attrs = convert_stage2_attrs(env, extract32(attrs, 0, 4));
11786     } else {
11787         /* Index into MAIR registers for cache attributes */
11788         uint8_t attrindx = extract32(attrs, 0, 3);
11789         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11790         assert(attrindx <= 7);
11791         cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11792     }
11793     cacheattrs->shareability = extract32(attrs, 6, 2);
11794 
11795     *phys_ptr = descaddr;
11796     *page_size_ptr = page_size;
11797     return false;
11798 
11799 do_fault:
11800     fi->type = fault_type;
11801     fi->level = level;
11802     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11803     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2 ||
11804                                mmu_idx == ARMMMUIdx_Stage2_S);
11805     fi->s1ns = mmu_idx == ARMMMUIdx_Stage2;
11806     return true;
11807 }
11808 
11809 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11810                                                 ARMMMUIdx mmu_idx,
11811                                                 int32_t address, int *prot)
11812 {
11813     if (!arm_feature(env, ARM_FEATURE_M)) {
11814         *prot = PAGE_READ | PAGE_WRITE;
11815         switch (address) {
11816         case 0xF0000000 ... 0xFFFFFFFF:
11817             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11818                 /* hivecs execing is ok */
11819                 *prot |= PAGE_EXEC;
11820             }
11821             break;
11822         case 0x00000000 ... 0x7FFFFFFF:
11823             *prot |= PAGE_EXEC;
11824             break;
11825         }
11826     } else {
11827         /* Default system address map for M profile cores.
11828          * The architecture specifies which regions are execute-never;
11829          * at the MPU level no other checks are defined.
11830          */
11831         switch (address) {
11832         case 0x00000000 ... 0x1fffffff: /* ROM */
11833         case 0x20000000 ... 0x3fffffff: /* SRAM */
11834         case 0x60000000 ... 0x7fffffff: /* RAM */
11835         case 0x80000000 ... 0x9fffffff: /* RAM */
11836             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11837             break;
11838         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11839         case 0xa0000000 ... 0xbfffffff: /* Device */
11840         case 0xc0000000 ... 0xdfffffff: /* Device */
11841         case 0xe0000000 ... 0xffffffff: /* System */
11842             *prot = PAGE_READ | PAGE_WRITE;
11843             break;
11844         default:
11845             g_assert_not_reached();
11846         }
11847     }
11848 }
11849 
11850 static bool pmsav7_use_background_region(ARMCPU *cpu,
11851                                          ARMMMUIdx mmu_idx, bool is_user)
11852 {
11853     /* Return true if we should use the default memory map as a
11854      * "background" region if there are no hits against any MPU regions.
11855      */
11856     CPUARMState *env = &cpu->env;
11857 
11858     if (is_user) {
11859         return false;
11860     }
11861 
11862     if (arm_feature(env, ARM_FEATURE_M)) {
11863         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11864             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11865     } else {
11866         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11867     }
11868 }
11869 
11870 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11871 {
11872     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11873     return arm_feature(env, ARM_FEATURE_M) &&
11874         extract32(address, 20, 12) == 0xe00;
11875 }
11876 
11877 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11878 {
11879     /* True if address is in the M profile system region
11880      * 0xe0000000 - 0xffffffff
11881      */
11882     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11883 }
11884 
11885 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11886                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11887                                  hwaddr *phys_ptr, int *prot,
11888                                  target_ulong *page_size,
11889                                  ARMMMUFaultInfo *fi)
11890 {
11891     ARMCPU *cpu = env_archcpu(env);
11892     int n;
11893     bool is_user = regime_is_user(env, mmu_idx);
11894 
11895     *phys_ptr = address;
11896     *page_size = TARGET_PAGE_SIZE;
11897     *prot = 0;
11898 
11899     if (regime_translation_disabled(env, mmu_idx) ||
11900         m_is_ppb_region(env, address)) {
11901         /* MPU disabled or M profile PPB access: use default memory map.
11902          * The other case which uses the default memory map in the
11903          * v7M ARM ARM pseudocode is exception vector reads from the vector
11904          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11905          * which always does a direct read using address_space_ldl(), rather
11906          * than going via this function, so we don't need to check that here.
11907          */
11908         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11909     } else { /* MPU enabled */
11910         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11911             /* region search */
11912             uint32_t base = env->pmsav7.drbar[n];
11913             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11914             uint32_t rmask;
11915             bool srdis = false;
11916 
11917             if (!(env->pmsav7.drsr[n] & 0x1)) {
11918                 continue;
11919             }
11920 
11921             if (!rsize) {
11922                 qemu_log_mask(LOG_GUEST_ERROR,
11923                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11924                 continue;
11925             }
11926             rsize++;
11927             rmask = (1ull << rsize) - 1;
11928 
11929             if (base & rmask) {
11930                 qemu_log_mask(LOG_GUEST_ERROR,
11931                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11932                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11933                               n, base, rmask);
11934                 continue;
11935             }
11936 
11937             if (address < base || address > base + rmask) {
11938                 /*
11939                  * Address not in this region. We must check whether the
11940                  * region covers addresses in the same page as our address.
11941                  * In that case we must not report a size that covers the
11942                  * whole page for a subsequent hit against a different MPU
11943                  * region or the background region, because it would result in
11944                  * incorrect TLB hits for subsequent accesses to addresses that
11945                  * are in this MPU region.
11946                  */
11947                 if (ranges_overlap(base, rmask,
11948                                    address & TARGET_PAGE_MASK,
11949                                    TARGET_PAGE_SIZE)) {
11950                     *page_size = 1;
11951                 }
11952                 continue;
11953             }
11954 
11955             /* Region matched */
11956 
11957             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11958                 int i, snd;
11959                 uint32_t srdis_mask;
11960 
11961                 rsize -= 3; /* sub region size (power of 2) */
11962                 snd = ((address - base) >> rsize) & 0x7;
11963                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11964 
11965                 srdis_mask = srdis ? 0x3 : 0x0;
11966                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11967                     /* This will check in groups of 2, 4 and then 8, whether
11968                      * the subregion bits are consistent. rsize is incremented
11969                      * back up to give the region size, considering consistent
11970                      * adjacent subregions as one region. Stop testing if rsize
11971                      * is already big enough for an entire QEMU page.
11972                      */
11973                     int snd_rounded = snd & ~(i - 1);
11974                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11975                                                      snd_rounded + 8, i);
11976                     if (srdis_mask ^ srdis_multi) {
11977                         break;
11978                     }
11979                     srdis_mask = (srdis_mask << i) | srdis_mask;
11980                     rsize++;
11981                 }
11982             }
11983             if (srdis) {
11984                 continue;
11985             }
11986             if (rsize < TARGET_PAGE_BITS) {
11987                 *page_size = 1 << rsize;
11988             }
11989             break;
11990         }
11991 
11992         if (n == -1) { /* no hits */
11993             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
11994                 /* background fault */
11995                 fi->type = ARMFault_Background;
11996                 return true;
11997             }
11998             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11999         } else { /* a MPU hit! */
12000             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
12001             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
12002 
12003             if (m_is_system_region(env, address)) {
12004                 /* System space is always execute never */
12005                 xn = 1;
12006             }
12007 
12008             if (is_user) { /* User mode AP bit decoding */
12009                 switch (ap) {
12010                 case 0:
12011                 case 1:
12012                 case 5:
12013                     break; /* no access */
12014                 case 3:
12015                     *prot |= PAGE_WRITE;
12016                     /* fall through */
12017                 case 2:
12018                 case 6:
12019                     *prot |= PAGE_READ | PAGE_EXEC;
12020                     break;
12021                 case 7:
12022                     /* for v7M, same as 6; for R profile a reserved value */
12023                     if (arm_feature(env, ARM_FEATURE_M)) {
12024                         *prot |= PAGE_READ | PAGE_EXEC;
12025                         break;
12026                     }
12027                     /* fall through */
12028                 default:
12029                     qemu_log_mask(LOG_GUEST_ERROR,
12030                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12031                                   PRIx32 "\n", n, ap);
12032                 }
12033             } else { /* Priv. mode AP bits decoding */
12034                 switch (ap) {
12035                 case 0:
12036                     break; /* no access */
12037                 case 1:
12038                 case 2:
12039                 case 3:
12040                     *prot |= PAGE_WRITE;
12041                     /* fall through */
12042                 case 5:
12043                 case 6:
12044                     *prot |= PAGE_READ | PAGE_EXEC;
12045                     break;
12046                 case 7:
12047                     /* for v7M, same as 6; for R profile a reserved value */
12048                     if (arm_feature(env, ARM_FEATURE_M)) {
12049                         *prot |= PAGE_READ | PAGE_EXEC;
12050                         break;
12051                     }
12052                     /* fall through */
12053                 default:
12054                     qemu_log_mask(LOG_GUEST_ERROR,
12055                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12056                                   PRIx32 "\n", n, ap);
12057                 }
12058             }
12059 
12060             /* execute never */
12061             if (xn) {
12062                 *prot &= ~PAGE_EXEC;
12063             }
12064         }
12065     }
12066 
12067     fi->type = ARMFault_Permission;
12068     fi->level = 1;
12069     return !(*prot & (1 << access_type));
12070 }
12071 
12072 static bool v8m_is_sau_exempt(CPUARMState *env,
12073                               uint32_t address, MMUAccessType access_type)
12074 {
12075     /* The architecture specifies that certain address ranges are
12076      * exempt from v8M SAU/IDAU checks.
12077      */
12078     return
12079         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
12080         (address >= 0xe0000000 && address <= 0xe0002fff) ||
12081         (address >= 0xe000e000 && address <= 0xe000efff) ||
12082         (address >= 0xe002e000 && address <= 0xe002efff) ||
12083         (address >= 0xe0040000 && address <= 0xe0041fff) ||
12084         (address >= 0xe00ff000 && address <= 0xe00fffff);
12085 }
12086 
12087 void v8m_security_lookup(CPUARMState *env, uint32_t address,
12088                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
12089                                 V8M_SAttributes *sattrs)
12090 {
12091     /* Look up the security attributes for this address. Compare the
12092      * pseudocode SecurityCheck() function.
12093      * We assume the caller has zero-initialized *sattrs.
12094      */
12095     ARMCPU *cpu = env_archcpu(env);
12096     int r;
12097     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
12098     int idau_region = IREGION_NOTVALID;
12099     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12100     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12101 
12102     if (cpu->idau) {
12103         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
12104         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
12105 
12106         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
12107                    &idau_nsc);
12108     }
12109 
12110     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
12111         /* 0xf0000000..0xffffffff is always S for insn fetches */
12112         return;
12113     }
12114 
12115     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
12116         sattrs->ns = !regime_is_secure(env, mmu_idx);
12117         return;
12118     }
12119 
12120     if (idau_region != IREGION_NOTVALID) {
12121         sattrs->irvalid = true;
12122         sattrs->iregion = idau_region;
12123     }
12124 
12125     switch (env->sau.ctrl & 3) {
12126     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
12127         break;
12128     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
12129         sattrs->ns = true;
12130         break;
12131     default: /* SAU.ENABLE == 1 */
12132         for (r = 0; r < cpu->sau_sregion; r++) {
12133             if (env->sau.rlar[r] & 1) {
12134                 uint32_t base = env->sau.rbar[r] & ~0x1f;
12135                 uint32_t limit = env->sau.rlar[r] | 0x1f;
12136 
12137                 if (base <= address && limit >= address) {
12138                     if (base > addr_page_base || limit < addr_page_limit) {
12139                         sattrs->subpage = true;
12140                     }
12141                     if (sattrs->srvalid) {
12142                         /* If we hit in more than one region then we must report
12143                          * as Secure, not NS-Callable, with no valid region
12144                          * number info.
12145                          */
12146                         sattrs->ns = false;
12147                         sattrs->nsc = false;
12148                         sattrs->sregion = 0;
12149                         sattrs->srvalid = false;
12150                         break;
12151                     } else {
12152                         if (env->sau.rlar[r] & 2) {
12153                             sattrs->nsc = true;
12154                         } else {
12155                             sattrs->ns = true;
12156                         }
12157                         sattrs->srvalid = true;
12158                         sattrs->sregion = r;
12159                     }
12160                 } else {
12161                     /*
12162                      * Address not in this region. We must check whether the
12163                      * region covers addresses in the same page as our address.
12164                      * In that case we must not report a size that covers the
12165                      * whole page for a subsequent hit against a different MPU
12166                      * region or the background region, because it would result
12167                      * in incorrect TLB hits for subsequent accesses to
12168                      * addresses that are in this MPU region.
12169                      */
12170                     if (limit >= base &&
12171                         ranges_overlap(base, limit - base + 1,
12172                                        addr_page_base,
12173                                        TARGET_PAGE_SIZE)) {
12174                         sattrs->subpage = true;
12175                     }
12176                 }
12177             }
12178         }
12179         break;
12180     }
12181 
12182     /*
12183      * The IDAU will override the SAU lookup results if it specifies
12184      * higher security than the SAU does.
12185      */
12186     if (!idau_ns) {
12187         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
12188             sattrs->ns = false;
12189             sattrs->nsc = idau_nsc;
12190         }
12191     }
12192 }
12193 
12194 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
12195                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
12196                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
12197                               int *prot, bool *is_subpage,
12198                               ARMMMUFaultInfo *fi, uint32_t *mregion)
12199 {
12200     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
12201      * that a full phys-to-virt translation does).
12202      * mregion is (if not NULL) set to the region number which matched,
12203      * or -1 if no region number is returned (MPU off, address did not
12204      * hit a region, address hit in multiple regions).
12205      * We set is_subpage to true if the region hit doesn't cover the
12206      * entire TARGET_PAGE the address is within.
12207      */
12208     ARMCPU *cpu = env_archcpu(env);
12209     bool is_user = regime_is_user(env, mmu_idx);
12210     uint32_t secure = regime_is_secure(env, mmu_idx);
12211     int n;
12212     int matchregion = -1;
12213     bool hit = false;
12214     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12215     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12216 
12217     *is_subpage = false;
12218     *phys_ptr = address;
12219     *prot = 0;
12220     if (mregion) {
12221         *mregion = -1;
12222     }
12223 
12224     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
12225      * was an exception vector read from the vector table (which is always
12226      * done using the default system address map), because those accesses
12227      * are done in arm_v7m_load_vector(), which always does a direct
12228      * read using address_space_ldl(), rather than going via this function.
12229      */
12230     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
12231         hit = true;
12232     } else if (m_is_ppb_region(env, address)) {
12233         hit = true;
12234     } else {
12235         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12236             hit = true;
12237         }
12238 
12239         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12240             /* region search */
12241             /* Note that the base address is bits [31:5] from the register
12242              * with bits [4:0] all zeroes, but the limit address is bits
12243              * [31:5] from the register with bits [4:0] all ones.
12244              */
12245             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
12246             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
12247 
12248             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
12249                 /* Region disabled */
12250                 continue;
12251             }
12252 
12253             if (address < base || address > limit) {
12254                 /*
12255                  * Address not in this region. We must check whether the
12256                  * region covers addresses in the same page as our address.
12257                  * In that case we must not report a size that covers the
12258                  * whole page for a subsequent hit against a different MPU
12259                  * region or the background region, because it would result in
12260                  * incorrect TLB hits for subsequent accesses to addresses that
12261                  * are in this MPU region.
12262                  */
12263                 if (limit >= base &&
12264                     ranges_overlap(base, limit - base + 1,
12265                                    addr_page_base,
12266                                    TARGET_PAGE_SIZE)) {
12267                     *is_subpage = true;
12268                 }
12269                 continue;
12270             }
12271 
12272             if (base > addr_page_base || limit < addr_page_limit) {
12273                 *is_subpage = true;
12274             }
12275 
12276             if (matchregion != -1) {
12277                 /* Multiple regions match -- always a failure (unlike
12278                  * PMSAv7 where highest-numbered-region wins)
12279                  */
12280                 fi->type = ARMFault_Permission;
12281                 fi->level = 1;
12282                 return true;
12283             }
12284 
12285             matchregion = n;
12286             hit = true;
12287         }
12288     }
12289 
12290     if (!hit) {
12291         /* background fault */
12292         fi->type = ARMFault_Background;
12293         return true;
12294     }
12295 
12296     if (matchregion == -1) {
12297         /* hit using the background region */
12298         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12299     } else {
12300         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
12301         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
12302         bool pxn = false;
12303 
12304         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
12305             pxn = extract32(env->pmsav8.rlar[secure][matchregion], 4, 1);
12306         }
12307 
12308         if (m_is_system_region(env, address)) {
12309             /* System space is always execute never */
12310             xn = 1;
12311         }
12312 
12313         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
12314         if (*prot && !xn && !(pxn && !is_user)) {
12315             *prot |= PAGE_EXEC;
12316         }
12317         /* We don't need to look the attribute up in the MAIR0/MAIR1
12318          * registers because that only tells us about cacheability.
12319          */
12320         if (mregion) {
12321             *mregion = matchregion;
12322         }
12323     }
12324 
12325     fi->type = ARMFault_Permission;
12326     fi->level = 1;
12327     return !(*prot & (1 << access_type));
12328 }
12329 
12330 
12331 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12332                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12333                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12334                                  int *prot, target_ulong *page_size,
12335                                  ARMMMUFaultInfo *fi)
12336 {
12337     uint32_t secure = regime_is_secure(env, mmu_idx);
12338     V8M_SAttributes sattrs = {};
12339     bool ret;
12340     bool mpu_is_subpage;
12341 
12342     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12343         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12344         if (access_type == MMU_INST_FETCH) {
12345             /* Instruction fetches always use the MMU bank and the
12346              * transaction attribute determined by the fetch address,
12347              * regardless of CPU state. This is painful for QEMU
12348              * to handle, because it would mean we need to encode
12349              * into the mmu_idx not just the (user, negpri) information
12350              * for the current security state but also that for the
12351              * other security state, which would balloon the number
12352              * of mmu_idx values needed alarmingly.
12353              * Fortunately we can avoid this because it's not actually
12354              * possible to arbitrarily execute code from memory with
12355              * the wrong security attribute: it will always generate
12356              * an exception of some kind or another, apart from the
12357              * special case of an NS CPU executing an SG instruction
12358              * in S&NSC memory. So we always just fail the translation
12359              * here and sort things out in the exception handler
12360              * (including possibly emulating an SG instruction).
12361              */
12362             if (sattrs.ns != !secure) {
12363                 if (sattrs.nsc) {
12364                     fi->type = ARMFault_QEMU_NSCExec;
12365                 } else {
12366                     fi->type = ARMFault_QEMU_SFault;
12367                 }
12368                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12369                 *phys_ptr = address;
12370                 *prot = 0;
12371                 return true;
12372             }
12373         } else {
12374             /* For data accesses we always use the MMU bank indicated
12375              * by the current CPU state, but the security attributes
12376              * might downgrade a secure access to nonsecure.
12377              */
12378             if (sattrs.ns) {
12379                 txattrs->secure = false;
12380             } else if (!secure) {
12381                 /* NS access to S memory must fault.
12382                  * Architecturally we should first check whether the
12383                  * MPU information for this address indicates that we
12384                  * are doing an unaligned access to Device memory, which
12385                  * should generate a UsageFault instead. QEMU does not
12386                  * currently check for that kind of unaligned access though.
12387                  * If we added it we would need to do so as a special case
12388                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12389                  */
12390                 fi->type = ARMFault_QEMU_SFault;
12391                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12392                 *phys_ptr = address;
12393                 *prot = 0;
12394                 return true;
12395             }
12396         }
12397     }
12398 
12399     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12400                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12401     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12402     return ret;
12403 }
12404 
12405 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12406                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12407                                  hwaddr *phys_ptr, int *prot,
12408                                  ARMMMUFaultInfo *fi)
12409 {
12410     int n;
12411     uint32_t mask;
12412     uint32_t base;
12413     bool is_user = regime_is_user(env, mmu_idx);
12414 
12415     if (regime_translation_disabled(env, mmu_idx)) {
12416         /* MPU disabled.  */
12417         *phys_ptr = address;
12418         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12419         return false;
12420     }
12421 
12422     *phys_ptr = address;
12423     for (n = 7; n >= 0; n--) {
12424         base = env->cp15.c6_region[n];
12425         if ((base & 1) == 0) {
12426             continue;
12427         }
12428         mask = 1 << ((base >> 1) & 0x1f);
12429         /* Keep this shift separate from the above to avoid an
12430            (undefined) << 32.  */
12431         mask = (mask << 1) - 1;
12432         if (((base ^ address) & ~mask) == 0) {
12433             break;
12434         }
12435     }
12436     if (n < 0) {
12437         fi->type = ARMFault_Background;
12438         return true;
12439     }
12440 
12441     if (access_type == MMU_INST_FETCH) {
12442         mask = env->cp15.pmsav5_insn_ap;
12443     } else {
12444         mask = env->cp15.pmsav5_data_ap;
12445     }
12446     mask = (mask >> (n * 4)) & 0xf;
12447     switch (mask) {
12448     case 0:
12449         fi->type = ARMFault_Permission;
12450         fi->level = 1;
12451         return true;
12452     case 1:
12453         if (is_user) {
12454             fi->type = ARMFault_Permission;
12455             fi->level = 1;
12456             return true;
12457         }
12458         *prot = PAGE_READ | PAGE_WRITE;
12459         break;
12460     case 2:
12461         *prot = PAGE_READ;
12462         if (!is_user) {
12463             *prot |= PAGE_WRITE;
12464         }
12465         break;
12466     case 3:
12467         *prot = PAGE_READ | PAGE_WRITE;
12468         break;
12469     case 5:
12470         if (is_user) {
12471             fi->type = ARMFault_Permission;
12472             fi->level = 1;
12473             return true;
12474         }
12475         *prot = PAGE_READ;
12476         break;
12477     case 6:
12478         *prot = PAGE_READ;
12479         break;
12480     default:
12481         /* Bad permission.  */
12482         fi->type = ARMFault_Permission;
12483         fi->level = 1;
12484         return true;
12485     }
12486     *prot |= PAGE_EXEC;
12487     return false;
12488 }
12489 
12490 /* Combine either inner or outer cacheability attributes for normal
12491  * memory, according to table D4-42 and pseudocode procedure
12492  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12493  *
12494  * NB: only stage 1 includes allocation hints (RW bits), leading to
12495  * some asymmetry.
12496  */
12497 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12498 {
12499     if (s1 == 4 || s2 == 4) {
12500         /* non-cacheable has precedence */
12501         return 4;
12502     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12503         /* stage 1 write-through takes precedence */
12504         return s1;
12505     } else if (extract32(s2, 2, 2) == 2) {
12506         /* stage 2 write-through takes precedence, but the allocation hint
12507          * is still taken from stage 1
12508          */
12509         return (2 << 2) | extract32(s1, 0, 2);
12510     } else { /* write-back */
12511         return s1;
12512     }
12513 }
12514 
12515 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12516  * and CombineS1S2Desc()
12517  *
12518  * @s1:      Attributes from stage 1 walk
12519  * @s2:      Attributes from stage 2 walk
12520  */
12521 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
12522 {
12523     uint8_t s1lo, s2lo, s1hi, s2hi;
12524     ARMCacheAttrs ret;
12525     bool tagged = false;
12526 
12527     if (s1.attrs == 0xf0) {
12528         tagged = true;
12529         s1.attrs = 0xff;
12530     }
12531 
12532     s1lo = extract32(s1.attrs, 0, 4);
12533     s2lo = extract32(s2.attrs, 0, 4);
12534     s1hi = extract32(s1.attrs, 4, 4);
12535     s2hi = extract32(s2.attrs, 4, 4);
12536 
12537     /* Combine shareability attributes (table D4-43) */
12538     if (s1.shareability == 2 || s2.shareability == 2) {
12539         /* if either are outer-shareable, the result is outer-shareable */
12540         ret.shareability = 2;
12541     } else if (s1.shareability == 3 || s2.shareability == 3) {
12542         /* if either are inner-shareable, the result is inner-shareable */
12543         ret.shareability = 3;
12544     } else {
12545         /* both non-shareable */
12546         ret.shareability = 0;
12547     }
12548 
12549     /* Combine memory type and cacheability attributes */
12550     if (s1hi == 0 || s2hi == 0) {
12551         /* Device has precedence over normal */
12552         if (s1lo == 0 || s2lo == 0) {
12553             /* nGnRnE has precedence over anything */
12554             ret.attrs = 0;
12555         } else if (s1lo == 4 || s2lo == 4) {
12556             /* non-Reordering has precedence over Reordering */
12557             ret.attrs = 4;  /* nGnRE */
12558         } else if (s1lo == 8 || s2lo == 8) {
12559             /* non-Gathering has precedence over Gathering */
12560             ret.attrs = 8;  /* nGRE */
12561         } else {
12562             ret.attrs = 0xc; /* GRE */
12563         }
12564 
12565         /* Any location for which the resultant memory type is any
12566          * type of Device memory is always treated as Outer Shareable.
12567          */
12568         ret.shareability = 2;
12569     } else { /* Normal memory */
12570         /* Outer/inner cacheability combine independently */
12571         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12572                   | combine_cacheattr_nibble(s1lo, s2lo);
12573 
12574         if (ret.attrs == 0x44) {
12575             /* Any location for which the resultant memory type is Normal
12576              * Inner Non-cacheable, Outer Non-cacheable is always treated
12577              * as Outer Shareable.
12578              */
12579             ret.shareability = 2;
12580         }
12581     }
12582 
12583     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
12584     if (tagged && ret.attrs == 0xff) {
12585         ret.attrs = 0xf0;
12586     }
12587 
12588     return ret;
12589 }
12590 
12591 
12592 /* get_phys_addr - get the physical address for this virtual address
12593  *
12594  * Find the physical address corresponding to the given virtual address,
12595  * by doing a translation table walk on MMU based systems or using the
12596  * MPU state on MPU based systems.
12597  *
12598  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12599  * prot and page_size may not be filled in, and the populated fsr value provides
12600  * information on why the translation aborted, in the format of a
12601  * DFSR/IFSR fault register, with the following caveats:
12602  *  * we honour the short vs long DFSR format differences.
12603  *  * the WnR bit is never set (the caller must do this).
12604  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12605  *    value.
12606  *
12607  * @env: CPUARMState
12608  * @address: virtual address to get physical address for
12609  * @access_type: 0 for read, 1 for write, 2 for execute
12610  * @mmu_idx: MMU index indicating required translation regime
12611  * @phys_ptr: set to the physical address corresponding to the virtual address
12612  * @attrs: set to the memory transaction attributes to use
12613  * @prot: set to the permissions for the page containing phys_ptr
12614  * @page_size: set to the size of the page containing phys_ptr
12615  * @fi: set to fault info if the translation fails
12616  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12617  */
12618 bool get_phys_addr(CPUARMState *env, target_ulong address,
12619                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12620                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12621                    target_ulong *page_size,
12622                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12623 {
12624     ARMMMUIdx s1_mmu_idx = stage_1_mmu_idx(mmu_idx);
12625 
12626     if (mmu_idx != s1_mmu_idx) {
12627         /* Call ourselves recursively to do the stage 1 and then stage 2
12628          * translations if mmu_idx is a two-stage regime.
12629          */
12630         if (arm_feature(env, ARM_FEATURE_EL2)) {
12631             hwaddr ipa;
12632             int s2_prot;
12633             int ret;
12634             ARMCacheAttrs cacheattrs2 = {};
12635             ARMMMUIdx s2_mmu_idx;
12636             bool is_el0;
12637 
12638             ret = get_phys_addr(env, address, access_type, s1_mmu_idx, &ipa,
12639                                 attrs, prot, page_size, fi, cacheattrs);
12640 
12641             /* If S1 fails or S2 is disabled, return early.  */
12642             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
12643                 *phys_ptr = ipa;
12644                 return ret;
12645             }
12646 
12647             s2_mmu_idx = attrs->secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
12648             is_el0 = mmu_idx == ARMMMUIdx_E10_0 || mmu_idx == ARMMMUIdx_SE10_0;
12649 
12650             /* S1 is done. Now do S2 translation.  */
12651             ret = get_phys_addr_lpae(env, ipa, access_type, s2_mmu_idx, is_el0,
12652                                      phys_ptr, attrs, &s2_prot,
12653                                      page_size, fi, &cacheattrs2);
12654             fi->s2addr = ipa;
12655             /* Combine the S1 and S2 perms.  */
12656             *prot &= s2_prot;
12657 
12658             /* If S2 fails, return early.  */
12659             if (ret) {
12660                 return ret;
12661             }
12662 
12663             /* Combine the S1 and S2 cache attributes. */
12664             if (arm_hcr_el2_eff(env) & HCR_DC) {
12665                 /*
12666                  * HCR.DC forces the first stage attributes to
12667                  *  Normal Non-Shareable,
12668                  *  Inner Write-Back Read-Allocate Write-Allocate,
12669                  *  Outer Write-Back Read-Allocate Write-Allocate.
12670                  * Do not overwrite Tagged within attrs.
12671                  */
12672                 if (cacheattrs->attrs != 0xf0) {
12673                     cacheattrs->attrs = 0xff;
12674                 }
12675                 cacheattrs->shareability = 0;
12676             }
12677             *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12678 
12679             /* Check if IPA translates to secure or non-secure PA space. */
12680             if (arm_is_secure_below_el3(env)) {
12681                 if (attrs->secure) {
12682                     attrs->secure =
12683                         !(env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW));
12684                 } else {
12685                     attrs->secure =
12686                         !((env->cp15.vtcr_el2.raw_tcr & (VTCR_NSA | VTCR_NSW))
12687                         || (env->cp15.vstcr_el2.raw_tcr & VSTCR_SA));
12688                 }
12689             }
12690             return 0;
12691         } else {
12692             /*
12693              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12694              */
12695             mmu_idx = stage_1_mmu_idx(mmu_idx);
12696         }
12697     }
12698 
12699     /* The page table entries may downgrade secure to non-secure, but
12700      * cannot upgrade an non-secure translation regime's attributes
12701      * to secure.
12702      */
12703     attrs->secure = regime_is_secure(env, mmu_idx);
12704     attrs->user = regime_is_user(env, mmu_idx);
12705 
12706     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12707      * In v7 and earlier it affects all stage 1 translations.
12708      */
12709     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
12710         && !arm_feature(env, ARM_FEATURE_V8)) {
12711         if (regime_el(env, mmu_idx) == 3) {
12712             address += env->cp15.fcseidr_s;
12713         } else {
12714             address += env->cp15.fcseidr_ns;
12715         }
12716     }
12717 
12718     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12719         bool ret;
12720         *page_size = TARGET_PAGE_SIZE;
12721 
12722         if (arm_feature(env, ARM_FEATURE_V8)) {
12723             /* PMSAv8 */
12724             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12725                                        phys_ptr, attrs, prot, page_size, fi);
12726         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12727             /* PMSAv7 */
12728             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12729                                        phys_ptr, prot, page_size, fi);
12730         } else {
12731             /* Pre-v7 MPU */
12732             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12733                                        phys_ptr, prot, fi);
12734         }
12735         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12736                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12737                       access_type == MMU_DATA_LOAD ? "reading" :
12738                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12739                       (uint32_t)address, mmu_idx,
12740                       ret ? "Miss" : "Hit",
12741                       *prot & PAGE_READ ? 'r' : '-',
12742                       *prot & PAGE_WRITE ? 'w' : '-',
12743                       *prot & PAGE_EXEC ? 'x' : '-');
12744 
12745         return ret;
12746     }
12747 
12748     /* Definitely a real MMU, not an MPU */
12749 
12750     if (regime_translation_disabled(env, mmu_idx)) {
12751         uint64_t hcr;
12752         uint8_t memattr;
12753 
12754         /*
12755          * MMU disabled.  S1 addresses within aa64 translation regimes are
12756          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
12757          */
12758         if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
12759             int r_el = regime_el(env, mmu_idx);
12760             if (arm_el_is_aa64(env, r_el)) {
12761                 int pamax = arm_pamax(env_archcpu(env));
12762                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
12763                 int addrtop, tbi;
12764 
12765                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
12766                 if (access_type == MMU_INST_FETCH) {
12767                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
12768                 }
12769                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
12770                 addrtop = (tbi ? 55 : 63);
12771 
12772                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
12773                     fi->type = ARMFault_AddressSize;
12774                     fi->level = 0;
12775                     fi->stage2 = false;
12776                     return 1;
12777                 }
12778 
12779                 /*
12780                  * When TBI is disabled, we've just validated that all of the
12781                  * bits above PAMax are zero, so logically we only need to
12782                  * clear the top byte for TBI.  But it's clearer to follow
12783                  * the pseudocode set of addrdesc.paddress.
12784                  */
12785                 address = extract64(address, 0, 52);
12786             }
12787         }
12788         *phys_ptr = address;
12789         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12790         *page_size = TARGET_PAGE_SIZE;
12791 
12792         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
12793         hcr = arm_hcr_el2_eff(env);
12794         cacheattrs->shareability = 0;
12795         if (hcr & HCR_DC) {
12796             if (hcr & HCR_DCT) {
12797                 memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
12798             } else {
12799                 memattr = 0xff;  /* Normal, WB, RWA */
12800             }
12801         } else if (access_type == MMU_INST_FETCH) {
12802             if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
12803                 memattr = 0xee;  /* Normal, WT, RA, NT */
12804             } else {
12805                 memattr = 0x44;  /* Normal, NC, No */
12806             }
12807             cacheattrs->shareability = 2; /* outer sharable */
12808         } else {
12809             memattr = 0x00;      /* Device, nGnRnE */
12810         }
12811         cacheattrs->attrs = memattr;
12812         return 0;
12813     }
12814 
12815     if (regime_using_lpae_format(env, mmu_idx)) {
12816         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
12817                                   phys_ptr, attrs, prot, page_size,
12818                                   fi, cacheattrs);
12819     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12820         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12821                                 phys_ptr, attrs, prot, page_size, fi);
12822     } else {
12823         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12824                                     phys_ptr, prot, page_size, fi);
12825     }
12826 }
12827 
12828 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12829                                          MemTxAttrs *attrs)
12830 {
12831     ARMCPU *cpu = ARM_CPU(cs);
12832     CPUARMState *env = &cpu->env;
12833     hwaddr phys_addr;
12834     target_ulong page_size;
12835     int prot;
12836     bool ret;
12837     ARMMMUFaultInfo fi = {};
12838     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12839     ARMCacheAttrs cacheattrs = {};
12840 
12841     *attrs = (MemTxAttrs) {};
12842 
12843     ret = get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &phys_addr,
12844                         attrs, &prot, &page_size, &fi, &cacheattrs);
12845 
12846     if (ret) {
12847         return -1;
12848     }
12849     return phys_addr;
12850 }
12851 
12852 #endif
12853 
12854 /* Note that signed overflow is undefined in C.  The following routines are
12855    careful to use unsigned types where modulo arithmetic is required.
12856    Failure to do so _will_ break on newer gcc.  */
12857 
12858 /* Signed saturating arithmetic.  */
12859 
12860 /* Perform 16-bit signed saturating addition.  */
12861 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
12862 {
12863     uint16_t res;
12864 
12865     res = a + b;
12866     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
12867         if (a & 0x8000)
12868             res = 0x8000;
12869         else
12870             res = 0x7fff;
12871     }
12872     return res;
12873 }
12874 
12875 /* Perform 8-bit signed saturating addition.  */
12876 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
12877 {
12878     uint8_t res;
12879 
12880     res = a + b;
12881     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
12882         if (a & 0x80)
12883             res = 0x80;
12884         else
12885             res = 0x7f;
12886     }
12887     return res;
12888 }
12889 
12890 /* Perform 16-bit signed saturating subtraction.  */
12891 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
12892 {
12893     uint16_t res;
12894 
12895     res = a - b;
12896     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
12897         if (a & 0x8000)
12898             res = 0x8000;
12899         else
12900             res = 0x7fff;
12901     }
12902     return res;
12903 }
12904 
12905 /* Perform 8-bit signed saturating subtraction.  */
12906 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
12907 {
12908     uint8_t res;
12909 
12910     res = a - b;
12911     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
12912         if (a & 0x80)
12913             res = 0x80;
12914         else
12915             res = 0x7f;
12916     }
12917     return res;
12918 }
12919 
12920 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
12921 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
12922 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
12923 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
12924 #define PFX q
12925 
12926 #include "op_addsub.h"
12927 
12928 /* Unsigned saturating arithmetic.  */
12929 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
12930 {
12931     uint16_t res;
12932     res = a + b;
12933     if (res < a)
12934         res = 0xffff;
12935     return res;
12936 }
12937 
12938 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
12939 {
12940     if (a > b)
12941         return a - b;
12942     else
12943         return 0;
12944 }
12945 
12946 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
12947 {
12948     uint8_t res;
12949     res = a + b;
12950     if (res < a)
12951         res = 0xff;
12952     return res;
12953 }
12954 
12955 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
12956 {
12957     if (a > b)
12958         return a - b;
12959     else
12960         return 0;
12961 }
12962 
12963 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
12964 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
12965 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
12966 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
12967 #define PFX uq
12968 
12969 #include "op_addsub.h"
12970 
12971 /* Signed modulo arithmetic.  */
12972 #define SARITH16(a, b, n, op) do { \
12973     int32_t sum; \
12974     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
12975     RESULT(sum, n, 16); \
12976     if (sum >= 0) \
12977         ge |= 3 << (n * 2); \
12978     } while(0)
12979 
12980 #define SARITH8(a, b, n, op) do { \
12981     int32_t sum; \
12982     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
12983     RESULT(sum, n, 8); \
12984     if (sum >= 0) \
12985         ge |= 1 << n; \
12986     } while(0)
12987 
12988 
12989 #define ADD16(a, b, n) SARITH16(a, b, n, +)
12990 #define SUB16(a, b, n) SARITH16(a, b, n, -)
12991 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
12992 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
12993 #define PFX s
12994 #define ARITH_GE
12995 
12996 #include "op_addsub.h"
12997 
12998 /* Unsigned modulo arithmetic.  */
12999 #define ADD16(a, b, n) do { \
13000     uint32_t sum; \
13001     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
13002     RESULT(sum, n, 16); \
13003     if ((sum >> 16) == 1) \
13004         ge |= 3 << (n * 2); \
13005     } while(0)
13006 
13007 #define ADD8(a, b, n) do { \
13008     uint32_t sum; \
13009     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
13010     RESULT(sum, n, 8); \
13011     if ((sum >> 8) == 1) \
13012         ge |= 1 << n; \
13013     } while(0)
13014 
13015 #define SUB16(a, b, n) do { \
13016     uint32_t sum; \
13017     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
13018     RESULT(sum, n, 16); \
13019     if ((sum >> 16) == 0) \
13020         ge |= 3 << (n * 2); \
13021     } while(0)
13022 
13023 #define SUB8(a, b, n) do { \
13024     uint32_t sum; \
13025     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
13026     RESULT(sum, n, 8); \
13027     if ((sum >> 8) == 0) \
13028         ge |= 1 << n; \
13029     } while(0)
13030 
13031 #define PFX u
13032 #define ARITH_GE
13033 
13034 #include "op_addsub.h"
13035 
13036 /* Halved signed arithmetic.  */
13037 #define ADD16(a, b, n) \
13038   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
13039 #define SUB16(a, b, n) \
13040   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
13041 #define ADD8(a, b, n) \
13042   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
13043 #define SUB8(a, b, n) \
13044   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
13045 #define PFX sh
13046 
13047 #include "op_addsub.h"
13048 
13049 /* Halved unsigned arithmetic.  */
13050 #define ADD16(a, b, n) \
13051   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13052 #define SUB16(a, b, n) \
13053   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13054 #define ADD8(a, b, n) \
13055   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13056 #define SUB8(a, b, n) \
13057   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13058 #define PFX uh
13059 
13060 #include "op_addsub.h"
13061 
13062 static inline uint8_t do_usad(uint8_t a, uint8_t b)
13063 {
13064     if (a > b)
13065         return a - b;
13066     else
13067         return b - a;
13068 }
13069 
13070 /* Unsigned sum of absolute byte differences.  */
13071 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
13072 {
13073     uint32_t sum;
13074     sum = do_usad(a, b);
13075     sum += do_usad(a >> 8, b >> 8);
13076     sum += do_usad(a >> 16, b >> 16);
13077     sum += do_usad(a >> 24, b >> 24);
13078     return sum;
13079 }
13080 
13081 /* For ARMv6 SEL instruction.  */
13082 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
13083 {
13084     uint32_t mask;
13085 
13086     mask = 0;
13087     if (flags & 1)
13088         mask |= 0xff;
13089     if (flags & 2)
13090         mask |= 0xff00;
13091     if (flags & 4)
13092         mask |= 0xff0000;
13093     if (flags & 8)
13094         mask |= 0xff000000;
13095     return (a & mask) | (b & ~mask);
13096 }
13097 
13098 /* CRC helpers.
13099  * The upper bytes of val (above the number specified by 'bytes') must have
13100  * been zeroed out by the caller.
13101  */
13102 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
13103 {
13104     uint8_t buf[4];
13105 
13106     stl_le_p(buf, val);
13107 
13108     /* zlib crc32 converts the accumulator and output to one's complement.  */
13109     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
13110 }
13111 
13112 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
13113 {
13114     uint8_t buf[4];
13115 
13116     stl_le_p(buf, val);
13117 
13118     /* Linux crc32c converts the output to one's complement.  */
13119     return crc32c(acc, buf, bytes) ^ 0xffffffff;
13120 }
13121 
13122 /* Return the exception level to which FP-disabled exceptions should
13123  * be taken, or 0 if FP is enabled.
13124  */
13125 int fp_exception_el(CPUARMState *env, int cur_el)
13126 {
13127 #ifndef CONFIG_USER_ONLY
13128     /* CPACR and the CPTR registers don't exist before v6, so FP is
13129      * always accessible
13130      */
13131     if (!arm_feature(env, ARM_FEATURE_V6)) {
13132         return 0;
13133     }
13134 
13135     if (arm_feature(env, ARM_FEATURE_M)) {
13136         /* CPACR can cause a NOCP UsageFault taken to current security state */
13137         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
13138             return 1;
13139         }
13140 
13141         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
13142             if (!extract32(env->v7m.nsacr, 10, 1)) {
13143                 /* FP insns cause a NOCP UsageFault taken to Secure */
13144                 return 3;
13145             }
13146         }
13147 
13148         return 0;
13149     }
13150 
13151     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
13152      * 0, 2 : trap EL0 and EL1/PL1 accesses
13153      * 1    : trap only EL0 accesses
13154      * 3    : trap no accesses
13155      * This register is ignored if E2H+TGE are both set.
13156      */
13157     if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13158         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
13159 
13160         switch (fpen) {
13161         case 0:
13162         case 2:
13163             if (cur_el == 0 || cur_el == 1) {
13164                 /* Trap to PL1, which might be EL1 or EL3 */
13165                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
13166                     return 3;
13167                 }
13168                 return 1;
13169             }
13170             if (cur_el == 3 && !is_a64(env)) {
13171                 /* Secure PL1 running at EL3 */
13172                 return 3;
13173             }
13174             break;
13175         case 1:
13176             if (cur_el == 0) {
13177                 return 1;
13178             }
13179             break;
13180         case 3:
13181             break;
13182         }
13183     }
13184 
13185     /*
13186      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
13187      * to control non-secure access to the FPU. It doesn't have any
13188      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
13189      */
13190     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
13191          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
13192         if (!extract32(env->cp15.nsacr, 10, 1)) {
13193             /* FP insns act as UNDEF */
13194             return cur_el == 2 ? 2 : 1;
13195         }
13196     }
13197 
13198     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
13199      * check because zero bits in the registers mean "don't trap".
13200      */
13201 
13202     /* CPTR_EL2 : present in v7VE or v8 */
13203     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
13204         && arm_is_el2_enabled(env)) {
13205         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
13206         return 2;
13207     }
13208 
13209     /* CPTR_EL3 : present in v8 */
13210     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
13211         /* Trap all FP ops to EL3 */
13212         return 3;
13213     }
13214 #endif
13215     return 0;
13216 }
13217 
13218 /* Return the exception level we're running at if this is our mmu_idx */
13219 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
13220 {
13221     if (mmu_idx & ARM_MMU_IDX_M) {
13222         return mmu_idx & ARM_MMU_IDX_M_PRIV;
13223     }
13224 
13225     switch (mmu_idx) {
13226     case ARMMMUIdx_E10_0:
13227     case ARMMMUIdx_E20_0:
13228     case ARMMMUIdx_SE10_0:
13229     case ARMMMUIdx_SE20_0:
13230         return 0;
13231     case ARMMMUIdx_E10_1:
13232     case ARMMMUIdx_E10_1_PAN:
13233     case ARMMMUIdx_SE10_1:
13234     case ARMMMUIdx_SE10_1_PAN:
13235         return 1;
13236     case ARMMMUIdx_E2:
13237     case ARMMMUIdx_E20_2:
13238     case ARMMMUIdx_E20_2_PAN:
13239     case ARMMMUIdx_SE2:
13240     case ARMMMUIdx_SE20_2:
13241     case ARMMMUIdx_SE20_2_PAN:
13242         return 2;
13243     case ARMMMUIdx_SE3:
13244         return 3;
13245     default:
13246         g_assert_not_reached();
13247     }
13248 }
13249 
13250 #ifndef CONFIG_TCG
13251 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
13252 {
13253     g_assert_not_reached();
13254 }
13255 #endif
13256 
13257 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
13258 {
13259     ARMMMUIdx idx;
13260     uint64_t hcr;
13261 
13262     if (arm_feature(env, ARM_FEATURE_M)) {
13263         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
13264     }
13265 
13266     /* See ARM pseudo-function ELIsInHost.  */
13267     switch (el) {
13268     case 0:
13269         hcr = arm_hcr_el2_eff(env);
13270         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
13271             idx = ARMMMUIdx_E20_0;
13272         } else {
13273             idx = ARMMMUIdx_E10_0;
13274         }
13275         break;
13276     case 1:
13277         if (env->pstate & PSTATE_PAN) {
13278             idx = ARMMMUIdx_E10_1_PAN;
13279         } else {
13280             idx = ARMMMUIdx_E10_1;
13281         }
13282         break;
13283     case 2:
13284         /* Note that TGE does not apply at EL2.  */
13285         if (arm_hcr_el2_eff(env) & HCR_E2H) {
13286             if (env->pstate & PSTATE_PAN) {
13287                 idx = ARMMMUIdx_E20_2_PAN;
13288             } else {
13289                 idx = ARMMMUIdx_E20_2;
13290             }
13291         } else {
13292             idx = ARMMMUIdx_E2;
13293         }
13294         break;
13295     case 3:
13296         return ARMMMUIdx_SE3;
13297     default:
13298         g_assert_not_reached();
13299     }
13300 
13301     if (arm_is_secure_below_el3(env)) {
13302         idx &= ~ARM_MMU_IDX_A_NS;
13303     }
13304 
13305     return idx;
13306 }
13307 
13308 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
13309 {
13310     return arm_mmu_idx_el(env, arm_current_el(env));
13311 }
13312 
13313 #ifndef CONFIG_USER_ONLY
13314 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
13315 {
13316     return stage_1_mmu_idx(arm_mmu_idx(env));
13317 }
13318 #endif
13319 
13320 static CPUARMTBFlags rebuild_hflags_common(CPUARMState *env, int fp_el,
13321                                            ARMMMUIdx mmu_idx,
13322                                            CPUARMTBFlags flags)
13323 {
13324     DP_TBFLAG_ANY(flags, FPEXC_EL, fp_el);
13325     DP_TBFLAG_ANY(flags, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
13326 
13327     if (arm_singlestep_active(env)) {
13328         DP_TBFLAG_ANY(flags, SS_ACTIVE, 1);
13329     }
13330     return flags;
13331 }
13332 
13333 static CPUARMTBFlags rebuild_hflags_common_32(CPUARMState *env, int fp_el,
13334                                               ARMMMUIdx mmu_idx,
13335                                               CPUARMTBFlags flags)
13336 {
13337     bool sctlr_b = arm_sctlr_b(env);
13338 
13339     if (sctlr_b) {
13340         DP_TBFLAG_A32(flags, SCTLR__B, 1);
13341     }
13342     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
13343         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13344     }
13345     DP_TBFLAG_A32(flags, NS, !access_secure_reg(env));
13346 
13347     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13348 }
13349 
13350 static CPUARMTBFlags rebuild_hflags_m32(CPUARMState *env, int fp_el,
13351                                         ARMMMUIdx mmu_idx)
13352 {
13353     CPUARMTBFlags flags = {};
13354     uint32_t ccr = env->v7m.ccr[env->v7m.secure];
13355 
13356     /* Without HaveMainExt, CCR.UNALIGN_TRP is RES1. */
13357     if (ccr & R_V7M_CCR_UNALIGN_TRP_MASK) {
13358         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13359     }
13360 
13361     if (arm_v7m_is_handler_mode(env)) {
13362         DP_TBFLAG_M32(flags, HANDLER, 1);
13363     }
13364 
13365     /*
13366      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
13367      * is suppressing them because the requested execution priority
13368      * is less than 0.
13369      */
13370     if (arm_feature(env, ARM_FEATURE_V8) &&
13371         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
13372           (ccr & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13373         DP_TBFLAG_M32(flags, STACKCHECK, 1);
13374     }
13375 
13376     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13377 }
13378 
13379 static CPUARMTBFlags rebuild_hflags_aprofile(CPUARMState *env)
13380 {
13381     CPUARMTBFlags flags = {};
13382 
13383     DP_TBFLAG_ANY(flags, DEBUG_TARGET_EL, arm_debug_target_el(env));
13384     return flags;
13385 }
13386 
13387 static CPUARMTBFlags rebuild_hflags_a32(CPUARMState *env, int fp_el,
13388                                         ARMMMUIdx mmu_idx)
13389 {
13390     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13391     int el = arm_current_el(env);
13392 
13393     if (arm_sctlr(env, el) & SCTLR_A) {
13394         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13395     }
13396 
13397     if (arm_el_is_aa64(env, 1)) {
13398         DP_TBFLAG_A32(flags, VFPEN, 1);
13399     }
13400 
13401     if (el < 2 && env->cp15.hstr_el2 &&
13402         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13403         DP_TBFLAG_A32(flags, HSTR_ACTIVE, 1);
13404     }
13405 
13406     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13407 }
13408 
13409 static CPUARMTBFlags rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
13410                                         ARMMMUIdx mmu_idx)
13411 {
13412     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13413     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13414     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
13415     uint64_t sctlr;
13416     int tbii, tbid;
13417 
13418     DP_TBFLAG_ANY(flags, AARCH64_STATE, 1);
13419 
13420     /* Get control bits for tagged addresses.  */
13421     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
13422     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
13423 
13424     DP_TBFLAG_A64(flags, TBII, tbii);
13425     DP_TBFLAG_A64(flags, TBID, tbid);
13426 
13427     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
13428         int sve_el = sve_exception_el(env, el);
13429         uint32_t zcr_len;
13430 
13431         /*
13432          * If SVE is disabled, but FP is enabled,
13433          * then the effective len is 0.
13434          */
13435         if (sve_el != 0 && fp_el == 0) {
13436             zcr_len = 0;
13437         } else {
13438             zcr_len = sve_zcr_len_for_el(env, el);
13439         }
13440         DP_TBFLAG_A64(flags, SVEEXC_EL, sve_el);
13441         DP_TBFLAG_A64(flags, ZCR_LEN, zcr_len);
13442     }
13443 
13444     sctlr = regime_sctlr(env, stage1);
13445 
13446     if (sctlr & SCTLR_A) {
13447         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13448     }
13449 
13450     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
13451         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13452     }
13453 
13454     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
13455         /*
13456          * In order to save space in flags, we record only whether
13457          * pauth is "inactive", meaning all insns are implemented as
13458          * a nop, or "active" when some action must be performed.
13459          * The decision of which action to take is left to a helper.
13460          */
13461         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13462             DP_TBFLAG_A64(flags, PAUTH_ACTIVE, 1);
13463         }
13464     }
13465 
13466     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13467         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13468         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13469             DP_TBFLAG_A64(flags, BT, 1);
13470         }
13471     }
13472 
13473     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
13474     if (!(env->pstate & PSTATE_UAO)) {
13475         switch (mmu_idx) {
13476         case ARMMMUIdx_E10_1:
13477         case ARMMMUIdx_E10_1_PAN:
13478         case ARMMMUIdx_SE10_1:
13479         case ARMMMUIdx_SE10_1_PAN:
13480             /* TODO: ARMv8.3-NV */
13481             DP_TBFLAG_A64(flags, UNPRIV, 1);
13482             break;
13483         case ARMMMUIdx_E20_2:
13484         case ARMMMUIdx_E20_2_PAN:
13485         case ARMMMUIdx_SE20_2:
13486         case ARMMMUIdx_SE20_2_PAN:
13487             /*
13488              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
13489              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
13490              */
13491             if (env->cp15.hcr_el2 & HCR_TGE) {
13492                 DP_TBFLAG_A64(flags, UNPRIV, 1);
13493             }
13494             break;
13495         default:
13496             break;
13497         }
13498     }
13499 
13500     if (cpu_isar_feature(aa64_mte, env_archcpu(env))) {
13501         /*
13502          * Set MTE_ACTIVE if any access may be Checked, and leave clear
13503          * if all accesses must be Unchecked:
13504          * 1) If no TBI, then there are no tags in the address to check,
13505          * 2) If Tag Check Override, then all accesses are Unchecked,
13506          * 3) If Tag Check Fail == 0, then Checked access have no effect,
13507          * 4) If no Allocation Tag Access, then all accesses are Unchecked.
13508          */
13509         if (allocation_tag_access_enabled(env, el, sctlr)) {
13510             DP_TBFLAG_A64(flags, ATA, 1);
13511             if (tbid
13512                 && !(env->pstate & PSTATE_TCO)
13513                 && (sctlr & (el == 0 ? SCTLR_TCF0 : SCTLR_TCF))) {
13514                 DP_TBFLAG_A64(flags, MTE_ACTIVE, 1);
13515             }
13516         }
13517         /* And again for unprivileged accesses, if required.  */
13518         if (EX_TBFLAG_A64(flags, UNPRIV)
13519             && tbid
13520             && !(env->pstate & PSTATE_TCO)
13521             && (sctlr & SCTLR_TCF0)
13522             && allocation_tag_access_enabled(env, 0, sctlr)) {
13523             DP_TBFLAG_A64(flags, MTE0_ACTIVE, 1);
13524         }
13525         /* Cache TCMA as well as TBI. */
13526         DP_TBFLAG_A64(flags, TCMA, aa64_va_parameter_tcma(tcr, mmu_idx));
13527     }
13528 
13529     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13530 }
13531 
13532 static CPUARMTBFlags rebuild_hflags_internal(CPUARMState *env)
13533 {
13534     int el = arm_current_el(env);
13535     int fp_el = fp_exception_el(env, el);
13536     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13537 
13538     if (is_a64(env)) {
13539         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13540     } else if (arm_feature(env, ARM_FEATURE_M)) {
13541         return rebuild_hflags_m32(env, fp_el, mmu_idx);
13542     } else {
13543         return rebuild_hflags_a32(env, fp_el, mmu_idx);
13544     }
13545 }
13546 
13547 void arm_rebuild_hflags(CPUARMState *env)
13548 {
13549     env->hflags = rebuild_hflags_internal(env);
13550 }
13551 
13552 /*
13553  * If we have triggered a EL state change we can't rely on the
13554  * translator having passed it to us, we need to recompute.
13555  */
13556 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
13557 {
13558     int el = arm_current_el(env);
13559     int fp_el = fp_exception_el(env, el);
13560     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13561 
13562     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13563 }
13564 
13565 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
13566 {
13567     int fp_el = fp_exception_el(env, el);
13568     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13569 
13570     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13571 }
13572 
13573 /*
13574  * If we have triggered a EL state change we can't rely on the
13575  * translator having passed it to us, we need to recompute.
13576  */
13577 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
13578 {
13579     int el = arm_current_el(env);
13580     int fp_el = fp_exception_el(env, el);
13581     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13582     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13583 }
13584 
13585 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
13586 {
13587     int fp_el = fp_exception_el(env, el);
13588     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13589 
13590     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13591 }
13592 
13593 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
13594 {
13595     int fp_el = fp_exception_el(env, el);
13596     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13597 
13598     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13599 }
13600 
13601 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
13602 {
13603 #ifdef CONFIG_DEBUG_TCG
13604     CPUARMTBFlags c = env->hflags;
13605     CPUARMTBFlags r = rebuild_hflags_internal(env);
13606 
13607     if (unlikely(c.flags != r.flags || c.flags2 != r.flags2)) {
13608         fprintf(stderr, "TCG hflags mismatch "
13609                         "(current:(0x%08x,0x" TARGET_FMT_lx ")"
13610                         " rebuilt:(0x%08x,0x" TARGET_FMT_lx ")\n",
13611                 c.flags, c.flags2, r.flags, r.flags2);
13612         abort();
13613     }
13614 #endif
13615 }
13616 
13617 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13618                           target_ulong *cs_base, uint32_t *pflags)
13619 {
13620     CPUARMTBFlags flags;
13621 
13622     assert_hflags_rebuild_correctly(env);
13623     flags = env->hflags;
13624 
13625     if (EX_TBFLAG_ANY(flags, AARCH64_STATE)) {
13626         *pc = env->pc;
13627         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13628             DP_TBFLAG_A64(flags, BTYPE, env->btype);
13629         }
13630     } else {
13631         *pc = env->regs[15];
13632 
13633         if (arm_feature(env, ARM_FEATURE_M)) {
13634             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13635                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
13636                 != env->v7m.secure) {
13637                 DP_TBFLAG_M32(flags, FPCCR_S_WRONG, 1);
13638             }
13639 
13640             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13641                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13642                  (env->v7m.secure &&
13643                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13644                 /*
13645                  * ASPEN is set, but FPCA/SFPA indicate that there is no
13646                  * active FP context; we must create a new FP context before
13647                  * executing any FP insn.
13648                  */
13649                 DP_TBFLAG_M32(flags, NEW_FP_CTXT_NEEDED, 1);
13650             }
13651 
13652             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13653             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13654                 DP_TBFLAG_M32(flags, LSPACT, 1);
13655             }
13656         } else {
13657             /*
13658              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
13659              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
13660              */
13661             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13662                 DP_TBFLAG_A32(flags, XSCALE_CPAR, env->cp15.c15_cpar);
13663             } else {
13664                 DP_TBFLAG_A32(flags, VECLEN, env->vfp.vec_len);
13665                 DP_TBFLAG_A32(flags, VECSTRIDE, env->vfp.vec_stride);
13666             }
13667             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
13668                 DP_TBFLAG_A32(flags, VFPEN, 1);
13669             }
13670         }
13671 
13672         DP_TBFLAG_AM32(flags, THUMB, env->thumb);
13673         DP_TBFLAG_AM32(flags, CONDEXEC, env->condexec_bits);
13674     }
13675 
13676     /*
13677      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13678      * states defined in the ARM ARM for software singlestep:
13679      *  SS_ACTIVE   PSTATE.SS   State
13680      *     0            x       Inactive (the TB flag for SS is always 0)
13681      *     1            0       Active-pending
13682      *     1            1       Active-not-pending
13683      * SS_ACTIVE is set in hflags; PSTATE__SS is computed every TB.
13684      */
13685     if (EX_TBFLAG_ANY(flags, SS_ACTIVE) && (env->pstate & PSTATE_SS)) {
13686         DP_TBFLAG_ANY(flags, PSTATE__SS, 1);
13687     }
13688 
13689     *pflags = flags.flags;
13690     *cs_base = flags.flags2;
13691 }
13692 
13693 #ifdef TARGET_AARCH64
13694 /*
13695  * The manual says that when SVE is enabled and VQ is widened the
13696  * implementation is allowed to zero the previously inaccessible
13697  * portion of the registers.  The corollary to that is that when
13698  * SVE is enabled and VQ is narrowed we are also allowed to zero
13699  * the now inaccessible portion of the registers.
13700  *
13701  * The intent of this is that no predicate bit beyond VQ is ever set.
13702  * Which means that some operations on predicate registers themselves
13703  * may operate on full uint64_t or even unrolled across the maximum
13704  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13705  * may well be cheaper than conditionals to restrict the operation
13706  * to the relevant portion of a uint16_t[16].
13707  */
13708 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13709 {
13710     int i, j;
13711     uint64_t pmask;
13712 
13713     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13714     assert(vq <= env_archcpu(env)->sve_max_vq);
13715 
13716     /* Zap the high bits of the zregs.  */
13717     for (i = 0; i < 32; i++) {
13718         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13719     }
13720 
13721     /* Zap the high bits of the pregs and ffr.  */
13722     pmask = 0;
13723     if (vq & 3) {
13724         pmask = ~(-1ULL << (16 * (vq & 3)));
13725     }
13726     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13727         for (i = 0; i < 17; ++i) {
13728             env->vfp.pregs[i].p[j] &= pmask;
13729         }
13730         pmask = 0;
13731     }
13732 }
13733 
13734 /*
13735  * Notice a change in SVE vector size when changing EL.
13736  */
13737 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13738                            int new_el, bool el0_a64)
13739 {
13740     ARMCPU *cpu = env_archcpu(env);
13741     int old_len, new_len;
13742     bool old_a64, new_a64;
13743 
13744     /* Nothing to do if no SVE.  */
13745     if (!cpu_isar_feature(aa64_sve, cpu)) {
13746         return;
13747     }
13748 
13749     /* Nothing to do if FP is disabled in either EL.  */
13750     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13751         return;
13752     }
13753 
13754     /*
13755      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13756      * at ELx, or not available because the EL is in AArch32 state, then
13757      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13758      * has an effective value of 0".
13759      *
13760      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13761      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13762      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13763      * we already have the correct register contents when encountering the
13764      * vq0->vq0 transition between EL0->EL1.
13765      */
13766     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13767     old_len = (old_a64 && !sve_exception_el(env, old_el)
13768                ? sve_zcr_len_for_el(env, old_el) : 0);
13769     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13770     new_len = (new_a64 && !sve_exception_el(env, new_el)
13771                ? sve_zcr_len_for_el(env, new_el) : 0);
13772 
13773     /* When changing vector length, clear inaccessible state.  */
13774     if (new_len < old_len) {
13775         aarch64_sve_narrow_vq(env, new_len + 1);
13776     }
13777 }
13778 #endif
13779