xref: /openbmc/qemu/target/arm/helper.c (revision 8b1d5b3c)
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 typedef struct pm_event {
1118     uint16_t number; /* PMEVTYPER.evtCount is 16 bits wide */
1119     /* If the event is supported on this CPU (used to generate PMCEID[01]) */
1120     bool (*supported)(CPUARMState *);
1121     /*
1122      * Retrieve the current count of the underlying event. The programmed
1123      * counters hold a difference from the return value from this function
1124      */
1125     uint64_t (*get_count)(CPUARMState *);
1126     /*
1127      * Return how many nanoseconds it will take (at a minimum) for count events
1128      * to occur. A negative value indicates the counter will never overflow, or
1129      * that the counter has otherwise arranged for the overflow bit to be set
1130      * and the PMU interrupt to be raised on overflow.
1131      */
1132     int64_t (*ns_per_count)(uint64_t);
1133 } pm_event;
1134 
1135 static bool event_always_supported(CPUARMState *env)
1136 {
1137     return true;
1138 }
1139 
1140 static uint64_t swinc_get_count(CPUARMState *env)
1141 {
1142     /*
1143      * SW_INCR events are written directly to the pmevcntr's by writes to
1144      * PMSWINC, so there is no underlying count maintained by the PMU itself
1145      */
1146     return 0;
1147 }
1148 
1149 static int64_t swinc_ns_per(uint64_t ignored)
1150 {
1151     return -1;
1152 }
1153 
1154 /*
1155  * Return the underlying cycle count for the PMU cycle counters. If we're in
1156  * usermode, simply return 0.
1157  */
1158 static uint64_t cycles_get_count(CPUARMState *env)
1159 {
1160 #ifndef CONFIG_USER_ONLY
1161     return muldiv64(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL),
1162                    ARM_CPU_FREQ, NANOSECONDS_PER_SECOND);
1163 #else
1164     return cpu_get_host_ticks();
1165 #endif
1166 }
1167 
1168 #ifndef CONFIG_USER_ONLY
1169 static int64_t cycles_ns_per(uint64_t cycles)
1170 {
1171     return (ARM_CPU_FREQ / NANOSECONDS_PER_SECOND) * cycles;
1172 }
1173 
1174 static bool instructions_supported(CPUARMState *env)
1175 {
1176     return icount_enabled() == 1; /* Precise instruction counting */
1177 }
1178 
1179 static uint64_t instructions_get_count(CPUARMState *env)
1180 {
1181     return (uint64_t)icount_get_raw();
1182 }
1183 
1184 static int64_t instructions_ns_per(uint64_t icount)
1185 {
1186     return icount_to_ns((int64_t)icount);
1187 }
1188 #endif
1189 
1190 static bool pmu_8_1_events_supported(CPUARMState *env)
1191 {
1192     /* For events which are supported in any v8.1 PMU */
1193     return cpu_isar_feature(any_pmu_8_1, env_archcpu(env));
1194 }
1195 
1196 static bool pmu_8_4_events_supported(CPUARMState *env)
1197 {
1198     /* For events which are supported in any v8.1 PMU */
1199     return cpu_isar_feature(any_pmu_8_4, env_archcpu(env));
1200 }
1201 
1202 static uint64_t zero_event_get_count(CPUARMState *env)
1203 {
1204     /* For events which on QEMU never fire, so their count is always zero */
1205     return 0;
1206 }
1207 
1208 static int64_t zero_event_ns_per(uint64_t cycles)
1209 {
1210     /* An event which never fires can never overflow */
1211     return -1;
1212 }
1213 
1214 static const pm_event pm_events[] = {
1215     { .number = 0x000, /* SW_INCR */
1216       .supported = event_always_supported,
1217       .get_count = swinc_get_count,
1218       .ns_per_count = swinc_ns_per,
1219     },
1220 #ifndef CONFIG_USER_ONLY
1221     { .number = 0x008, /* INST_RETIRED, Instruction architecturally executed */
1222       .supported = instructions_supported,
1223       .get_count = instructions_get_count,
1224       .ns_per_count = instructions_ns_per,
1225     },
1226     { .number = 0x011, /* CPU_CYCLES, Cycle */
1227       .supported = event_always_supported,
1228       .get_count = cycles_get_count,
1229       .ns_per_count = cycles_ns_per,
1230     },
1231 #endif
1232     { .number = 0x023, /* STALL_FRONTEND */
1233       .supported = pmu_8_1_events_supported,
1234       .get_count = zero_event_get_count,
1235       .ns_per_count = zero_event_ns_per,
1236     },
1237     { .number = 0x024, /* STALL_BACKEND */
1238       .supported = pmu_8_1_events_supported,
1239       .get_count = zero_event_get_count,
1240       .ns_per_count = zero_event_ns_per,
1241     },
1242     { .number = 0x03c, /* STALL */
1243       .supported = pmu_8_4_events_supported,
1244       .get_count = zero_event_get_count,
1245       .ns_per_count = zero_event_ns_per,
1246     },
1247 };
1248 
1249 /*
1250  * Note: Before increasing MAX_EVENT_ID beyond 0x3f into the 0x40xx range of
1251  * events (i.e. the statistical profiling extension), this implementation
1252  * should first be updated to something sparse instead of the current
1253  * supported_event_map[] array.
1254  */
1255 #define MAX_EVENT_ID 0x3c
1256 #define UNSUPPORTED_EVENT UINT16_MAX
1257 static uint16_t supported_event_map[MAX_EVENT_ID + 1];
1258 
1259 /*
1260  * Called upon CPU initialization to initialize PMCEID[01]_EL0 and build a map
1261  * of ARM event numbers to indices in our pm_events array.
1262  *
1263  * Note: Events in the 0x40XX range are not currently supported.
1264  */
1265 void pmu_init(ARMCPU *cpu)
1266 {
1267     unsigned int i;
1268 
1269     /*
1270      * Empty supported_event_map and cpu->pmceid[01] before adding supported
1271      * events to them
1272      */
1273     for (i = 0; i < ARRAY_SIZE(supported_event_map); i++) {
1274         supported_event_map[i] = UNSUPPORTED_EVENT;
1275     }
1276     cpu->pmceid0 = 0;
1277     cpu->pmceid1 = 0;
1278 
1279     for (i = 0; i < ARRAY_SIZE(pm_events); i++) {
1280         const pm_event *cnt = &pm_events[i];
1281         assert(cnt->number <= MAX_EVENT_ID);
1282         /* We do not currently support events in the 0x40xx range */
1283         assert(cnt->number <= 0x3f);
1284 
1285         if (cnt->supported(&cpu->env)) {
1286             supported_event_map[cnt->number] = i;
1287             uint64_t event_mask = 1ULL << (cnt->number & 0x1f);
1288             if (cnt->number & 0x20) {
1289                 cpu->pmceid1 |= event_mask;
1290             } else {
1291                 cpu->pmceid0 |= event_mask;
1292             }
1293         }
1294     }
1295 }
1296 
1297 /*
1298  * Check at runtime whether a PMU event is supported for the current machine
1299  */
1300 static bool event_supported(uint16_t number)
1301 {
1302     if (number > MAX_EVENT_ID) {
1303         return false;
1304     }
1305     return supported_event_map[number] != UNSUPPORTED_EVENT;
1306 }
1307 
1308 static CPAccessResult pmreg_access(CPUARMState *env, const ARMCPRegInfo *ri,
1309                                    bool isread)
1310 {
1311     /* Performance monitor registers user accessibility is controlled
1312      * by PMUSERENR. MDCR_EL2.TPM and MDCR_EL3.TPM allow configurable
1313      * trapping to EL2 or EL3 for other accesses.
1314      */
1315     int el = arm_current_el(env);
1316     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1317 
1318     if (el == 0 && !(env->cp15.c9_pmuserenr & 1)) {
1319         return CP_ACCESS_TRAP;
1320     }
1321     if (el < 2 && (mdcr_el2 & MDCR_TPM)) {
1322         return CP_ACCESS_TRAP_EL2;
1323     }
1324     if (el < 3 && (env->cp15.mdcr_el3 & MDCR_TPM)) {
1325         return CP_ACCESS_TRAP_EL3;
1326     }
1327 
1328     return CP_ACCESS_OK;
1329 }
1330 
1331 static CPAccessResult pmreg_access_xevcntr(CPUARMState *env,
1332                                            const ARMCPRegInfo *ri,
1333                                            bool isread)
1334 {
1335     /* ER: event counter read trap control */
1336     if (arm_feature(env, ARM_FEATURE_V8)
1337         && arm_current_el(env) == 0
1338         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0
1339         && isread) {
1340         return CP_ACCESS_OK;
1341     }
1342 
1343     return pmreg_access(env, ri, isread);
1344 }
1345 
1346 static CPAccessResult pmreg_access_swinc(CPUARMState *env,
1347                                          const ARMCPRegInfo *ri,
1348                                          bool isread)
1349 {
1350     /* SW: software increment write trap control */
1351     if (arm_feature(env, ARM_FEATURE_V8)
1352         && arm_current_el(env) == 0
1353         && (env->cp15.c9_pmuserenr & (1 << 1)) != 0
1354         && !isread) {
1355         return CP_ACCESS_OK;
1356     }
1357 
1358     return pmreg_access(env, ri, isread);
1359 }
1360 
1361 static CPAccessResult pmreg_access_selr(CPUARMState *env,
1362                                         const ARMCPRegInfo *ri,
1363                                         bool isread)
1364 {
1365     /* ER: event counter read trap control */
1366     if (arm_feature(env, ARM_FEATURE_V8)
1367         && arm_current_el(env) == 0
1368         && (env->cp15.c9_pmuserenr & (1 << 3)) != 0) {
1369         return CP_ACCESS_OK;
1370     }
1371 
1372     return pmreg_access(env, ri, isread);
1373 }
1374 
1375 static CPAccessResult pmreg_access_ccntr(CPUARMState *env,
1376                                          const ARMCPRegInfo *ri,
1377                                          bool isread)
1378 {
1379     /* CR: cycle counter read trap control */
1380     if (arm_feature(env, ARM_FEATURE_V8)
1381         && arm_current_el(env) == 0
1382         && (env->cp15.c9_pmuserenr & (1 << 2)) != 0
1383         && isread) {
1384         return CP_ACCESS_OK;
1385     }
1386 
1387     return pmreg_access(env, ri, isread);
1388 }
1389 
1390 /* Returns true if the counter (pass 31 for PMCCNTR) should count events using
1391  * the current EL, security state, and register configuration.
1392  */
1393 static bool pmu_counter_enabled(CPUARMState *env, uint8_t counter)
1394 {
1395     uint64_t filter;
1396     bool e, p, u, nsk, nsu, nsh, m;
1397     bool enabled, prohibited, filtered;
1398     bool secure = arm_is_secure(env);
1399     int el = arm_current_el(env);
1400     uint64_t mdcr_el2 = arm_mdcr_el2_eff(env);
1401     uint8_t hpmn = mdcr_el2 & MDCR_HPMN;
1402 
1403     if (!arm_feature(env, ARM_FEATURE_PMU)) {
1404         return false;
1405     }
1406 
1407     if (!arm_feature(env, ARM_FEATURE_EL2) ||
1408             (counter < hpmn || counter == 31)) {
1409         e = env->cp15.c9_pmcr & PMCRE;
1410     } else {
1411         e = mdcr_el2 & MDCR_HPME;
1412     }
1413     enabled = e && (env->cp15.c9_pmcnten & (1 << counter));
1414 
1415     if (!secure) {
1416         if (el == 2 && (counter < hpmn || counter == 31)) {
1417             prohibited = mdcr_el2 & MDCR_HPMD;
1418         } else {
1419             prohibited = false;
1420         }
1421     } else {
1422         prohibited = arm_feature(env, ARM_FEATURE_EL3) &&
1423            !(env->cp15.mdcr_el3 & MDCR_SPME);
1424     }
1425 
1426     if (prohibited && counter == 31) {
1427         prohibited = env->cp15.c9_pmcr & PMCRDP;
1428     }
1429 
1430     if (counter == 31) {
1431         filter = env->cp15.pmccfiltr_el0;
1432     } else {
1433         filter = env->cp15.c14_pmevtyper[counter];
1434     }
1435 
1436     p   = filter & PMXEVTYPER_P;
1437     u   = filter & PMXEVTYPER_U;
1438     nsk = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSK);
1439     nsu = arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_NSU);
1440     nsh = arm_feature(env, ARM_FEATURE_EL2) && (filter & PMXEVTYPER_NSH);
1441     m   = arm_el_is_aa64(env, 1) &&
1442               arm_feature(env, ARM_FEATURE_EL3) && (filter & PMXEVTYPER_M);
1443 
1444     if (el == 0) {
1445         filtered = secure ? u : u != nsu;
1446     } else if (el == 1) {
1447         filtered = secure ? p : p != nsk;
1448     } else if (el == 2) {
1449         filtered = !nsh;
1450     } else { /* EL3 */
1451         filtered = m != p;
1452     }
1453 
1454     if (counter != 31) {
1455         /*
1456          * If not checking PMCCNTR, ensure the counter is setup to an event we
1457          * support
1458          */
1459         uint16_t event = filter & PMXEVTYPER_EVTCOUNT;
1460         if (!event_supported(event)) {
1461             return false;
1462         }
1463     }
1464 
1465     return enabled && !prohibited && !filtered;
1466 }
1467 
1468 static void pmu_update_irq(CPUARMState *env)
1469 {
1470     ARMCPU *cpu = env_archcpu(env);
1471     qemu_set_irq(cpu->pmu_interrupt, (env->cp15.c9_pmcr & PMCRE) &&
1472             (env->cp15.c9_pminten & env->cp15.c9_pmovsr));
1473 }
1474 
1475 /*
1476  * Ensure c15_ccnt is the guest-visible count so that operations such as
1477  * enabling/disabling the counter or filtering, modifying the count itself,
1478  * etc. can be done logically. This is essentially a no-op if the counter is
1479  * not enabled at the time of the call.
1480  */
1481 static void pmccntr_op_start(CPUARMState *env)
1482 {
1483     uint64_t cycles = cycles_get_count(env);
1484 
1485     if (pmu_counter_enabled(env, 31)) {
1486         uint64_t eff_cycles = cycles;
1487         if (env->cp15.c9_pmcr & PMCRD) {
1488             /* Increment once every 64 processor clock cycles */
1489             eff_cycles /= 64;
1490         }
1491 
1492         uint64_t new_pmccntr = eff_cycles - env->cp15.c15_ccnt_delta;
1493 
1494         uint64_t overflow_mask = env->cp15.c9_pmcr & PMCRLC ? \
1495                                  1ull << 63 : 1ull << 31;
1496         if (env->cp15.c15_ccnt & ~new_pmccntr & overflow_mask) {
1497             env->cp15.c9_pmovsr |= (1 << 31);
1498             pmu_update_irq(env);
1499         }
1500 
1501         env->cp15.c15_ccnt = new_pmccntr;
1502     }
1503     env->cp15.c15_ccnt_delta = cycles;
1504 }
1505 
1506 /*
1507  * If PMCCNTR is enabled, recalculate the delta between the clock and the
1508  * guest-visible count. A call to pmccntr_op_finish should follow every call to
1509  * pmccntr_op_start.
1510  */
1511 static void pmccntr_op_finish(CPUARMState *env)
1512 {
1513     if (pmu_counter_enabled(env, 31)) {
1514 #ifndef CONFIG_USER_ONLY
1515         /* Calculate when the counter will next overflow */
1516         uint64_t remaining_cycles = -env->cp15.c15_ccnt;
1517         if (!(env->cp15.c9_pmcr & PMCRLC)) {
1518             remaining_cycles = (uint32_t)remaining_cycles;
1519         }
1520         int64_t overflow_in = cycles_ns_per(remaining_cycles);
1521 
1522         if (overflow_in > 0) {
1523             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1524                 overflow_in;
1525             ARMCPU *cpu = env_archcpu(env);
1526             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1527         }
1528 #endif
1529 
1530         uint64_t prev_cycles = env->cp15.c15_ccnt_delta;
1531         if (env->cp15.c9_pmcr & PMCRD) {
1532             /* Increment once every 64 processor clock cycles */
1533             prev_cycles /= 64;
1534         }
1535         env->cp15.c15_ccnt_delta = prev_cycles - env->cp15.c15_ccnt;
1536     }
1537 }
1538 
1539 static void pmevcntr_op_start(CPUARMState *env, uint8_t counter)
1540 {
1541 
1542     uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1543     uint64_t count = 0;
1544     if (event_supported(event)) {
1545         uint16_t event_idx = supported_event_map[event];
1546         count = pm_events[event_idx].get_count(env);
1547     }
1548 
1549     if (pmu_counter_enabled(env, counter)) {
1550         uint32_t new_pmevcntr = count - env->cp15.c14_pmevcntr_delta[counter];
1551 
1552         if (env->cp15.c14_pmevcntr[counter] & ~new_pmevcntr & INT32_MIN) {
1553             env->cp15.c9_pmovsr |= (1 << counter);
1554             pmu_update_irq(env);
1555         }
1556         env->cp15.c14_pmevcntr[counter] = new_pmevcntr;
1557     }
1558     env->cp15.c14_pmevcntr_delta[counter] = count;
1559 }
1560 
1561 static void pmevcntr_op_finish(CPUARMState *env, uint8_t counter)
1562 {
1563     if (pmu_counter_enabled(env, counter)) {
1564 #ifndef CONFIG_USER_ONLY
1565         uint16_t event = env->cp15.c14_pmevtyper[counter] & PMXEVTYPER_EVTCOUNT;
1566         uint16_t event_idx = supported_event_map[event];
1567         uint64_t delta = UINT32_MAX -
1568             (uint32_t)env->cp15.c14_pmevcntr[counter] + 1;
1569         int64_t overflow_in = pm_events[event_idx].ns_per_count(delta);
1570 
1571         if (overflow_in > 0) {
1572             int64_t overflow_at = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
1573                 overflow_in;
1574             ARMCPU *cpu = env_archcpu(env);
1575             timer_mod_anticipate_ns(cpu->pmu_timer, overflow_at);
1576         }
1577 #endif
1578 
1579         env->cp15.c14_pmevcntr_delta[counter] -=
1580             env->cp15.c14_pmevcntr[counter];
1581     }
1582 }
1583 
1584 void pmu_op_start(CPUARMState *env)
1585 {
1586     unsigned int i;
1587     pmccntr_op_start(env);
1588     for (i = 0; i < pmu_num_counters(env); i++) {
1589         pmevcntr_op_start(env, i);
1590     }
1591 }
1592 
1593 void pmu_op_finish(CPUARMState *env)
1594 {
1595     unsigned int i;
1596     pmccntr_op_finish(env);
1597     for (i = 0; i < pmu_num_counters(env); i++) {
1598         pmevcntr_op_finish(env, i);
1599     }
1600 }
1601 
1602 void pmu_pre_el_change(ARMCPU *cpu, void *ignored)
1603 {
1604     pmu_op_start(&cpu->env);
1605 }
1606 
1607 void pmu_post_el_change(ARMCPU *cpu, void *ignored)
1608 {
1609     pmu_op_finish(&cpu->env);
1610 }
1611 
1612 void arm_pmu_timer_cb(void *opaque)
1613 {
1614     ARMCPU *cpu = opaque;
1615 
1616     /*
1617      * Update all the counter values based on the current underlying counts,
1618      * triggering interrupts to be raised, if necessary. pmu_op_finish() also
1619      * has the effect of setting the cpu->pmu_timer to the next earliest time a
1620      * counter may expire.
1621      */
1622     pmu_op_start(&cpu->env);
1623     pmu_op_finish(&cpu->env);
1624 }
1625 
1626 static void pmcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1627                        uint64_t value)
1628 {
1629     pmu_op_start(env);
1630 
1631     if (value & PMCRC) {
1632         /* The counter has been reset */
1633         env->cp15.c15_ccnt = 0;
1634     }
1635 
1636     if (value & PMCRP) {
1637         unsigned int i;
1638         for (i = 0; i < pmu_num_counters(env); i++) {
1639             env->cp15.c14_pmevcntr[i] = 0;
1640         }
1641     }
1642 
1643     env->cp15.c9_pmcr &= ~PMCR_WRITEABLE_MASK;
1644     env->cp15.c9_pmcr |= (value & PMCR_WRITEABLE_MASK);
1645 
1646     pmu_op_finish(env);
1647 }
1648 
1649 static void pmswinc_write(CPUARMState *env, const ARMCPRegInfo *ri,
1650                           uint64_t value)
1651 {
1652     unsigned int i;
1653     for (i = 0; i < pmu_num_counters(env); i++) {
1654         /* Increment a counter's count iff: */
1655         if ((value & (1 << i)) && /* counter's bit is set */
1656                 /* counter is enabled and not filtered */
1657                 pmu_counter_enabled(env, i) &&
1658                 /* counter is SW_INCR */
1659                 (env->cp15.c14_pmevtyper[i] & PMXEVTYPER_EVTCOUNT) == 0x0) {
1660             pmevcntr_op_start(env, i);
1661 
1662             /*
1663              * Detect if this write causes an overflow since we can't predict
1664              * PMSWINC overflows like we can for other events
1665              */
1666             uint32_t new_pmswinc = env->cp15.c14_pmevcntr[i] + 1;
1667 
1668             if (env->cp15.c14_pmevcntr[i] & ~new_pmswinc & INT32_MIN) {
1669                 env->cp15.c9_pmovsr |= (1 << i);
1670                 pmu_update_irq(env);
1671             }
1672 
1673             env->cp15.c14_pmevcntr[i] = new_pmswinc;
1674 
1675             pmevcntr_op_finish(env, i);
1676         }
1677     }
1678 }
1679 
1680 static uint64_t pmccntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1681 {
1682     uint64_t ret;
1683     pmccntr_op_start(env);
1684     ret = env->cp15.c15_ccnt;
1685     pmccntr_op_finish(env);
1686     return ret;
1687 }
1688 
1689 static void pmselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1690                          uint64_t value)
1691 {
1692     /* The value of PMSELR.SEL affects the behavior of PMXEVTYPER and
1693      * PMXEVCNTR. We allow [0..31] to be written to PMSELR here; in the
1694      * meanwhile, we check PMSELR.SEL when PMXEVTYPER and PMXEVCNTR are
1695      * accessed.
1696      */
1697     env->cp15.c9_pmselr = value & 0x1f;
1698 }
1699 
1700 static void pmccntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1701                         uint64_t value)
1702 {
1703     pmccntr_op_start(env);
1704     env->cp15.c15_ccnt = value;
1705     pmccntr_op_finish(env);
1706 }
1707 
1708 static void pmccntr_write32(CPUARMState *env, const ARMCPRegInfo *ri,
1709                             uint64_t value)
1710 {
1711     uint64_t cur_val = pmccntr_read(env, NULL);
1712 
1713     pmccntr_write(env, ri, deposit64(cur_val, 0, 32, value));
1714 }
1715 
1716 static void pmccfiltr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1717                             uint64_t value)
1718 {
1719     pmccntr_op_start(env);
1720     env->cp15.pmccfiltr_el0 = value & PMCCFILTR_EL0;
1721     pmccntr_op_finish(env);
1722 }
1723 
1724 static void pmccfiltr_write_a32(CPUARMState *env, const ARMCPRegInfo *ri,
1725                             uint64_t value)
1726 {
1727     pmccntr_op_start(env);
1728     /* M is not accessible from AArch32 */
1729     env->cp15.pmccfiltr_el0 = (env->cp15.pmccfiltr_el0 & PMCCFILTR_M) |
1730         (value & PMCCFILTR);
1731     pmccntr_op_finish(env);
1732 }
1733 
1734 static uint64_t pmccfiltr_read_a32(CPUARMState *env, const ARMCPRegInfo *ri)
1735 {
1736     /* M is not visible in AArch32 */
1737     return env->cp15.pmccfiltr_el0 & PMCCFILTR;
1738 }
1739 
1740 static void pmcntenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1741                             uint64_t value)
1742 {
1743     value &= pmu_counter_mask(env);
1744     env->cp15.c9_pmcnten |= value;
1745 }
1746 
1747 static void pmcntenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1748                              uint64_t value)
1749 {
1750     value &= pmu_counter_mask(env);
1751     env->cp15.c9_pmcnten &= ~value;
1752 }
1753 
1754 static void pmovsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1755                          uint64_t value)
1756 {
1757     value &= pmu_counter_mask(env);
1758     env->cp15.c9_pmovsr &= ~value;
1759     pmu_update_irq(env);
1760 }
1761 
1762 static void pmovsset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1763                          uint64_t value)
1764 {
1765     value &= pmu_counter_mask(env);
1766     env->cp15.c9_pmovsr |= value;
1767     pmu_update_irq(env);
1768 }
1769 
1770 static void pmevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1771                              uint64_t value, const uint8_t counter)
1772 {
1773     if (counter == 31) {
1774         pmccfiltr_write(env, ri, value);
1775     } else if (counter < pmu_num_counters(env)) {
1776         pmevcntr_op_start(env, counter);
1777 
1778         /*
1779          * If this counter's event type is changing, store the current
1780          * underlying count for the new type in c14_pmevcntr_delta[counter] so
1781          * pmevcntr_op_finish has the correct baseline when it converts back to
1782          * a delta.
1783          */
1784         uint16_t old_event = env->cp15.c14_pmevtyper[counter] &
1785             PMXEVTYPER_EVTCOUNT;
1786         uint16_t new_event = value & PMXEVTYPER_EVTCOUNT;
1787         if (old_event != new_event) {
1788             uint64_t count = 0;
1789             if (event_supported(new_event)) {
1790                 uint16_t event_idx = supported_event_map[new_event];
1791                 count = pm_events[event_idx].get_count(env);
1792             }
1793             env->cp15.c14_pmevcntr_delta[counter] = count;
1794         }
1795 
1796         env->cp15.c14_pmevtyper[counter] = value & PMXEVTYPER_MASK;
1797         pmevcntr_op_finish(env, counter);
1798     }
1799     /* Attempts to access PMXEVTYPER are CONSTRAINED UNPREDICTABLE when
1800      * PMSELR value is equal to or greater than the number of implemented
1801      * counters, but not equal to 0x1f. We opt to behave as a RAZ/WI.
1802      */
1803 }
1804 
1805 static uint64_t pmevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri,
1806                                const uint8_t counter)
1807 {
1808     if (counter == 31) {
1809         return env->cp15.pmccfiltr_el0;
1810     } else if (counter < pmu_num_counters(env)) {
1811         return env->cp15.c14_pmevtyper[counter];
1812     } else {
1813       /*
1814        * We opt to behave as a RAZ/WI when attempts to access PMXEVTYPER
1815        * are CONSTRAINED UNPREDICTABLE. See comments in pmevtyper_write().
1816        */
1817         return 0;
1818     }
1819 }
1820 
1821 static void pmevtyper_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1822                               uint64_t value)
1823 {
1824     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1825     pmevtyper_write(env, ri, value, counter);
1826 }
1827 
1828 static void pmevtyper_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1829                                uint64_t value)
1830 {
1831     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1832     env->cp15.c14_pmevtyper[counter] = value;
1833 
1834     /*
1835      * pmevtyper_rawwrite is called between a pair of pmu_op_start and
1836      * pmu_op_finish calls when loading saved state for a migration. Because
1837      * we're potentially updating the type of event here, the value written to
1838      * c14_pmevcntr_delta by the preceeding pmu_op_start call may be for a
1839      * different counter type. Therefore, we need to set this value to the
1840      * current count for the counter type we're writing so that pmu_op_finish
1841      * has the correct count for its calculation.
1842      */
1843     uint16_t event = value & PMXEVTYPER_EVTCOUNT;
1844     if (event_supported(event)) {
1845         uint16_t event_idx = supported_event_map[event];
1846         env->cp15.c14_pmevcntr_delta[counter] =
1847             pm_events[event_idx].get_count(env);
1848     }
1849 }
1850 
1851 static uint64_t pmevtyper_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1852 {
1853     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1854     return pmevtyper_read(env, ri, counter);
1855 }
1856 
1857 static void pmxevtyper_write(CPUARMState *env, const ARMCPRegInfo *ri,
1858                              uint64_t value)
1859 {
1860     pmevtyper_write(env, ri, value, env->cp15.c9_pmselr & 31);
1861 }
1862 
1863 static uint64_t pmxevtyper_read(CPUARMState *env, const ARMCPRegInfo *ri)
1864 {
1865     return pmevtyper_read(env, ri, env->cp15.c9_pmselr & 31);
1866 }
1867 
1868 static void pmevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1869                              uint64_t value, uint8_t counter)
1870 {
1871     if (counter < pmu_num_counters(env)) {
1872         pmevcntr_op_start(env, counter);
1873         env->cp15.c14_pmevcntr[counter] = value;
1874         pmevcntr_op_finish(env, counter);
1875     }
1876     /*
1877      * We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1878      * are CONSTRAINED UNPREDICTABLE.
1879      */
1880 }
1881 
1882 static uint64_t pmevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri,
1883                               uint8_t counter)
1884 {
1885     if (counter < pmu_num_counters(env)) {
1886         uint64_t ret;
1887         pmevcntr_op_start(env, counter);
1888         ret = env->cp15.c14_pmevcntr[counter];
1889         pmevcntr_op_finish(env, counter);
1890         return ret;
1891     } else {
1892       /* We opt to behave as a RAZ/WI when attempts to access PM[X]EVCNTR
1893        * are CONSTRAINED UNPREDICTABLE. */
1894         return 0;
1895     }
1896 }
1897 
1898 static void pmevcntr_writefn(CPUARMState *env, const ARMCPRegInfo *ri,
1899                              uint64_t value)
1900 {
1901     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1902     pmevcntr_write(env, ri, value, counter);
1903 }
1904 
1905 static uint64_t pmevcntr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
1906 {
1907     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1908     return pmevcntr_read(env, ri, counter);
1909 }
1910 
1911 static void pmevcntr_rawwrite(CPUARMState *env, const ARMCPRegInfo *ri,
1912                              uint64_t value)
1913 {
1914     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1915     assert(counter < pmu_num_counters(env));
1916     env->cp15.c14_pmevcntr[counter] = value;
1917     pmevcntr_write(env, ri, value, counter);
1918 }
1919 
1920 static uint64_t pmevcntr_rawread(CPUARMState *env, const ARMCPRegInfo *ri)
1921 {
1922     uint8_t counter = ((ri->crm & 3) << 3) | (ri->opc2 & 7);
1923     assert(counter < pmu_num_counters(env));
1924     return env->cp15.c14_pmevcntr[counter];
1925 }
1926 
1927 static void pmxevcntr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1928                              uint64_t value)
1929 {
1930     pmevcntr_write(env, ri, value, env->cp15.c9_pmselr & 31);
1931 }
1932 
1933 static uint64_t pmxevcntr_read(CPUARMState *env, const ARMCPRegInfo *ri)
1934 {
1935     return pmevcntr_read(env, ri, env->cp15.c9_pmselr & 31);
1936 }
1937 
1938 static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1939                             uint64_t value)
1940 {
1941     if (arm_feature(env, ARM_FEATURE_V8)) {
1942         env->cp15.c9_pmuserenr = value & 0xf;
1943     } else {
1944         env->cp15.c9_pmuserenr = value & 1;
1945     }
1946 }
1947 
1948 static void pmintenset_write(CPUARMState *env, const ARMCPRegInfo *ri,
1949                              uint64_t value)
1950 {
1951     /* We have no event counters so only the C bit can be changed */
1952     value &= pmu_counter_mask(env);
1953     env->cp15.c9_pminten |= value;
1954     pmu_update_irq(env);
1955 }
1956 
1957 static void pmintenclr_write(CPUARMState *env, const ARMCPRegInfo *ri,
1958                              uint64_t value)
1959 {
1960     value &= pmu_counter_mask(env);
1961     env->cp15.c9_pminten &= ~value;
1962     pmu_update_irq(env);
1963 }
1964 
1965 static void vbar_write(CPUARMState *env, const ARMCPRegInfo *ri,
1966                        uint64_t value)
1967 {
1968     /* Note that even though the AArch64 view of this register has bits
1969      * [10:0] all RES0 we can only mask the bottom 5, to comply with the
1970      * architectural requirements for bits which are RES0 only in some
1971      * contexts. (ARMv8 would permit us to do no masking at all, but ARMv7
1972      * requires the bottom five bits to be RAZ/WI because they're UNK/SBZP.)
1973      */
1974     raw_write(env, ri, value & ~0x1FULL);
1975 }
1976 
1977 static void scr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
1978 {
1979     /* Begin with base v8.0 state.  */
1980     uint32_t valid_mask = 0x3fff;
1981     ARMCPU *cpu = env_archcpu(env);
1982 
1983     if (ri->state == ARM_CP_STATE_AA64) {
1984         if (arm_feature(env, ARM_FEATURE_AARCH64) &&
1985             !cpu_isar_feature(aa64_aa32_el1, cpu)) {
1986                 value |= SCR_FW | SCR_AW;   /* these two bits are RES1.  */
1987         }
1988         valid_mask &= ~SCR_NET;
1989 
1990         if (cpu_isar_feature(aa64_lor, cpu)) {
1991             valid_mask |= SCR_TLOR;
1992         }
1993         if (cpu_isar_feature(aa64_pauth, cpu)) {
1994             valid_mask |= SCR_API | SCR_APK;
1995         }
1996         if (cpu_isar_feature(aa64_sel2, cpu)) {
1997             valid_mask |= SCR_EEL2;
1998         }
1999         if (cpu_isar_feature(aa64_mte, cpu)) {
2000             valid_mask |= SCR_ATA;
2001         }
2002     } else {
2003         valid_mask &= ~(SCR_RW | SCR_ST);
2004     }
2005 
2006     if (!arm_feature(env, ARM_FEATURE_EL2)) {
2007         valid_mask &= ~SCR_HCE;
2008 
2009         /* On ARMv7, SMD (or SCD as it is called in v7) is only
2010          * supported if EL2 exists. The bit is UNK/SBZP when
2011          * EL2 is unavailable. In QEMU ARMv7, we force it to always zero
2012          * when EL2 is unavailable.
2013          * On ARMv8, this bit is always available.
2014          */
2015         if (arm_feature(env, ARM_FEATURE_V7) &&
2016             !arm_feature(env, ARM_FEATURE_V8)) {
2017             valid_mask &= ~SCR_SMD;
2018         }
2019     }
2020 
2021     /* Clear all-context RES0 bits.  */
2022     value &= valid_mask;
2023     raw_write(env, ri, value);
2024 }
2025 
2026 static void scr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2027 {
2028     /*
2029      * scr_write will set the RES1 bits on an AArch64-only CPU.
2030      * The reset value will be 0x30 on an AArch64-only CPU and 0 otherwise.
2031      */
2032     scr_write(env, ri, 0);
2033 }
2034 
2035 static CPAccessResult access_aa64_tid2(CPUARMState *env,
2036                                        const ARMCPRegInfo *ri,
2037                                        bool isread)
2038 {
2039     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID2)) {
2040         return CP_ACCESS_TRAP_EL2;
2041     }
2042 
2043     return CP_ACCESS_OK;
2044 }
2045 
2046 static uint64_t ccsidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2047 {
2048     ARMCPU *cpu = env_archcpu(env);
2049 
2050     /* Acquire the CSSELR index from the bank corresponding to the CCSIDR
2051      * bank
2052      */
2053     uint32_t index = A32_BANKED_REG_GET(env, csselr,
2054                                         ri->secure & ARM_CP_SECSTATE_S);
2055 
2056     return cpu->ccsidr[index];
2057 }
2058 
2059 static void csselr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2060                          uint64_t value)
2061 {
2062     raw_write(env, ri, value & 0xf);
2063 }
2064 
2065 static uint64_t isr_read(CPUARMState *env, const ARMCPRegInfo *ri)
2066 {
2067     CPUState *cs = env_cpu(env);
2068     bool el1 = arm_current_el(env) == 1;
2069     uint64_t hcr_el2 = el1 ? arm_hcr_el2_eff(env) : 0;
2070     uint64_t ret = 0;
2071 
2072     if (hcr_el2 & HCR_IMO) {
2073         if (cs->interrupt_request & CPU_INTERRUPT_VIRQ) {
2074             ret |= CPSR_I;
2075         }
2076     } else {
2077         if (cs->interrupt_request & CPU_INTERRUPT_HARD) {
2078             ret |= CPSR_I;
2079         }
2080     }
2081 
2082     if (hcr_el2 & HCR_FMO) {
2083         if (cs->interrupt_request & CPU_INTERRUPT_VFIQ) {
2084             ret |= CPSR_F;
2085         }
2086     } else {
2087         if (cs->interrupt_request & CPU_INTERRUPT_FIQ) {
2088             ret |= CPSR_F;
2089         }
2090     }
2091 
2092     /* External aborts are not possible in QEMU so A bit is always clear */
2093     return ret;
2094 }
2095 
2096 static CPAccessResult access_aa64_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2097                                        bool isread)
2098 {
2099     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID1)) {
2100         return CP_ACCESS_TRAP_EL2;
2101     }
2102 
2103     return CP_ACCESS_OK;
2104 }
2105 
2106 static CPAccessResult access_aa32_tid1(CPUARMState *env, const ARMCPRegInfo *ri,
2107                                        bool isread)
2108 {
2109     if (arm_feature(env, ARM_FEATURE_V8)) {
2110         return access_aa64_tid1(env, ri, isread);
2111     }
2112 
2113     return CP_ACCESS_OK;
2114 }
2115 
2116 static const ARMCPRegInfo v7_cp_reginfo[] = {
2117     /* the old v6 WFI, UNPREDICTABLE in v7 but we choose to NOP */
2118     { .name = "NOP", .cp = 15, .crn = 7, .crm = 0, .opc1 = 0, .opc2 = 4,
2119       .access = PL1_W, .type = ARM_CP_NOP },
2120     /* Performance monitors are implementation defined in v7,
2121      * but with an ARM recommended set of registers, which we
2122      * follow.
2123      *
2124      * Performance registers fall into three categories:
2125      *  (a) always UNDEF in PL0, RW in PL1 (PMINTENSET, PMINTENCLR)
2126      *  (b) RO in PL0 (ie UNDEF on write), RW in PL1 (PMUSERENR)
2127      *  (c) UNDEF in PL0 if PMUSERENR.EN==0, otherwise accessible (all others)
2128      * For the cases controlled by PMUSERENR we must set .access to PL0_RW
2129      * or PL0_RO as appropriate and then check PMUSERENR in the helper fn.
2130      */
2131     { .name = "PMCNTENSET", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 1,
2132       .access = PL0_RW, .type = ARM_CP_ALIAS,
2133       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2134       .writefn = pmcntenset_write,
2135       .accessfn = pmreg_access,
2136       .raw_writefn = raw_write },
2137     { .name = "PMCNTENSET_EL0", .state = ARM_CP_STATE_AA64,
2138       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 1,
2139       .access = PL0_RW, .accessfn = pmreg_access,
2140       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten), .resetvalue = 0,
2141       .writefn = pmcntenset_write, .raw_writefn = raw_write },
2142     { .name = "PMCNTENCLR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 2,
2143       .access = PL0_RW,
2144       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcnten),
2145       .accessfn = pmreg_access,
2146       .writefn = pmcntenclr_write,
2147       .type = ARM_CP_ALIAS },
2148     { .name = "PMCNTENCLR_EL0", .state = ARM_CP_STATE_AA64,
2149       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 2,
2150       .access = PL0_RW, .accessfn = pmreg_access,
2151       .type = ARM_CP_ALIAS,
2152       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcnten),
2153       .writefn = pmcntenclr_write },
2154     { .name = "PMOVSR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 3,
2155       .access = PL0_RW, .type = ARM_CP_IO,
2156       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2157       .accessfn = pmreg_access,
2158       .writefn = pmovsr_write,
2159       .raw_writefn = raw_write },
2160     { .name = "PMOVSCLR_EL0", .state = ARM_CP_STATE_AA64,
2161       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 3,
2162       .access = PL0_RW, .accessfn = pmreg_access,
2163       .type = ARM_CP_ALIAS | ARM_CP_IO,
2164       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2165       .writefn = pmovsr_write,
2166       .raw_writefn = raw_write },
2167     { .name = "PMSWINC", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 4,
2168       .access = PL0_W, .accessfn = pmreg_access_swinc,
2169       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2170       .writefn = pmswinc_write },
2171     { .name = "PMSWINC_EL0", .state = ARM_CP_STATE_AA64,
2172       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 4,
2173       .access = PL0_W, .accessfn = pmreg_access_swinc,
2174       .type = ARM_CP_NO_RAW | ARM_CP_IO,
2175       .writefn = pmswinc_write },
2176     { .name = "PMSELR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 5,
2177       .access = PL0_RW, .type = ARM_CP_ALIAS,
2178       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmselr),
2179       .accessfn = pmreg_access_selr, .writefn = pmselr_write,
2180       .raw_writefn = raw_write},
2181     { .name = "PMSELR_EL0", .state = ARM_CP_STATE_AA64,
2182       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 5,
2183       .access = PL0_RW, .accessfn = pmreg_access_selr,
2184       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmselr),
2185       .writefn = pmselr_write, .raw_writefn = raw_write, },
2186     { .name = "PMCCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 0,
2187       .access = PL0_RW, .resetvalue = 0, .type = ARM_CP_ALIAS | ARM_CP_IO,
2188       .readfn = pmccntr_read, .writefn = pmccntr_write32,
2189       .accessfn = pmreg_access_ccntr },
2190     { .name = "PMCCNTR_EL0", .state = ARM_CP_STATE_AA64,
2191       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 0,
2192       .access = PL0_RW, .accessfn = pmreg_access_ccntr,
2193       .type = ARM_CP_IO,
2194       .fieldoffset = offsetof(CPUARMState, cp15.c15_ccnt),
2195       .readfn = pmccntr_read, .writefn = pmccntr_write,
2196       .raw_readfn = raw_read, .raw_writefn = raw_write, },
2197     { .name = "PMCCFILTR", .cp = 15, .opc1 = 0, .crn = 14, .crm = 15, .opc2 = 7,
2198       .writefn = pmccfiltr_write_a32, .readfn = pmccfiltr_read_a32,
2199       .access = PL0_RW, .accessfn = pmreg_access,
2200       .type = ARM_CP_ALIAS | ARM_CP_IO,
2201       .resetvalue = 0, },
2202     { .name = "PMCCFILTR_EL0", .state = ARM_CP_STATE_AA64,
2203       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 15, .opc2 = 7,
2204       .writefn = pmccfiltr_write, .raw_writefn = raw_write,
2205       .access = PL0_RW, .accessfn = pmreg_access,
2206       .type = ARM_CP_IO,
2207       .fieldoffset = offsetof(CPUARMState, cp15.pmccfiltr_el0),
2208       .resetvalue = 0, },
2209     { .name = "PMXEVTYPER", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 1,
2210       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2211       .accessfn = pmreg_access,
2212       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2213     { .name = "PMXEVTYPER_EL0", .state = ARM_CP_STATE_AA64,
2214       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 1,
2215       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2216       .accessfn = pmreg_access,
2217       .writefn = pmxevtyper_write, .readfn = pmxevtyper_read },
2218     { .name = "PMXEVCNTR", .cp = 15, .crn = 9, .crm = 13, .opc1 = 0, .opc2 = 2,
2219       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2220       .accessfn = pmreg_access_xevcntr,
2221       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2222     { .name = "PMXEVCNTR_EL0", .state = ARM_CP_STATE_AA64,
2223       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 13, .opc2 = 2,
2224       .access = PL0_RW, .type = ARM_CP_NO_RAW | ARM_CP_IO,
2225       .accessfn = pmreg_access_xevcntr,
2226       .writefn = pmxevcntr_write, .readfn = pmxevcntr_read },
2227     { .name = "PMUSERENR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 0,
2228       .access = PL0_R | PL1_RW, .accessfn = access_tpm,
2229       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmuserenr),
2230       .resetvalue = 0,
2231       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2232     { .name = "PMUSERENR_EL0", .state = ARM_CP_STATE_AA64,
2233       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 0,
2234       .access = PL0_R | PL1_RW, .accessfn = access_tpm, .type = ARM_CP_ALIAS,
2235       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmuserenr),
2236       .resetvalue = 0,
2237       .writefn = pmuserenr_write, .raw_writefn = raw_write },
2238     { .name = "PMINTENSET", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 1,
2239       .access = PL1_RW, .accessfn = access_tpm,
2240       .type = ARM_CP_ALIAS | ARM_CP_IO,
2241       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pminten),
2242       .resetvalue = 0,
2243       .writefn = pmintenset_write, .raw_writefn = raw_write },
2244     { .name = "PMINTENSET_EL1", .state = ARM_CP_STATE_AA64,
2245       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 1,
2246       .access = PL1_RW, .accessfn = access_tpm,
2247       .type = ARM_CP_IO,
2248       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2249       .writefn = pmintenset_write, .raw_writefn = raw_write,
2250       .resetvalue = 0x0 },
2251     { .name = "PMINTENCLR", .cp = 15, .crn = 9, .crm = 14, .opc1 = 0, .opc2 = 2,
2252       .access = PL1_RW, .accessfn = access_tpm,
2253       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2254       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2255       .writefn = pmintenclr_write, },
2256     { .name = "PMINTENCLR_EL1", .state = ARM_CP_STATE_AA64,
2257       .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 2,
2258       .access = PL1_RW, .accessfn = access_tpm,
2259       .type = ARM_CP_ALIAS | ARM_CP_IO | ARM_CP_NO_RAW,
2260       .fieldoffset = offsetof(CPUARMState, cp15.c9_pminten),
2261       .writefn = pmintenclr_write },
2262     { .name = "CCSIDR", .state = ARM_CP_STATE_BOTH,
2263       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 0,
2264       .access = PL1_R,
2265       .accessfn = access_aa64_tid2,
2266       .readfn = ccsidr_read, .type = ARM_CP_NO_RAW },
2267     { .name = "CSSELR", .state = ARM_CP_STATE_BOTH,
2268       .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 2, .opc2 = 0,
2269       .access = PL1_RW,
2270       .accessfn = access_aa64_tid2,
2271       .writefn = csselr_write, .resetvalue = 0,
2272       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.csselr_s),
2273                              offsetof(CPUARMState, cp15.csselr_ns) } },
2274     /* Auxiliary ID register: this actually has an IMPDEF value but for now
2275      * just RAZ for all cores:
2276      */
2277     { .name = "AIDR", .state = ARM_CP_STATE_BOTH,
2278       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 7,
2279       .access = PL1_R, .type = ARM_CP_CONST,
2280       .accessfn = access_aa64_tid1,
2281       .resetvalue = 0 },
2282     /* Auxiliary fault status registers: these also are IMPDEF, and we
2283      * choose to RAZ/WI for all cores.
2284      */
2285     { .name = "AFSR0_EL1", .state = ARM_CP_STATE_BOTH,
2286       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 0,
2287       .access = PL1_RW, .accessfn = access_tvm_trvm,
2288       .type = ARM_CP_CONST, .resetvalue = 0 },
2289     { .name = "AFSR1_EL1", .state = ARM_CP_STATE_BOTH,
2290       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 1, .opc2 = 1,
2291       .access = PL1_RW, .accessfn = access_tvm_trvm,
2292       .type = ARM_CP_CONST, .resetvalue = 0 },
2293     /* MAIR can just read-as-written because we don't implement caches
2294      * and so don't need to care about memory attributes.
2295      */
2296     { .name = "MAIR_EL1", .state = ARM_CP_STATE_AA64,
2297       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2298       .access = PL1_RW, .accessfn = access_tvm_trvm,
2299       .fieldoffset = offsetof(CPUARMState, cp15.mair_el[1]),
2300       .resetvalue = 0 },
2301     { .name = "MAIR_EL3", .state = ARM_CP_STATE_AA64,
2302       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 2, .opc2 = 0,
2303       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[3]),
2304       .resetvalue = 0 },
2305     /* For non-long-descriptor page tables these are PRRR and NMRR;
2306      * regardless they still act as reads-as-written for QEMU.
2307      */
2308      /* MAIR0/1 are defined separately from their 64-bit counterpart which
2309       * allows them to assign the correct fieldoffset based on the endianness
2310       * handled in the field definitions.
2311       */
2312     { .name = "MAIR0", .state = ARM_CP_STATE_AA32,
2313       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 0,
2314       .access = PL1_RW, .accessfn = access_tvm_trvm,
2315       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair0_s),
2316                              offsetof(CPUARMState, cp15.mair0_ns) },
2317       .resetfn = arm_cp_reset_ignore },
2318     { .name = "MAIR1", .state = ARM_CP_STATE_AA32,
2319       .cp = 15, .opc1 = 0, .crn = 10, .crm = 2, .opc2 = 1,
2320       .access = PL1_RW, .accessfn = access_tvm_trvm,
2321       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.mair1_s),
2322                              offsetof(CPUARMState, cp15.mair1_ns) },
2323       .resetfn = arm_cp_reset_ignore },
2324     { .name = "ISR_EL1", .state = ARM_CP_STATE_BOTH,
2325       .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 1, .opc2 = 0,
2326       .type = ARM_CP_NO_RAW, .access = PL1_R, .readfn = isr_read },
2327     /* 32 bit ITLB invalidates */
2328     { .name = "ITLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 0,
2329       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2330       .writefn = tlbiall_write },
2331     { .name = "ITLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
2332       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2333       .writefn = tlbimva_write },
2334     { .name = "ITLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 2,
2335       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2336       .writefn = tlbiasid_write },
2337     /* 32 bit DTLB invalidates */
2338     { .name = "DTLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 0,
2339       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2340       .writefn = tlbiall_write },
2341     { .name = "DTLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
2342       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2343       .writefn = tlbimva_write },
2344     { .name = "DTLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 2,
2345       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2346       .writefn = tlbiasid_write },
2347     /* 32 bit TLB invalidates */
2348     { .name = "TLBIALL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
2349       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2350       .writefn = tlbiall_write },
2351     { .name = "TLBIMVA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
2352       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2353       .writefn = tlbimva_write },
2354     { .name = "TLBIASID", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
2355       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2356       .writefn = tlbiasid_write },
2357     { .name = "TLBIMVAA", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
2358       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2359       .writefn = tlbimvaa_write },
2360     REGINFO_SENTINEL
2361 };
2362 
2363 static const ARMCPRegInfo v7mp_cp_reginfo[] = {
2364     /* 32 bit TLB invalidates, Inner Shareable */
2365     { .name = "TLBIALLIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
2366       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2367       .writefn = tlbiall_is_write },
2368     { .name = "TLBIMVAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
2369       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2370       .writefn = tlbimva_is_write },
2371     { .name = "TLBIASIDIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
2372       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2373       .writefn = tlbiasid_is_write },
2374     { .name = "TLBIMVAAIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
2375       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
2376       .writefn = tlbimvaa_is_write },
2377     REGINFO_SENTINEL
2378 };
2379 
2380 static const ARMCPRegInfo pmovsset_cp_reginfo[] = {
2381     /* PMOVSSET is not implemented in v7 before v7ve */
2382     { .name = "PMOVSSET", .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 3,
2383       .access = PL0_RW, .accessfn = pmreg_access,
2384       .type = ARM_CP_ALIAS | ARM_CP_IO,
2385       .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmovsr),
2386       .writefn = pmovsset_write,
2387       .raw_writefn = raw_write },
2388     { .name = "PMOVSSET_EL0", .state = ARM_CP_STATE_AA64,
2389       .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 14, .opc2 = 3,
2390       .access = PL0_RW, .accessfn = pmreg_access,
2391       .type = ARM_CP_ALIAS | ARM_CP_IO,
2392       .fieldoffset = offsetof(CPUARMState, cp15.c9_pmovsr),
2393       .writefn = pmovsset_write,
2394       .raw_writefn = raw_write },
2395     REGINFO_SENTINEL
2396 };
2397 
2398 static void teecr_write(CPUARMState *env, const ARMCPRegInfo *ri,
2399                         uint64_t value)
2400 {
2401     value &= 1;
2402     env->teecr = value;
2403 }
2404 
2405 static CPAccessResult teecr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2406                                    bool isread)
2407 {
2408     /*
2409      * HSTR.TTEE only exists in v7A, not v8A, but v8A doesn't have T2EE
2410      * at all, so we don't need to check whether we're v8A.
2411      */
2412     if (arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
2413         (env->cp15.hstr_el2 & HSTR_TTEE)) {
2414         return CP_ACCESS_TRAP_EL2;
2415     }
2416     return CP_ACCESS_OK;
2417 }
2418 
2419 static CPAccessResult teehbr_access(CPUARMState *env, const ARMCPRegInfo *ri,
2420                                     bool isread)
2421 {
2422     if (arm_current_el(env) == 0 && (env->teecr & 1)) {
2423         return CP_ACCESS_TRAP;
2424     }
2425     return teecr_access(env, ri, isread);
2426 }
2427 
2428 static const ARMCPRegInfo t2ee_cp_reginfo[] = {
2429     { .name = "TEECR", .cp = 14, .crn = 0, .crm = 0, .opc1 = 6, .opc2 = 0,
2430       .access = PL1_RW, .fieldoffset = offsetof(CPUARMState, teecr),
2431       .resetvalue = 0,
2432       .writefn = teecr_write, .accessfn = teecr_access },
2433     { .name = "TEEHBR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 6, .opc2 = 0,
2434       .access = PL0_RW, .fieldoffset = offsetof(CPUARMState, teehbr),
2435       .accessfn = teehbr_access, .resetvalue = 0 },
2436     REGINFO_SENTINEL
2437 };
2438 
2439 static const ARMCPRegInfo v6k_cp_reginfo[] = {
2440     { .name = "TPIDR_EL0", .state = ARM_CP_STATE_AA64,
2441       .opc0 = 3, .opc1 = 3, .opc2 = 2, .crn = 13, .crm = 0,
2442       .access = PL0_RW,
2443       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[0]), .resetvalue = 0 },
2444     { .name = "TPIDRURW", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 2,
2445       .access = PL0_RW,
2446       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrurw_s),
2447                              offsetoflow32(CPUARMState, cp15.tpidrurw_ns) },
2448       .resetfn = arm_cp_reset_ignore },
2449     { .name = "TPIDRRO_EL0", .state = ARM_CP_STATE_AA64,
2450       .opc0 = 3, .opc1 = 3, .opc2 = 3, .crn = 13, .crm = 0,
2451       .access = PL0_R|PL1_W,
2452       .fieldoffset = offsetof(CPUARMState, cp15.tpidrro_el[0]),
2453       .resetvalue = 0},
2454     { .name = "TPIDRURO", .cp = 15, .crn = 13, .crm = 0, .opc1 = 0, .opc2 = 3,
2455       .access = PL0_R|PL1_W,
2456       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidruro_s),
2457                              offsetoflow32(CPUARMState, cp15.tpidruro_ns) },
2458       .resetfn = arm_cp_reset_ignore },
2459     { .name = "TPIDR_EL1", .state = ARM_CP_STATE_AA64,
2460       .opc0 = 3, .opc1 = 0, .opc2 = 4, .crn = 13, .crm = 0,
2461       .access = PL1_RW,
2462       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[1]), .resetvalue = 0 },
2463     { .name = "TPIDRPRW", .opc1 = 0, .cp = 15, .crn = 13, .crm = 0, .opc2 = 4,
2464       .access = PL1_RW,
2465       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.tpidrprw_s),
2466                              offsetoflow32(CPUARMState, cp15.tpidrprw_ns) },
2467       .resetvalue = 0 },
2468     REGINFO_SENTINEL
2469 };
2470 
2471 #ifndef CONFIG_USER_ONLY
2472 
2473 static CPAccessResult gt_cntfrq_access(CPUARMState *env, const ARMCPRegInfo *ri,
2474                                        bool isread)
2475 {
2476     /* CNTFRQ: not visible from PL0 if both PL0PCTEN and PL0VCTEN are zero.
2477      * Writable only at the highest implemented exception level.
2478      */
2479     int el = arm_current_el(env);
2480     uint64_t hcr;
2481     uint32_t cntkctl;
2482 
2483     switch (el) {
2484     case 0:
2485         hcr = arm_hcr_el2_eff(env);
2486         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2487             cntkctl = env->cp15.cnthctl_el2;
2488         } else {
2489             cntkctl = env->cp15.c14_cntkctl;
2490         }
2491         if (!extract32(cntkctl, 0, 2)) {
2492             return CP_ACCESS_TRAP;
2493         }
2494         break;
2495     case 1:
2496         if (!isread && ri->state == ARM_CP_STATE_AA32 &&
2497             arm_is_secure_below_el3(env)) {
2498             /* Accesses from 32-bit Secure EL1 UNDEF (*not* trap to EL3!) */
2499             return CP_ACCESS_TRAP_UNCATEGORIZED;
2500         }
2501         break;
2502     case 2:
2503     case 3:
2504         break;
2505     }
2506 
2507     if (!isread && el < arm_highest_el(env)) {
2508         return CP_ACCESS_TRAP_UNCATEGORIZED;
2509     }
2510 
2511     return CP_ACCESS_OK;
2512 }
2513 
2514 static CPAccessResult gt_counter_access(CPUARMState *env, int timeridx,
2515                                         bool isread)
2516 {
2517     unsigned int cur_el = arm_current_el(env);
2518     bool has_el2 = arm_is_el2_enabled(env);
2519     uint64_t hcr = arm_hcr_el2_eff(env);
2520 
2521     switch (cur_el) {
2522     case 0:
2523         /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]CTEN. */
2524         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2525             return (extract32(env->cp15.cnthctl_el2, timeridx, 1)
2526                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2527         }
2528 
2529         /* CNT[PV]CT: not visible from PL0 if EL0[PV]CTEN is zero */
2530         if (!extract32(env->cp15.c14_cntkctl, timeridx, 1)) {
2531             return CP_ACCESS_TRAP;
2532         }
2533 
2534         /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PCTEN. */
2535         if (hcr & HCR_E2H) {
2536             if (timeridx == GTIMER_PHYS &&
2537                 !extract32(env->cp15.cnthctl_el2, 10, 1)) {
2538                 return CP_ACCESS_TRAP_EL2;
2539             }
2540         } else {
2541             /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2542             if (has_el2 && timeridx == GTIMER_PHYS &&
2543                 !extract32(env->cp15.cnthctl_el2, 1, 1)) {
2544                 return CP_ACCESS_TRAP_EL2;
2545             }
2546         }
2547         break;
2548 
2549     case 1:
2550         /* Check CNTHCTL_EL2.EL1PCTEN, which changes location based on E2H. */
2551         if (has_el2 && timeridx == GTIMER_PHYS &&
2552             (hcr & HCR_E2H
2553              ? !extract32(env->cp15.cnthctl_el2, 10, 1)
2554              : !extract32(env->cp15.cnthctl_el2, 0, 1))) {
2555             return CP_ACCESS_TRAP_EL2;
2556         }
2557         break;
2558     }
2559     return CP_ACCESS_OK;
2560 }
2561 
2562 static CPAccessResult gt_timer_access(CPUARMState *env, int timeridx,
2563                                       bool isread)
2564 {
2565     unsigned int cur_el = arm_current_el(env);
2566     bool has_el2 = arm_is_el2_enabled(env);
2567     uint64_t hcr = arm_hcr_el2_eff(env);
2568 
2569     switch (cur_el) {
2570     case 0:
2571         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2572             /* If HCR_EL2.<E2H,TGE> == '11': check CNTHCTL_EL2.EL0[PV]TEN. */
2573             return (extract32(env->cp15.cnthctl_el2, 9 - timeridx, 1)
2574                     ? CP_ACCESS_OK : CP_ACCESS_TRAP_EL2);
2575         }
2576 
2577         /*
2578          * CNT[PV]_CVAL, CNT[PV]_CTL, CNT[PV]_TVAL: not visible from
2579          * EL0 if EL0[PV]TEN is zero.
2580          */
2581         if (!extract32(env->cp15.c14_cntkctl, 9 - timeridx, 1)) {
2582             return CP_ACCESS_TRAP;
2583         }
2584         /* fall through */
2585 
2586     case 1:
2587         if (has_el2 && timeridx == GTIMER_PHYS) {
2588             if (hcr & HCR_E2H) {
2589                 /* If HCR_EL2.<E2H,TGE> == '10': check CNTHCTL_EL2.EL1PTEN. */
2590                 if (!extract32(env->cp15.cnthctl_el2, 11, 1)) {
2591                     return CP_ACCESS_TRAP_EL2;
2592                 }
2593             } else {
2594                 /* If HCR_EL2.<E2H> == 0: check CNTHCTL_EL2.EL1PCEN. */
2595                 if (!extract32(env->cp15.cnthctl_el2, 1, 1)) {
2596                     return CP_ACCESS_TRAP_EL2;
2597                 }
2598             }
2599         }
2600         break;
2601     }
2602     return CP_ACCESS_OK;
2603 }
2604 
2605 static CPAccessResult gt_pct_access(CPUARMState *env,
2606                                     const ARMCPRegInfo *ri,
2607                                     bool isread)
2608 {
2609     return gt_counter_access(env, GTIMER_PHYS, isread);
2610 }
2611 
2612 static CPAccessResult gt_vct_access(CPUARMState *env,
2613                                     const ARMCPRegInfo *ri,
2614                                     bool isread)
2615 {
2616     return gt_counter_access(env, GTIMER_VIRT, isread);
2617 }
2618 
2619 static CPAccessResult gt_ptimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2620                                        bool isread)
2621 {
2622     return gt_timer_access(env, GTIMER_PHYS, isread);
2623 }
2624 
2625 static CPAccessResult gt_vtimer_access(CPUARMState *env, const ARMCPRegInfo *ri,
2626                                        bool isread)
2627 {
2628     return gt_timer_access(env, GTIMER_VIRT, isread);
2629 }
2630 
2631 static CPAccessResult gt_stimer_access(CPUARMState *env,
2632                                        const ARMCPRegInfo *ri,
2633                                        bool isread)
2634 {
2635     /* The AArch64 register view of the secure physical timer is
2636      * always accessible from EL3, and configurably accessible from
2637      * Secure EL1.
2638      */
2639     switch (arm_current_el(env)) {
2640     case 1:
2641         if (!arm_is_secure(env)) {
2642             return CP_ACCESS_TRAP;
2643         }
2644         if (!(env->cp15.scr_el3 & SCR_ST)) {
2645             return CP_ACCESS_TRAP_EL3;
2646         }
2647         return CP_ACCESS_OK;
2648     case 0:
2649     case 2:
2650         return CP_ACCESS_TRAP;
2651     case 3:
2652         return CP_ACCESS_OK;
2653     default:
2654         g_assert_not_reached();
2655     }
2656 }
2657 
2658 static uint64_t gt_get_countervalue(CPUARMState *env)
2659 {
2660     ARMCPU *cpu = env_archcpu(env);
2661 
2662     return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / gt_cntfrq_period_ns(cpu);
2663 }
2664 
2665 static void gt_recalc_timer(ARMCPU *cpu, int timeridx)
2666 {
2667     ARMGenericTimer *gt = &cpu->env.cp15.c14_timer[timeridx];
2668 
2669     if (gt->ctl & 1) {
2670         /* Timer enabled: calculate and set current ISTATUS, irq, and
2671          * reset timer to when ISTATUS next has to change
2672          */
2673         uint64_t offset = timeridx == GTIMER_VIRT ?
2674                                       cpu->env.cp15.cntvoff_el2 : 0;
2675         uint64_t count = gt_get_countervalue(&cpu->env);
2676         /* Note that this must be unsigned 64 bit arithmetic: */
2677         int istatus = count - offset >= gt->cval;
2678         uint64_t nexttick;
2679         int irqstate;
2680 
2681         gt->ctl = deposit32(gt->ctl, 2, 1, istatus);
2682 
2683         irqstate = (istatus && !(gt->ctl & 2));
2684         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2685 
2686         if (istatus) {
2687             /* Next transition is when count rolls back over to zero */
2688             nexttick = UINT64_MAX;
2689         } else {
2690             /* Next transition is when we hit cval */
2691             nexttick = gt->cval + offset;
2692         }
2693         /* Note that the desired next expiry time might be beyond the
2694          * signed-64-bit range of a QEMUTimer -- in this case we just
2695          * set the timer for as far in the future as possible. When the
2696          * timer expires we will reset the timer for any remaining period.
2697          */
2698         if (nexttick > INT64_MAX / gt_cntfrq_period_ns(cpu)) {
2699             timer_mod_ns(cpu->gt_timer[timeridx], INT64_MAX);
2700         } else {
2701             timer_mod(cpu->gt_timer[timeridx], nexttick);
2702         }
2703         trace_arm_gt_recalc(timeridx, irqstate, nexttick);
2704     } else {
2705         /* Timer disabled: ISTATUS and timer output always clear */
2706         gt->ctl &= ~4;
2707         qemu_set_irq(cpu->gt_timer_outputs[timeridx], 0);
2708         timer_del(cpu->gt_timer[timeridx]);
2709         trace_arm_gt_recalc_disabled(timeridx);
2710     }
2711 }
2712 
2713 static void gt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri,
2714                            int timeridx)
2715 {
2716     ARMCPU *cpu = env_archcpu(env);
2717 
2718     timer_del(cpu->gt_timer[timeridx]);
2719 }
2720 
2721 static uint64_t gt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2722 {
2723     return gt_get_countervalue(env);
2724 }
2725 
2726 static uint64_t gt_virt_cnt_offset(CPUARMState *env)
2727 {
2728     uint64_t hcr;
2729 
2730     switch (arm_current_el(env)) {
2731     case 2:
2732         hcr = arm_hcr_el2_eff(env);
2733         if (hcr & HCR_E2H) {
2734             return 0;
2735         }
2736         break;
2737     case 0:
2738         hcr = arm_hcr_el2_eff(env);
2739         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
2740             return 0;
2741         }
2742         break;
2743     }
2744 
2745     return env->cp15.cntvoff_el2;
2746 }
2747 
2748 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
2749 {
2750     return gt_get_countervalue(env) - gt_virt_cnt_offset(env);
2751 }
2752 
2753 static void gt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2754                           int timeridx,
2755                           uint64_t value)
2756 {
2757     trace_arm_gt_cval_write(timeridx, value);
2758     env->cp15.c14_timer[timeridx].cval = value;
2759     gt_recalc_timer(env_archcpu(env), timeridx);
2760 }
2761 
2762 static uint64_t gt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri,
2763                              int timeridx)
2764 {
2765     uint64_t offset = 0;
2766 
2767     switch (timeridx) {
2768     case GTIMER_VIRT:
2769     case GTIMER_HYPVIRT:
2770         offset = gt_virt_cnt_offset(env);
2771         break;
2772     }
2773 
2774     return (uint32_t)(env->cp15.c14_timer[timeridx].cval -
2775                       (gt_get_countervalue(env) - offset));
2776 }
2777 
2778 static void gt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2779                           int timeridx,
2780                           uint64_t value)
2781 {
2782     uint64_t offset = 0;
2783 
2784     switch (timeridx) {
2785     case GTIMER_VIRT:
2786     case GTIMER_HYPVIRT:
2787         offset = gt_virt_cnt_offset(env);
2788         break;
2789     }
2790 
2791     trace_arm_gt_tval_write(timeridx, value);
2792     env->cp15.c14_timer[timeridx].cval = gt_get_countervalue(env) - offset +
2793                                          sextract64(value, 0, 32);
2794     gt_recalc_timer(env_archcpu(env), timeridx);
2795 }
2796 
2797 static void gt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2798                          int timeridx,
2799                          uint64_t value)
2800 {
2801     ARMCPU *cpu = env_archcpu(env);
2802     uint32_t oldval = env->cp15.c14_timer[timeridx].ctl;
2803 
2804     trace_arm_gt_ctl_write(timeridx, value);
2805     env->cp15.c14_timer[timeridx].ctl = deposit64(oldval, 0, 2, value);
2806     if ((oldval ^ value) & 1) {
2807         /* Enable toggled */
2808         gt_recalc_timer(cpu, timeridx);
2809     } else if ((oldval ^ value) & 2) {
2810         /* IMASK toggled: don't need to recalculate,
2811          * just set the interrupt line based on ISTATUS
2812          */
2813         int irqstate = (oldval & 4) && !(value & 2);
2814 
2815         trace_arm_gt_imask_toggle(timeridx, irqstate);
2816         qemu_set_irq(cpu->gt_timer_outputs[timeridx], irqstate);
2817     }
2818 }
2819 
2820 static void gt_phys_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2821 {
2822     gt_timer_reset(env, ri, GTIMER_PHYS);
2823 }
2824 
2825 static void gt_phys_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2826                                uint64_t value)
2827 {
2828     gt_cval_write(env, ri, GTIMER_PHYS, value);
2829 }
2830 
2831 static uint64_t gt_phys_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2832 {
2833     return gt_tval_read(env, ri, GTIMER_PHYS);
2834 }
2835 
2836 static void gt_phys_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2837                                uint64_t value)
2838 {
2839     gt_tval_write(env, ri, GTIMER_PHYS, value);
2840 }
2841 
2842 static void gt_phys_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2843                               uint64_t value)
2844 {
2845     gt_ctl_write(env, ri, GTIMER_PHYS, value);
2846 }
2847 
2848 static int gt_phys_redir_timeridx(CPUARMState *env)
2849 {
2850     switch (arm_mmu_idx(env)) {
2851     case ARMMMUIdx_E20_0:
2852     case ARMMMUIdx_E20_2:
2853     case ARMMMUIdx_E20_2_PAN:
2854     case ARMMMUIdx_SE20_0:
2855     case ARMMMUIdx_SE20_2:
2856     case ARMMMUIdx_SE20_2_PAN:
2857         return GTIMER_HYP;
2858     default:
2859         return GTIMER_PHYS;
2860     }
2861 }
2862 
2863 static int gt_virt_redir_timeridx(CPUARMState *env)
2864 {
2865     switch (arm_mmu_idx(env)) {
2866     case ARMMMUIdx_E20_0:
2867     case ARMMMUIdx_E20_2:
2868     case ARMMMUIdx_E20_2_PAN:
2869     case ARMMMUIdx_SE20_0:
2870     case ARMMMUIdx_SE20_2:
2871     case ARMMMUIdx_SE20_2_PAN:
2872         return GTIMER_HYPVIRT;
2873     default:
2874         return GTIMER_VIRT;
2875     }
2876 }
2877 
2878 static uint64_t gt_phys_redir_cval_read(CPUARMState *env,
2879                                         const ARMCPRegInfo *ri)
2880 {
2881     int timeridx = gt_phys_redir_timeridx(env);
2882     return env->cp15.c14_timer[timeridx].cval;
2883 }
2884 
2885 static void gt_phys_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2886                                      uint64_t value)
2887 {
2888     int timeridx = gt_phys_redir_timeridx(env);
2889     gt_cval_write(env, ri, timeridx, value);
2890 }
2891 
2892 static uint64_t gt_phys_redir_tval_read(CPUARMState *env,
2893                                         const ARMCPRegInfo *ri)
2894 {
2895     int timeridx = gt_phys_redir_timeridx(env);
2896     return gt_tval_read(env, ri, timeridx);
2897 }
2898 
2899 static void gt_phys_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2900                                      uint64_t value)
2901 {
2902     int timeridx = gt_phys_redir_timeridx(env);
2903     gt_tval_write(env, ri, timeridx, value);
2904 }
2905 
2906 static uint64_t gt_phys_redir_ctl_read(CPUARMState *env,
2907                                        const ARMCPRegInfo *ri)
2908 {
2909     int timeridx = gt_phys_redir_timeridx(env);
2910     return env->cp15.c14_timer[timeridx].ctl;
2911 }
2912 
2913 static void gt_phys_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2914                                     uint64_t value)
2915 {
2916     int timeridx = gt_phys_redir_timeridx(env);
2917     gt_ctl_write(env, ri, timeridx, value);
2918 }
2919 
2920 static void gt_virt_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
2921 {
2922     gt_timer_reset(env, ri, GTIMER_VIRT);
2923 }
2924 
2925 static void gt_virt_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2926                                uint64_t value)
2927 {
2928     gt_cval_write(env, ri, GTIMER_VIRT, value);
2929 }
2930 
2931 static uint64_t gt_virt_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
2932 {
2933     return gt_tval_read(env, ri, GTIMER_VIRT);
2934 }
2935 
2936 static void gt_virt_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2937                                uint64_t value)
2938 {
2939     gt_tval_write(env, ri, GTIMER_VIRT, value);
2940 }
2941 
2942 static void gt_virt_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2943                               uint64_t value)
2944 {
2945     gt_ctl_write(env, ri, GTIMER_VIRT, value);
2946 }
2947 
2948 static void gt_cntvoff_write(CPUARMState *env, const ARMCPRegInfo *ri,
2949                               uint64_t value)
2950 {
2951     ARMCPU *cpu = env_archcpu(env);
2952 
2953     trace_arm_gt_cntvoff_write(value);
2954     raw_write(env, ri, value);
2955     gt_recalc_timer(cpu, GTIMER_VIRT);
2956 }
2957 
2958 static uint64_t gt_virt_redir_cval_read(CPUARMState *env,
2959                                         const ARMCPRegInfo *ri)
2960 {
2961     int timeridx = gt_virt_redir_timeridx(env);
2962     return env->cp15.c14_timer[timeridx].cval;
2963 }
2964 
2965 static void gt_virt_redir_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2966                                      uint64_t value)
2967 {
2968     int timeridx = gt_virt_redir_timeridx(env);
2969     gt_cval_write(env, ri, timeridx, value);
2970 }
2971 
2972 static uint64_t gt_virt_redir_tval_read(CPUARMState *env,
2973                                         const ARMCPRegInfo *ri)
2974 {
2975     int timeridx = gt_virt_redir_timeridx(env);
2976     return gt_tval_read(env, ri, timeridx);
2977 }
2978 
2979 static void gt_virt_redir_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
2980                                      uint64_t value)
2981 {
2982     int timeridx = gt_virt_redir_timeridx(env);
2983     gt_tval_write(env, ri, timeridx, value);
2984 }
2985 
2986 static uint64_t gt_virt_redir_ctl_read(CPUARMState *env,
2987                                        const ARMCPRegInfo *ri)
2988 {
2989     int timeridx = gt_virt_redir_timeridx(env);
2990     return env->cp15.c14_timer[timeridx].ctl;
2991 }
2992 
2993 static void gt_virt_redir_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
2994                                     uint64_t value)
2995 {
2996     int timeridx = gt_virt_redir_timeridx(env);
2997     gt_ctl_write(env, ri, timeridx, value);
2998 }
2999 
3000 static void gt_hyp_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3001 {
3002     gt_timer_reset(env, ri, GTIMER_HYP);
3003 }
3004 
3005 static void gt_hyp_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3006                               uint64_t value)
3007 {
3008     gt_cval_write(env, ri, GTIMER_HYP, value);
3009 }
3010 
3011 static uint64_t gt_hyp_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3012 {
3013     return gt_tval_read(env, ri, GTIMER_HYP);
3014 }
3015 
3016 static void gt_hyp_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3017                               uint64_t value)
3018 {
3019     gt_tval_write(env, ri, GTIMER_HYP, value);
3020 }
3021 
3022 static void gt_hyp_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3023                               uint64_t value)
3024 {
3025     gt_ctl_write(env, ri, GTIMER_HYP, value);
3026 }
3027 
3028 static void gt_sec_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3029 {
3030     gt_timer_reset(env, ri, GTIMER_SEC);
3031 }
3032 
3033 static void gt_sec_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3034                               uint64_t value)
3035 {
3036     gt_cval_write(env, ri, GTIMER_SEC, value);
3037 }
3038 
3039 static uint64_t gt_sec_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3040 {
3041     return gt_tval_read(env, ri, GTIMER_SEC);
3042 }
3043 
3044 static void gt_sec_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3045                               uint64_t value)
3046 {
3047     gt_tval_write(env, ri, GTIMER_SEC, value);
3048 }
3049 
3050 static void gt_sec_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3051                               uint64_t value)
3052 {
3053     gt_ctl_write(env, ri, GTIMER_SEC, value);
3054 }
3055 
3056 static void gt_hv_timer_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3057 {
3058     gt_timer_reset(env, ri, GTIMER_HYPVIRT);
3059 }
3060 
3061 static void gt_hv_cval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3062                              uint64_t value)
3063 {
3064     gt_cval_write(env, ri, GTIMER_HYPVIRT, value);
3065 }
3066 
3067 static uint64_t gt_hv_tval_read(CPUARMState *env, const ARMCPRegInfo *ri)
3068 {
3069     return gt_tval_read(env, ri, GTIMER_HYPVIRT);
3070 }
3071 
3072 static void gt_hv_tval_write(CPUARMState *env, const ARMCPRegInfo *ri,
3073                              uint64_t value)
3074 {
3075     gt_tval_write(env, ri, GTIMER_HYPVIRT, value);
3076 }
3077 
3078 static void gt_hv_ctl_write(CPUARMState *env, const ARMCPRegInfo *ri,
3079                             uint64_t value)
3080 {
3081     gt_ctl_write(env, ri, GTIMER_HYPVIRT, value);
3082 }
3083 
3084 void arm_gt_ptimer_cb(void *opaque)
3085 {
3086     ARMCPU *cpu = opaque;
3087 
3088     gt_recalc_timer(cpu, GTIMER_PHYS);
3089 }
3090 
3091 void arm_gt_vtimer_cb(void *opaque)
3092 {
3093     ARMCPU *cpu = opaque;
3094 
3095     gt_recalc_timer(cpu, GTIMER_VIRT);
3096 }
3097 
3098 void arm_gt_htimer_cb(void *opaque)
3099 {
3100     ARMCPU *cpu = opaque;
3101 
3102     gt_recalc_timer(cpu, GTIMER_HYP);
3103 }
3104 
3105 void arm_gt_stimer_cb(void *opaque)
3106 {
3107     ARMCPU *cpu = opaque;
3108 
3109     gt_recalc_timer(cpu, GTIMER_SEC);
3110 }
3111 
3112 void arm_gt_hvtimer_cb(void *opaque)
3113 {
3114     ARMCPU *cpu = opaque;
3115 
3116     gt_recalc_timer(cpu, GTIMER_HYPVIRT);
3117 }
3118 
3119 static void arm_gt_cntfrq_reset(CPUARMState *env, const ARMCPRegInfo *opaque)
3120 {
3121     ARMCPU *cpu = env_archcpu(env);
3122 
3123     cpu->env.cp15.c14_cntfrq = cpu->gt_cntfrq_hz;
3124 }
3125 
3126 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3127     /* Note that CNTFRQ is purely reads-as-written for the benefit
3128      * of software; writing it doesn't actually change the timer frequency.
3129      * Our reset value matches the fixed frequency we implement the timer at.
3130      */
3131     { .name = "CNTFRQ", .cp = 15, .crn = 14, .crm = 0, .opc1 = 0, .opc2 = 0,
3132       .type = ARM_CP_ALIAS,
3133       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3134       .fieldoffset = offsetoflow32(CPUARMState, cp15.c14_cntfrq),
3135     },
3136     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3137       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3138       .access = PL1_RW | PL0_R, .accessfn = gt_cntfrq_access,
3139       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3140       .resetfn = arm_gt_cntfrq_reset,
3141     },
3142     /* overall control: mostly access permissions */
3143     { .name = "CNTKCTL", .state = ARM_CP_STATE_BOTH,
3144       .opc0 = 3, .opc1 = 0, .crn = 14, .crm = 1, .opc2 = 0,
3145       .access = PL1_RW,
3146       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntkctl),
3147       .resetvalue = 0,
3148     },
3149     /* per-timer control */
3150     { .name = "CNTP_CTL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3151       .secure = ARM_CP_SECSTATE_NS,
3152       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3153       .accessfn = gt_ptimer_access,
3154       .fieldoffset = offsetoflow32(CPUARMState,
3155                                    cp15.c14_timer[GTIMER_PHYS].ctl),
3156       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3157       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3158     },
3159     { .name = "CNTP_CTL_S",
3160       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 1,
3161       .secure = ARM_CP_SECSTATE_S,
3162       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3163       .accessfn = gt_ptimer_access,
3164       .fieldoffset = offsetoflow32(CPUARMState,
3165                                    cp15.c14_timer[GTIMER_SEC].ctl),
3166       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3167     },
3168     { .name = "CNTP_CTL_EL0", .state = ARM_CP_STATE_AA64,
3169       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 1,
3170       .type = ARM_CP_IO, .access = PL0_RW,
3171       .accessfn = gt_ptimer_access,
3172       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
3173       .resetvalue = 0,
3174       .readfn = gt_phys_redir_ctl_read, .raw_readfn = raw_read,
3175       .writefn = gt_phys_redir_ctl_write, .raw_writefn = raw_write,
3176     },
3177     { .name = "CNTV_CTL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 1,
3178       .type = ARM_CP_IO | ARM_CP_ALIAS, .access = PL0_RW,
3179       .accessfn = gt_vtimer_access,
3180       .fieldoffset = offsetoflow32(CPUARMState,
3181                                    cp15.c14_timer[GTIMER_VIRT].ctl),
3182       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3183       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3184     },
3185     { .name = "CNTV_CTL_EL0", .state = ARM_CP_STATE_AA64,
3186       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 1,
3187       .type = ARM_CP_IO, .access = PL0_RW,
3188       .accessfn = gt_vtimer_access,
3189       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
3190       .resetvalue = 0,
3191       .readfn = gt_virt_redir_ctl_read, .raw_readfn = raw_read,
3192       .writefn = gt_virt_redir_ctl_write, .raw_writefn = raw_write,
3193     },
3194     /* TimerValue views: a 32 bit downcounting view of the underlying state */
3195     { .name = "CNTP_TVAL", .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3196       .secure = ARM_CP_SECSTATE_NS,
3197       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3198       .accessfn = gt_ptimer_access,
3199       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3200     },
3201     { .name = "CNTP_TVAL_S",
3202       .cp = 15, .crn = 14, .crm = 2, .opc1 = 0, .opc2 = 0,
3203       .secure = ARM_CP_SECSTATE_S,
3204       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3205       .accessfn = gt_ptimer_access,
3206       .readfn = gt_sec_tval_read, .writefn = gt_sec_tval_write,
3207     },
3208     { .name = "CNTP_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3209       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 0,
3210       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3211       .accessfn = gt_ptimer_access, .resetfn = gt_phys_timer_reset,
3212       .readfn = gt_phys_redir_tval_read, .writefn = gt_phys_redir_tval_write,
3213     },
3214     { .name = "CNTV_TVAL", .cp = 15, .crn = 14, .crm = 3, .opc1 = 0, .opc2 = 0,
3215       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3216       .accessfn = gt_vtimer_access,
3217       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3218     },
3219     { .name = "CNTV_TVAL_EL0", .state = ARM_CP_STATE_AA64,
3220       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 0,
3221       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL0_RW,
3222       .accessfn = gt_vtimer_access, .resetfn = gt_virt_timer_reset,
3223       .readfn = gt_virt_redir_tval_read, .writefn = gt_virt_redir_tval_write,
3224     },
3225     /* The counter itself */
3226     { .name = "CNTPCT", .cp = 15, .crm = 14, .opc1 = 0,
3227       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3228       .accessfn = gt_pct_access,
3229       .readfn = gt_cnt_read, .resetfn = arm_cp_reset_ignore,
3230     },
3231     { .name = "CNTPCT_EL0", .state = ARM_CP_STATE_AA64,
3232       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 1,
3233       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3234       .accessfn = gt_pct_access, .readfn = gt_cnt_read,
3235     },
3236     { .name = "CNTVCT", .cp = 15, .crm = 14, .opc1 = 1,
3237       .access = PL0_R, .type = ARM_CP_64BIT | ARM_CP_NO_RAW | ARM_CP_IO,
3238       .accessfn = gt_vct_access,
3239       .readfn = gt_virt_cnt_read, .resetfn = arm_cp_reset_ignore,
3240     },
3241     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3242       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3243       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3244       .accessfn = gt_vct_access, .readfn = gt_virt_cnt_read,
3245     },
3246     /* Comparison value, indicating when the timer goes off */
3247     { .name = "CNTP_CVAL", .cp = 15, .crm = 14, .opc1 = 2,
3248       .secure = ARM_CP_SECSTATE_NS,
3249       .access = PL0_RW,
3250       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3251       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3252       .accessfn = gt_ptimer_access,
3253       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3254       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3255     },
3256     { .name = "CNTP_CVAL_S", .cp = 15, .crm = 14, .opc1 = 2,
3257       .secure = ARM_CP_SECSTATE_S,
3258       .access = PL0_RW,
3259       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3260       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3261       .accessfn = gt_ptimer_access,
3262       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3263     },
3264     { .name = "CNTP_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3265       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 2, .opc2 = 2,
3266       .access = PL0_RW,
3267       .type = ARM_CP_IO,
3268       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
3269       .resetvalue = 0, .accessfn = gt_ptimer_access,
3270       .readfn = gt_phys_redir_cval_read, .raw_readfn = raw_read,
3271       .writefn = gt_phys_redir_cval_write, .raw_writefn = raw_write,
3272     },
3273     { .name = "CNTV_CVAL", .cp = 15, .crm = 14, .opc1 = 3,
3274       .access = PL0_RW,
3275       .type = ARM_CP_64BIT | ARM_CP_IO | ARM_CP_ALIAS,
3276       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3277       .accessfn = gt_vtimer_access,
3278       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3279       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3280     },
3281     { .name = "CNTV_CVAL_EL0", .state = ARM_CP_STATE_AA64,
3282       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 3, .opc2 = 2,
3283       .access = PL0_RW,
3284       .type = ARM_CP_IO,
3285       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
3286       .resetvalue = 0, .accessfn = gt_vtimer_access,
3287       .readfn = gt_virt_redir_cval_read, .raw_readfn = raw_read,
3288       .writefn = gt_virt_redir_cval_write, .raw_writefn = raw_write,
3289     },
3290     /* Secure timer -- this is actually restricted to only EL3
3291      * and configurably Secure-EL1 via the accessfn.
3292      */
3293     { .name = "CNTPS_TVAL_EL1", .state = ARM_CP_STATE_AA64,
3294       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 0,
3295       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL1_RW,
3296       .accessfn = gt_stimer_access,
3297       .readfn = gt_sec_tval_read,
3298       .writefn = gt_sec_tval_write,
3299       .resetfn = gt_sec_timer_reset,
3300     },
3301     { .name = "CNTPS_CTL_EL1", .state = ARM_CP_STATE_AA64,
3302       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 1,
3303       .type = ARM_CP_IO, .access = PL1_RW,
3304       .accessfn = gt_stimer_access,
3305       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].ctl),
3306       .resetvalue = 0,
3307       .writefn = gt_sec_ctl_write, .raw_writefn = raw_write,
3308     },
3309     { .name = "CNTPS_CVAL_EL1", .state = ARM_CP_STATE_AA64,
3310       .opc0 = 3, .opc1 = 7, .crn = 14, .crm = 2, .opc2 = 2,
3311       .type = ARM_CP_IO, .access = PL1_RW,
3312       .accessfn = gt_stimer_access,
3313       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_SEC].cval),
3314       .writefn = gt_sec_cval_write, .raw_writefn = raw_write,
3315     },
3316     REGINFO_SENTINEL
3317 };
3318 
3319 static CPAccessResult e2h_access(CPUARMState *env, const ARMCPRegInfo *ri,
3320                                  bool isread)
3321 {
3322     if (!(arm_hcr_el2_eff(env) & HCR_E2H)) {
3323         return CP_ACCESS_TRAP;
3324     }
3325     return CP_ACCESS_OK;
3326 }
3327 
3328 #else
3329 
3330 /* In user-mode most of the generic timer registers are inaccessible
3331  * however modern kernels (4.12+) allow access to cntvct_el0
3332  */
3333 
3334 static uint64_t gt_virt_cnt_read(CPUARMState *env, const ARMCPRegInfo *ri)
3335 {
3336     ARMCPU *cpu = env_archcpu(env);
3337 
3338     /* Currently we have no support for QEMUTimer in linux-user so we
3339      * can't call gt_get_countervalue(env), instead we directly
3340      * call the lower level functions.
3341      */
3342     return cpu_get_clock() / gt_cntfrq_period_ns(cpu);
3343 }
3344 
3345 static const ARMCPRegInfo generic_timer_cp_reginfo[] = {
3346     { .name = "CNTFRQ_EL0", .state = ARM_CP_STATE_AA64,
3347       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 0,
3348       .type = ARM_CP_CONST, .access = PL0_R /* no PL1_RW in linux-user */,
3349       .fieldoffset = offsetof(CPUARMState, cp15.c14_cntfrq),
3350       .resetvalue = NANOSECONDS_PER_SECOND / GTIMER_SCALE,
3351     },
3352     { .name = "CNTVCT_EL0", .state = ARM_CP_STATE_AA64,
3353       .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 0, .opc2 = 2,
3354       .access = PL0_R, .type = ARM_CP_NO_RAW | ARM_CP_IO,
3355       .readfn = gt_virt_cnt_read,
3356     },
3357     REGINFO_SENTINEL
3358 };
3359 
3360 #endif
3361 
3362 static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3363 {
3364     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3365         raw_write(env, ri, value);
3366     } else if (arm_feature(env, ARM_FEATURE_V7)) {
3367         raw_write(env, ri, value & 0xfffff6ff);
3368     } else {
3369         raw_write(env, ri, value & 0xfffff1ff);
3370     }
3371 }
3372 
3373 #ifndef CONFIG_USER_ONLY
3374 /* get_phys_addr() isn't present for user-mode-only targets */
3375 
3376 static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri,
3377                                  bool isread)
3378 {
3379     if (ri->opc2 & 4) {
3380         /* The ATS12NSO* operations must trap to EL3 or EL2 if executed in
3381          * Secure EL1 (which can only happen if EL3 is AArch64).
3382          * They are simply UNDEF if executed from NS EL1.
3383          * They function normally from EL2 or EL3.
3384          */
3385         if (arm_current_el(env) == 1) {
3386             if (arm_is_secure_below_el3(env)) {
3387                 if (env->cp15.scr_el3 & SCR_EEL2) {
3388                     return CP_ACCESS_TRAP_UNCATEGORIZED_EL2;
3389                 }
3390                 return CP_ACCESS_TRAP_UNCATEGORIZED_EL3;
3391             }
3392             return CP_ACCESS_TRAP_UNCATEGORIZED;
3393         }
3394     }
3395     return CP_ACCESS_OK;
3396 }
3397 
3398 #ifdef CONFIG_TCG
3399 static uint64_t do_ats_write(CPUARMState *env, uint64_t value,
3400                              MMUAccessType access_type, ARMMMUIdx mmu_idx)
3401 {
3402     hwaddr phys_addr;
3403     target_ulong page_size;
3404     int prot;
3405     bool ret;
3406     uint64_t par64;
3407     bool format64 = false;
3408     MemTxAttrs attrs = {};
3409     ARMMMUFaultInfo fi = {};
3410     ARMCacheAttrs cacheattrs = {};
3411 
3412     ret = get_phys_addr(env, value, access_type, mmu_idx, &phys_addr, &attrs,
3413                         &prot, &page_size, &fi, &cacheattrs);
3414 
3415     if (ret) {
3416         /*
3417          * Some kinds of translation fault must cause exceptions rather
3418          * than being reported in the PAR.
3419          */
3420         int current_el = arm_current_el(env);
3421         int target_el;
3422         uint32_t syn, fsr, fsc;
3423         bool take_exc = false;
3424 
3425         if (fi.s1ptw && current_el == 1
3426             && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
3427             /*
3428              * Synchronous stage 2 fault on an access made as part of the
3429              * translation table walk for AT S1E0* or AT S1E1* insn
3430              * executed from NS EL1. If this is a synchronous external abort
3431              * and SCR_EL3.EA == 1, then we take a synchronous external abort
3432              * to EL3. Otherwise the fault is taken as an exception to EL2,
3433              * and HPFAR_EL2 holds the faulting IPA.
3434              */
3435             if (fi.type == ARMFault_SyncExternalOnWalk &&
3436                 (env->cp15.scr_el3 & SCR_EA)) {
3437                 target_el = 3;
3438             } else {
3439                 env->cp15.hpfar_el2 = extract64(fi.s2addr, 12, 47) << 4;
3440                 if (arm_is_secure_below_el3(env) && fi.s1ns) {
3441                     env->cp15.hpfar_el2 |= HPFAR_NS;
3442                 }
3443                 target_el = 2;
3444             }
3445             take_exc = true;
3446         } else if (fi.type == ARMFault_SyncExternalOnWalk) {
3447             /*
3448              * Synchronous external aborts during a translation table walk
3449              * are taken as Data Abort exceptions.
3450              */
3451             if (fi.stage2) {
3452                 if (current_el == 3) {
3453                     target_el = 3;
3454                 } else {
3455                     target_el = 2;
3456                 }
3457             } else {
3458                 target_el = exception_target_el(env);
3459             }
3460             take_exc = true;
3461         }
3462 
3463         if (take_exc) {
3464             /* Construct FSR and FSC using same logic as arm_deliver_fault() */
3465             if (target_el == 2 || arm_el_is_aa64(env, target_el) ||
3466                 arm_s1_regime_using_lpae_format(env, mmu_idx)) {
3467                 fsr = arm_fi_to_lfsc(&fi);
3468                 fsc = extract32(fsr, 0, 6);
3469             } else {
3470                 fsr = arm_fi_to_sfsc(&fi);
3471                 fsc = 0x3f;
3472             }
3473             /*
3474              * Report exception with ESR indicating a fault due to a
3475              * translation table walk for a cache maintenance instruction.
3476              */
3477             syn = syn_data_abort_no_iss(current_el == target_el, 0,
3478                                         fi.ea, 1, fi.s1ptw, 1, fsc);
3479             env->exception.vaddress = value;
3480             env->exception.fsr = fsr;
3481             raise_exception(env, EXCP_DATA_ABORT, syn, target_el);
3482         }
3483     }
3484 
3485     if (is_a64(env)) {
3486         format64 = true;
3487     } else if (arm_feature(env, ARM_FEATURE_LPAE)) {
3488         /*
3489          * ATS1Cxx:
3490          * * TTBCR.EAE determines whether the result is returned using the
3491          *   32-bit or the 64-bit PAR format
3492          * * Instructions executed in Hyp mode always use the 64bit format
3493          *
3494          * ATS1S2NSOxx uses the 64bit format if any of the following is true:
3495          * * The Non-secure TTBCR.EAE bit is set to 1
3496          * * The implementation includes EL2, and the value of HCR.VM is 1
3497          *
3498          * (Note that HCR.DC makes HCR.VM behave as if it is 1.)
3499          *
3500          * ATS1Hx always uses the 64bit format.
3501          */
3502         format64 = arm_s1_regime_using_lpae_format(env, mmu_idx);
3503 
3504         if (arm_feature(env, ARM_FEATURE_EL2)) {
3505             if (mmu_idx == ARMMMUIdx_E10_0 ||
3506                 mmu_idx == ARMMMUIdx_E10_1 ||
3507                 mmu_idx == ARMMMUIdx_E10_1_PAN) {
3508                 format64 |= env->cp15.hcr_el2 & (HCR_VM | HCR_DC);
3509             } else {
3510                 format64 |= arm_current_el(env) == 2;
3511             }
3512         }
3513     }
3514 
3515     if (format64) {
3516         /* Create a 64-bit PAR */
3517         par64 = (1 << 11); /* LPAE bit always set */
3518         if (!ret) {
3519             par64 |= phys_addr & ~0xfffULL;
3520             if (!attrs.secure) {
3521                 par64 |= (1 << 9); /* NS */
3522             }
3523             par64 |= (uint64_t)cacheattrs.attrs << 56; /* ATTR */
3524             par64 |= cacheattrs.shareability << 7; /* SH */
3525         } else {
3526             uint32_t fsr = arm_fi_to_lfsc(&fi);
3527 
3528             par64 |= 1; /* F */
3529             par64 |= (fsr & 0x3f) << 1; /* FS */
3530             if (fi.stage2) {
3531                 par64 |= (1 << 9); /* S */
3532             }
3533             if (fi.s1ptw) {
3534                 par64 |= (1 << 8); /* PTW */
3535             }
3536         }
3537     } else {
3538         /* fsr is a DFSR/IFSR value for the short descriptor
3539          * translation table format (with WnR always clear).
3540          * Convert it to a 32-bit PAR.
3541          */
3542         if (!ret) {
3543             /* We do not set any attribute bits in the PAR */
3544             if (page_size == (1 << 24)
3545                 && arm_feature(env, ARM_FEATURE_V7)) {
3546                 par64 = (phys_addr & 0xff000000) | (1 << 1);
3547             } else {
3548                 par64 = phys_addr & 0xfffff000;
3549             }
3550             if (!attrs.secure) {
3551                 par64 |= (1 << 9); /* NS */
3552             }
3553         } else {
3554             uint32_t fsr = arm_fi_to_sfsc(&fi);
3555 
3556             par64 = ((fsr & (1 << 10)) >> 5) | ((fsr & (1 << 12)) >> 6) |
3557                     ((fsr & 0xf) << 1) | 1;
3558         }
3559     }
3560     return par64;
3561 }
3562 #endif /* CONFIG_TCG */
3563 
3564 static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
3565 {
3566 #ifdef CONFIG_TCG
3567     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3568     uint64_t par64;
3569     ARMMMUIdx mmu_idx;
3570     int el = arm_current_el(env);
3571     bool secure = arm_is_secure_below_el3(env);
3572 
3573     switch (ri->opc2 & 6) {
3574     case 0:
3575         /* stage 1 current state PL1: ATS1CPR, ATS1CPW, ATS1CPRP, ATS1CPWP */
3576         switch (el) {
3577         case 3:
3578             mmu_idx = ARMMMUIdx_SE3;
3579             break;
3580         case 2:
3581             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3582             /* fall through */
3583         case 1:
3584             if (ri->crm == 9 && (env->uncached_cpsr & CPSR_PAN)) {
3585                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3586                            : ARMMMUIdx_Stage1_E1_PAN);
3587             } else {
3588                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3589             }
3590             break;
3591         default:
3592             g_assert_not_reached();
3593         }
3594         break;
3595     case 2:
3596         /* stage 1 current state PL0: ATS1CUR, ATS1CUW */
3597         switch (el) {
3598         case 3:
3599             mmu_idx = ARMMMUIdx_SE10_0;
3600             break;
3601         case 2:
3602             g_assert(!secure);  /* ARMv8.4-SecEL2 is 64-bit only */
3603             mmu_idx = ARMMMUIdx_Stage1_E0;
3604             break;
3605         case 1:
3606             mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3607             break;
3608         default:
3609             g_assert_not_reached();
3610         }
3611         break;
3612     case 4:
3613         /* stage 1+2 NonSecure PL1: ATS12NSOPR, ATS12NSOPW */
3614         mmu_idx = ARMMMUIdx_E10_1;
3615         break;
3616     case 6:
3617         /* stage 1+2 NonSecure PL0: ATS12NSOUR, ATS12NSOUW */
3618         mmu_idx = ARMMMUIdx_E10_0;
3619         break;
3620     default:
3621         g_assert_not_reached();
3622     }
3623 
3624     par64 = do_ats_write(env, value, access_type, mmu_idx);
3625 
3626     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3627 #else
3628     /* Handled by hardware accelerator. */
3629     g_assert_not_reached();
3630 #endif /* CONFIG_TCG */
3631 }
3632 
3633 static void ats1h_write(CPUARMState *env, const ARMCPRegInfo *ri,
3634                         uint64_t value)
3635 {
3636 #ifdef CONFIG_TCG
3637     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3638     uint64_t par64;
3639 
3640     par64 = do_ats_write(env, value, access_type, ARMMMUIdx_E2);
3641 
3642     A32_BANKED_CURRENT_REG_SET(env, par, par64);
3643 #else
3644     /* Handled by hardware accelerator. */
3645     g_assert_not_reached();
3646 #endif /* CONFIG_TCG */
3647 }
3648 
3649 static CPAccessResult at_s1e2_access(CPUARMState *env, const ARMCPRegInfo *ri,
3650                                      bool isread)
3651 {
3652     if (arm_current_el(env) == 3 &&
3653         !(env->cp15.scr_el3 & (SCR_NS | SCR_EEL2))) {
3654         return CP_ACCESS_TRAP;
3655     }
3656     return CP_ACCESS_OK;
3657 }
3658 
3659 static void ats_write64(CPUARMState *env, const ARMCPRegInfo *ri,
3660                         uint64_t value)
3661 {
3662 #ifdef CONFIG_TCG
3663     MMUAccessType access_type = ri->opc2 & 1 ? MMU_DATA_STORE : MMU_DATA_LOAD;
3664     ARMMMUIdx mmu_idx;
3665     int secure = arm_is_secure_below_el3(env);
3666 
3667     switch (ri->opc2 & 6) {
3668     case 0:
3669         switch (ri->opc1) {
3670         case 0: /* AT S1E1R, AT S1E1W, AT S1E1RP, AT S1E1WP */
3671             if (ri->crm == 9 && (env->pstate & PSTATE_PAN)) {
3672                 mmu_idx = (secure ? ARMMMUIdx_Stage1_SE1_PAN
3673                            : ARMMMUIdx_Stage1_E1_PAN);
3674             } else {
3675                 mmu_idx = secure ? ARMMMUIdx_Stage1_SE1 : ARMMMUIdx_Stage1_E1;
3676             }
3677             break;
3678         case 4: /* AT S1E2R, AT S1E2W */
3679             mmu_idx = secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2;
3680             break;
3681         case 6: /* AT S1E3R, AT S1E3W */
3682             mmu_idx = ARMMMUIdx_SE3;
3683             break;
3684         default:
3685             g_assert_not_reached();
3686         }
3687         break;
3688     case 2: /* AT S1E0R, AT S1E0W */
3689         mmu_idx = secure ? ARMMMUIdx_Stage1_SE0 : ARMMMUIdx_Stage1_E0;
3690         break;
3691     case 4: /* AT S12E1R, AT S12E1W */
3692         mmu_idx = secure ? ARMMMUIdx_SE10_1 : ARMMMUIdx_E10_1;
3693         break;
3694     case 6: /* AT S12E0R, AT S12E0W */
3695         mmu_idx = secure ? ARMMMUIdx_SE10_0 : ARMMMUIdx_E10_0;
3696         break;
3697     default:
3698         g_assert_not_reached();
3699     }
3700 
3701     env->cp15.par_el[1] = do_ats_write(env, value, access_type, mmu_idx);
3702 #else
3703     /* Handled by hardware accelerator. */
3704     g_assert_not_reached();
3705 #endif /* CONFIG_TCG */
3706 }
3707 #endif
3708 
3709 static const ARMCPRegInfo vapa_cp_reginfo[] = {
3710     { .name = "PAR", .cp = 15, .crn = 7, .crm = 4, .opc1 = 0, .opc2 = 0,
3711       .access = PL1_RW, .resetvalue = 0,
3712       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.par_s),
3713                              offsetoflow32(CPUARMState, cp15.par_ns) },
3714       .writefn = par_write },
3715 #ifndef CONFIG_USER_ONLY
3716     /* This underdecoding is safe because the reginfo is NO_RAW. */
3717     { .name = "ATS", .cp = 15, .crn = 7, .crm = 8, .opc1 = 0, .opc2 = CP_ANY,
3718       .access = PL1_W, .accessfn = ats_access,
3719       .writefn = ats_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
3720 #endif
3721     REGINFO_SENTINEL
3722 };
3723 
3724 /* Return basic MPU access permission bits.  */
3725 static uint32_t simple_mpu_ap_bits(uint32_t val)
3726 {
3727     uint32_t ret;
3728     uint32_t mask;
3729     int i;
3730     ret = 0;
3731     mask = 3;
3732     for (i = 0; i < 16; i += 2) {
3733         ret |= (val >> i) & mask;
3734         mask <<= 2;
3735     }
3736     return ret;
3737 }
3738 
3739 /* Pad basic MPU access permission bits to extended format.  */
3740 static uint32_t extended_mpu_ap_bits(uint32_t val)
3741 {
3742     uint32_t ret;
3743     uint32_t mask;
3744     int i;
3745     ret = 0;
3746     mask = 3;
3747     for (i = 0; i < 16; i += 2) {
3748         ret |= (val & mask) << i;
3749         mask <<= 2;
3750     }
3751     return ret;
3752 }
3753 
3754 static void pmsav5_data_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3755                                  uint64_t value)
3756 {
3757     env->cp15.pmsav5_data_ap = extended_mpu_ap_bits(value);
3758 }
3759 
3760 static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3761 {
3762     return simple_mpu_ap_bits(env->cp15.pmsav5_data_ap);
3763 }
3764 
3765 static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,
3766                                  uint64_t value)
3767 {
3768     env->cp15.pmsav5_insn_ap = extended_mpu_ap_bits(value);
3769 }
3770 
3771 static uint64_t pmsav5_insn_ap_read(CPUARMState *env, const ARMCPRegInfo *ri)
3772 {
3773     return simple_mpu_ap_bits(env->cp15.pmsav5_insn_ap);
3774 }
3775 
3776 static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)
3777 {
3778     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3779 
3780     if (!u32p) {
3781         return 0;
3782     }
3783 
3784     u32p += env->pmsav7.rnr[M_REG_NS];
3785     return *u32p;
3786 }
3787 
3788 static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,
3789                          uint64_t value)
3790 {
3791     ARMCPU *cpu = env_archcpu(env);
3792     uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);
3793 
3794     if (!u32p) {
3795         return;
3796     }
3797 
3798     u32p += env->pmsav7.rnr[M_REG_NS];
3799     tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */
3800     *u32p = value;
3801 }
3802 
3803 static void pmsav7_rgnr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3804                               uint64_t value)
3805 {
3806     ARMCPU *cpu = env_archcpu(env);
3807     uint32_t nrgs = cpu->pmsav7_dregion;
3808 
3809     if (value >= nrgs) {
3810         qemu_log_mask(LOG_GUEST_ERROR,
3811                       "PMSAv7 RGNR write >= # supported regions, %" PRIu32
3812                       " > %" PRIu32 "\n", (uint32_t)value, nrgs);
3813         return;
3814     }
3815 
3816     raw_write(env, ri, value);
3817 }
3818 
3819 static const ARMCPRegInfo pmsav7_cp_reginfo[] = {
3820     /* Reset for all these registers is handled in arm_cpu_reset(),
3821      * because the PMSAv7 is also used by M-profile CPUs, which do
3822      * not register cpregs but still need the state to be reset.
3823      */
3824     { .name = "DRBAR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 0,
3825       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3826       .fieldoffset = offsetof(CPUARMState, pmsav7.drbar),
3827       .readfn = pmsav7_read, .writefn = pmsav7_write,
3828       .resetfn = arm_cp_reset_ignore },
3829     { .name = "DRSR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 2,
3830       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3831       .fieldoffset = offsetof(CPUARMState, pmsav7.drsr),
3832       .readfn = pmsav7_read, .writefn = pmsav7_write,
3833       .resetfn = arm_cp_reset_ignore },
3834     { .name = "DRACR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 1, .opc2 = 4,
3835       .access = PL1_RW, .type = ARM_CP_NO_RAW,
3836       .fieldoffset = offsetof(CPUARMState, pmsav7.dracr),
3837       .readfn = pmsav7_read, .writefn = pmsav7_write,
3838       .resetfn = arm_cp_reset_ignore },
3839     { .name = "RGNR", .cp = 15, .crn = 6, .opc1 = 0, .crm = 2, .opc2 = 0,
3840       .access = PL1_RW,
3841       .fieldoffset = offsetof(CPUARMState, pmsav7.rnr[M_REG_NS]),
3842       .writefn = pmsav7_rgnr_write,
3843       .resetfn = arm_cp_reset_ignore },
3844     REGINFO_SENTINEL
3845 };
3846 
3847 static const ARMCPRegInfo pmsav5_cp_reginfo[] = {
3848     { .name = "DATA_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
3849       .access = PL1_RW, .type = ARM_CP_ALIAS,
3850       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3851       .readfn = pmsav5_data_ap_read, .writefn = pmsav5_data_ap_write, },
3852     { .name = "INSN_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
3853       .access = PL1_RW, .type = ARM_CP_ALIAS,
3854       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3855       .readfn = pmsav5_insn_ap_read, .writefn = pmsav5_insn_ap_write, },
3856     { .name = "DATA_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 2,
3857       .access = PL1_RW,
3858       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_data_ap),
3859       .resetvalue = 0, },
3860     { .name = "INSN_EXT_AP", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 3,
3861       .access = PL1_RW,
3862       .fieldoffset = offsetof(CPUARMState, cp15.pmsav5_insn_ap),
3863       .resetvalue = 0, },
3864     { .name = "DCACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
3865       .access = PL1_RW,
3866       .fieldoffset = offsetof(CPUARMState, cp15.c2_data), .resetvalue = 0, },
3867     { .name = "ICACHE_CFG", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 1,
3868       .access = PL1_RW,
3869       .fieldoffset = offsetof(CPUARMState, cp15.c2_insn), .resetvalue = 0, },
3870     /* Protection region base and size registers */
3871     { .name = "946_PRBS0", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0,
3872       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3873       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[0]) },
3874     { .name = "946_PRBS1", .cp = 15, .crn = 6, .crm = 1, .opc1 = 0,
3875       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3876       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[1]) },
3877     { .name = "946_PRBS2", .cp = 15, .crn = 6, .crm = 2, .opc1 = 0,
3878       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3879       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[2]) },
3880     { .name = "946_PRBS3", .cp = 15, .crn = 6, .crm = 3, .opc1 = 0,
3881       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3882       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[3]) },
3883     { .name = "946_PRBS4", .cp = 15, .crn = 6, .crm = 4, .opc1 = 0,
3884       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3885       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[4]) },
3886     { .name = "946_PRBS5", .cp = 15, .crn = 6, .crm = 5, .opc1 = 0,
3887       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3888       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[5]) },
3889     { .name = "946_PRBS6", .cp = 15, .crn = 6, .crm = 6, .opc1 = 0,
3890       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3891       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[6]) },
3892     { .name = "946_PRBS7", .cp = 15, .crn = 6, .crm = 7, .opc1 = 0,
3893       .opc2 = CP_ANY, .access = PL1_RW, .resetvalue = 0,
3894       .fieldoffset = offsetof(CPUARMState, cp15.c6_region[7]) },
3895     REGINFO_SENTINEL
3896 };
3897 
3898 static void vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,
3899                                  uint64_t value)
3900 {
3901     TCR *tcr = raw_ptr(env, ri);
3902     int maskshift = extract32(value, 0, 3);
3903 
3904     if (!arm_feature(env, ARM_FEATURE_V8)) {
3905         if (arm_feature(env, ARM_FEATURE_LPAE) && (value & TTBCR_EAE)) {
3906             /* Pre ARMv8 bits [21:19], [15:14] and [6:3] are UNK/SBZP when
3907              * using Long-desciptor translation table format */
3908             value &= ~((7 << 19) | (3 << 14) | (0xf << 3));
3909         } else if (arm_feature(env, ARM_FEATURE_EL3)) {
3910             /* In an implementation that includes the Security Extensions
3911              * TTBCR has additional fields PD0 [4] and PD1 [5] for
3912              * Short-descriptor translation table format.
3913              */
3914             value &= TTBCR_PD1 | TTBCR_PD0 | TTBCR_N;
3915         } else {
3916             value &= TTBCR_N;
3917         }
3918     }
3919 
3920     /* Update the masks corresponding to the TCR bank being written
3921      * Note that we always calculate mask and base_mask, but
3922      * they are only used for short-descriptor tables (ie if EAE is 0);
3923      * for long-descriptor tables the TCR fields are used differently
3924      * and the mask and base_mask values are meaningless.
3925      */
3926     tcr->raw_tcr = value;
3927     tcr->mask = ~(((uint32_t)0xffffffffu) >> maskshift);
3928     tcr->base_mask = ~((uint32_t)0x3fffu >> maskshift);
3929 }
3930 
3931 static void vmsa_ttbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3932                              uint64_t value)
3933 {
3934     ARMCPU *cpu = env_archcpu(env);
3935     TCR *tcr = raw_ptr(env, ri);
3936 
3937     if (arm_feature(env, ARM_FEATURE_LPAE)) {
3938         /* With LPAE the TTBCR could result in a change of ASID
3939          * via the TTBCR.A1 bit, so do a TLB flush.
3940          */
3941         tlb_flush(CPU(cpu));
3942     }
3943     /* Preserve the high half of TCR_EL1, set via TTBCR2.  */
3944     value = deposit64(tcr->raw_tcr, 0, 32, value);
3945     vmsa_ttbcr_raw_write(env, ri, value);
3946 }
3947 
3948 static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)
3949 {
3950     TCR *tcr = raw_ptr(env, ri);
3951 
3952     /* Reset both the TCR as well as the masks corresponding to the bank of
3953      * the TCR being reset.
3954      */
3955     tcr->raw_tcr = 0;
3956     tcr->mask = 0;
3957     tcr->base_mask = 0xffffc000u;
3958 }
3959 
3960 static void vmsa_tcr_el12_write(CPUARMState *env, const ARMCPRegInfo *ri,
3961                                uint64_t value)
3962 {
3963     ARMCPU *cpu = env_archcpu(env);
3964     TCR *tcr = raw_ptr(env, ri);
3965 
3966     /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */
3967     tlb_flush(CPU(cpu));
3968     tcr->raw_tcr = value;
3969 }
3970 
3971 static void vmsa_ttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
3972                             uint64_t value)
3973 {
3974     /* If the ASID changes (with a 64-bit write), we must flush the TLB.  */
3975     if (cpreg_field_is_64bit(ri) &&
3976         extract64(raw_read(env, ri) ^ value, 48, 16) != 0) {
3977         ARMCPU *cpu = env_archcpu(env);
3978         tlb_flush(CPU(cpu));
3979     }
3980     raw_write(env, ri, value);
3981 }
3982 
3983 static void vmsa_tcr_ttbr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
3984                                     uint64_t value)
3985 {
3986     /*
3987      * If we are running with E2&0 regime, then an ASID is active.
3988      * Flush if that might be changing.  Note we're not checking
3989      * TCR_EL2.A1 to know if this is really the TTBRx_EL2 that
3990      * holds the active ASID, only checking the field that might.
3991      */
3992     if (extract64(raw_read(env, ri) ^ value, 48, 16) &&
3993         (arm_hcr_el2_eff(env) & HCR_E2H)) {
3994         uint16_t mask = ARMMMUIdxBit_E20_2 |
3995                         ARMMMUIdxBit_E20_2_PAN |
3996                         ARMMMUIdxBit_E20_0;
3997 
3998         if (arm_is_secure_below_el3(env)) {
3999             mask >>= ARM_MMU_IDX_A_NS;
4000         }
4001 
4002         tlb_flush_by_mmuidx(env_cpu(env), mask);
4003     }
4004     raw_write(env, ri, value);
4005 }
4006 
4007 static void vttbr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4008                         uint64_t value)
4009 {
4010     ARMCPU *cpu = env_archcpu(env);
4011     CPUState *cs = CPU(cpu);
4012 
4013     /*
4014      * A change in VMID to the stage2 page table (Stage2) invalidates
4015      * the combined stage 1&2 tlbs (EL10_1 and EL10_0).
4016      */
4017     if (raw_read(env, ri) != value) {
4018         uint16_t mask = ARMMMUIdxBit_E10_1 |
4019                         ARMMMUIdxBit_E10_1_PAN |
4020                         ARMMMUIdxBit_E10_0;
4021 
4022         if (arm_is_secure_below_el3(env)) {
4023             mask >>= ARM_MMU_IDX_A_NS;
4024         }
4025 
4026         tlb_flush_by_mmuidx(cs, mask);
4027         raw_write(env, ri, value);
4028     }
4029 }
4030 
4031 static const ARMCPRegInfo vmsa_pmsa_cp_reginfo[] = {
4032     { .name = "DFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 0,
4033       .access = PL1_RW, .accessfn = access_tvm_trvm, .type = ARM_CP_ALIAS,
4034       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dfsr_s),
4035                              offsetoflow32(CPUARMState, cp15.dfsr_ns) }, },
4036     { .name = "IFSR", .cp = 15, .crn = 5, .crm = 0, .opc1 = 0, .opc2 = 1,
4037       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4038       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.ifsr_s),
4039                              offsetoflow32(CPUARMState, cp15.ifsr_ns) } },
4040     { .name = "DFAR", .cp = 15, .opc1 = 0, .crn = 6, .crm = 0, .opc2 = 0,
4041       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
4042       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.dfar_s),
4043                              offsetof(CPUARMState, cp15.dfar_ns) } },
4044     { .name = "FAR_EL1", .state = ARM_CP_STATE_AA64,
4045       .opc0 = 3, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 0,
4046       .access = PL1_RW, .accessfn = access_tvm_trvm,
4047       .fieldoffset = offsetof(CPUARMState, cp15.far_el[1]),
4048       .resetvalue = 0, },
4049     REGINFO_SENTINEL
4050 };
4051 
4052 static const ARMCPRegInfo vmsa_cp_reginfo[] = {
4053     { .name = "ESR_EL1", .state = ARM_CP_STATE_AA64,
4054       .opc0 = 3, .crn = 5, .crm = 2, .opc1 = 0, .opc2 = 0,
4055       .access = PL1_RW, .accessfn = access_tvm_trvm,
4056       .fieldoffset = offsetof(CPUARMState, cp15.esr_el[1]), .resetvalue = 0, },
4057     { .name = "TTBR0_EL1", .state = ARM_CP_STATE_BOTH,
4058       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 0,
4059       .access = PL1_RW, .accessfn = access_tvm_trvm,
4060       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4061       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4062                              offsetof(CPUARMState, cp15.ttbr0_ns) } },
4063     { .name = "TTBR1_EL1", .state = ARM_CP_STATE_BOTH,
4064       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 1,
4065       .access = PL1_RW, .accessfn = access_tvm_trvm,
4066       .writefn = vmsa_ttbr_write, .resetvalue = 0,
4067       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4068                              offsetof(CPUARMState, cp15.ttbr1_ns) } },
4069     { .name = "TCR_EL1", .state = ARM_CP_STATE_AA64,
4070       .opc0 = 3, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4071       .access = PL1_RW, .accessfn = access_tvm_trvm,
4072       .writefn = vmsa_tcr_el12_write,
4073       .resetfn = vmsa_ttbcr_reset, .raw_writefn = raw_write,
4074       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[1]) },
4075     { .name = "TTBCR", .cp = 15, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 2,
4076       .access = PL1_RW, .accessfn = access_tvm_trvm,
4077       .type = ARM_CP_ALIAS, .writefn = vmsa_ttbcr_write,
4078       .raw_writefn = vmsa_ttbcr_raw_write,
4079       /* No offsetoflow32 -- pass the entire TCR to writefn/raw_writefn. */
4080       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.tcr_el[3]),
4081                              offsetof(CPUARMState, cp15.tcr_el[1])} },
4082     REGINFO_SENTINEL
4083 };
4084 
4085 /* Note that unlike TTBCR, writing to TTBCR2 does not require flushing
4086  * qemu tlbs nor adjusting cached masks.
4087  */
4088 static const ARMCPRegInfo ttbcr2_reginfo = {
4089     .name = "TTBCR2", .cp = 15, .opc1 = 0, .crn = 2, .crm = 0, .opc2 = 3,
4090     .access = PL1_RW, .accessfn = access_tvm_trvm,
4091     .type = ARM_CP_ALIAS,
4092     .bank_fieldoffsets = {
4093         offsetofhigh32(CPUARMState, cp15.tcr_el[3].raw_tcr),
4094         offsetofhigh32(CPUARMState, cp15.tcr_el[1].raw_tcr),
4095     },
4096 };
4097 
4098 static void omap_ticonfig_write(CPUARMState *env, const ARMCPRegInfo *ri,
4099                                 uint64_t value)
4100 {
4101     env->cp15.c15_ticonfig = value & 0xe7;
4102     /* The OS_TYPE bit in this register changes the reported CPUID! */
4103     env->cp15.c0_cpuid = (value & (1 << 5)) ?
4104         ARM_CPUID_TI915T : ARM_CPUID_TI925T;
4105 }
4106 
4107 static void omap_threadid_write(CPUARMState *env, const ARMCPRegInfo *ri,
4108                                 uint64_t value)
4109 {
4110     env->cp15.c15_threadid = value & 0xffff;
4111 }
4112 
4113 static void omap_wfi_write(CPUARMState *env, const ARMCPRegInfo *ri,
4114                            uint64_t value)
4115 {
4116     /* Wait-for-interrupt (deprecated) */
4117     cpu_interrupt(env_cpu(env), CPU_INTERRUPT_HALT);
4118 }
4119 
4120 static void omap_cachemaint_write(CPUARMState *env, const ARMCPRegInfo *ri,
4121                                   uint64_t value)
4122 {
4123     /* On OMAP there are registers indicating the max/min index of dcache lines
4124      * containing a dirty line; cache flush operations have to reset these.
4125      */
4126     env->cp15.c15_i_max = 0x000;
4127     env->cp15.c15_i_min = 0xff0;
4128 }
4129 
4130 static const ARMCPRegInfo omap_cp_reginfo[] = {
4131     { .name = "DFSR", .cp = 15, .crn = 5, .crm = CP_ANY,
4132       .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW, .type = ARM_CP_OVERRIDE,
4133       .fieldoffset = offsetoflow32(CPUARMState, cp15.esr_el[1]),
4134       .resetvalue = 0, },
4135     { .name = "", .cp = 15, .crn = 15, .crm = 0, .opc1 = 0, .opc2 = 0,
4136       .access = PL1_RW, .type = ARM_CP_NOP },
4137     { .name = "TICONFIG", .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0,
4138       .access = PL1_RW,
4139       .fieldoffset = offsetof(CPUARMState, cp15.c15_ticonfig), .resetvalue = 0,
4140       .writefn = omap_ticonfig_write },
4141     { .name = "IMAX", .cp = 15, .crn = 15, .crm = 2, .opc1 = 0, .opc2 = 0,
4142       .access = PL1_RW,
4143       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_max), .resetvalue = 0, },
4144     { .name = "IMIN", .cp = 15, .crn = 15, .crm = 3, .opc1 = 0, .opc2 = 0,
4145       .access = PL1_RW, .resetvalue = 0xff0,
4146       .fieldoffset = offsetof(CPUARMState, cp15.c15_i_min) },
4147     { .name = "THREADID", .cp = 15, .crn = 15, .crm = 4, .opc1 = 0, .opc2 = 0,
4148       .access = PL1_RW,
4149       .fieldoffset = offsetof(CPUARMState, cp15.c15_threadid), .resetvalue = 0,
4150       .writefn = omap_threadid_write },
4151     { .name = "TI925T_STATUS", .cp = 15, .crn = 15,
4152       .crm = 8, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4153       .type = ARM_CP_NO_RAW,
4154       .readfn = arm_cp_read_zero, .writefn = omap_wfi_write, },
4155     /* TODO: Peripheral port remap register:
4156      * On OMAP2 mcr p15, 0, rn, c15, c2, 4 sets up the interrupt controller
4157      * base address at $rn & ~0xfff and map size of 0x200 << ($rn & 0xfff),
4158      * when MMU is off.
4159      */
4160     { .name = "OMAP_CACHEMAINT", .cp = 15, .crn = 7, .crm = CP_ANY,
4161       .opc1 = 0, .opc2 = CP_ANY, .access = PL1_W,
4162       .type = ARM_CP_OVERRIDE | ARM_CP_NO_RAW,
4163       .writefn = omap_cachemaint_write },
4164     { .name = "C9", .cp = 15, .crn = 9,
4165       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_RW,
4166       .type = ARM_CP_CONST | ARM_CP_OVERRIDE, .resetvalue = 0 },
4167     REGINFO_SENTINEL
4168 };
4169 
4170 static void xscale_cpar_write(CPUARMState *env, const ARMCPRegInfo *ri,
4171                               uint64_t value)
4172 {
4173     env->cp15.c15_cpar = value & 0x3fff;
4174 }
4175 
4176 static const ARMCPRegInfo xscale_cp_reginfo[] = {
4177     { .name = "XSCALE_CPAR",
4178       .cp = 15, .crn = 15, .crm = 1, .opc1 = 0, .opc2 = 0, .access = PL1_RW,
4179       .fieldoffset = offsetof(CPUARMState, cp15.c15_cpar), .resetvalue = 0,
4180       .writefn = xscale_cpar_write, },
4181     { .name = "XSCALE_AUXCR",
4182       .cp = 15, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 1, .access = PL1_RW,
4183       .fieldoffset = offsetof(CPUARMState, cp15.c1_xscaleauxcr),
4184       .resetvalue = 0, },
4185     /* XScale specific cache-lockdown: since we have no cache we NOP these
4186      * and hope the guest does not really rely on cache behaviour.
4187      */
4188     { .name = "XSCALE_LOCK_ICACHE_LINE",
4189       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 0,
4190       .access = PL1_W, .type = ARM_CP_NOP },
4191     { .name = "XSCALE_UNLOCK_ICACHE",
4192       .cp = 15, .opc1 = 0, .crn = 9, .crm = 1, .opc2 = 1,
4193       .access = PL1_W, .type = ARM_CP_NOP },
4194     { .name = "XSCALE_DCACHE_LOCK",
4195       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 0,
4196       .access = PL1_RW, .type = ARM_CP_NOP },
4197     { .name = "XSCALE_UNLOCK_DCACHE",
4198       .cp = 15, .opc1 = 0, .crn = 9, .crm = 2, .opc2 = 1,
4199       .access = PL1_W, .type = ARM_CP_NOP },
4200     REGINFO_SENTINEL
4201 };
4202 
4203 static const ARMCPRegInfo dummy_c15_cp_reginfo[] = {
4204     /* RAZ/WI the whole crn=15 space, when we don't have a more specific
4205      * implementation of this implementation-defined space.
4206      * Ideally this should eventually disappear in favour of actually
4207      * implementing the correct behaviour for all cores.
4208      */
4209     { .name = "C15_IMPDEF", .cp = 15, .crn = 15,
4210       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4211       .access = PL1_RW,
4212       .type = ARM_CP_CONST | ARM_CP_NO_RAW | ARM_CP_OVERRIDE,
4213       .resetvalue = 0 },
4214     REGINFO_SENTINEL
4215 };
4216 
4217 static const ARMCPRegInfo cache_dirty_status_cp_reginfo[] = {
4218     /* Cache status: RAZ because we have no cache so it's always clean */
4219     { .name = "CDSR", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 6,
4220       .access = PL1_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4221       .resetvalue = 0 },
4222     REGINFO_SENTINEL
4223 };
4224 
4225 static const ARMCPRegInfo cache_block_ops_cp_reginfo[] = {
4226     /* We never have a a block transfer operation in progress */
4227     { .name = "BXSR", .cp = 15, .crn = 7, .crm = 12, .opc1 = 0, .opc2 = 4,
4228       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4229       .resetvalue = 0 },
4230     /* The cache ops themselves: these all NOP for QEMU */
4231     { .name = "IICR", .cp = 15, .crm = 5, .opc1 = 0,
4232       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4233     { .name = "IDCR", .cp = 15, .crm = 6, .opc1 = 0,
4234       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4235     { .name = "CDCR", .cp = 15, .crm = 12, .opc1 = 0,
4236       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4237     { .name = "PIR", .cp = 15, .crm = 12, .opc1 = 1,
4238       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4239     { .name = "PDR", .cp = 15, .crm = 12, .opc1 = 2,
4240       .access = PL0_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4241     { .name = "CIDCR", .cp = 15, .crm = 14, .opc1 = 0,
4242       .access = PL1_W, .type = ARM_CP_NOP|ARM_CP_64BIT },
4243     REGINFO_SENTINEL
4244 };
4245 
4246 static const ARMCPRegInfo cache_test_clean_cp_reginfo[] = {
4247     /* The cache test-and-clean instructions always return (1 << 30)
4248      * to indicate that there are no dirty cache lines.
4249      */
4250     { .name = "TC_DCACHE", .cp = 15, .crn = 7, .crm = 10, .opc1 = 0, .opc2 = 3,
4251       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4252       .resetvalue = (1 << 30) },
4253     { .name = "TCI_DCACHE", .cp = 15, .crn = 7, .crm = 14, .opc1 = 0, .opc2 = 3,
4254       .access = PL0_R, .type = ARM_CP_CONST | ARM_CP_NO_RAW,
4255       .resetvalue = (1 << 30) },
4256     REGINFO_SENTINEL
4257 };
4258 
4259 static const ARMCPRegInfo strongarm_cp_reginfo[] = {
4260     /* Ignore ReadBuffer accesses */
4261     { .name = "C9_READBUFFER", .cp = 15, .crn = 9,
4262       .crm = CP_ANY, .opc1 = CP_ANY, .opc2 = CP_ANY,
4263       .access = PL1_RW, .resetvalue = 0,
4264       .type = ARM_CP_CONST | ARM_CP_OVERRIDE | ARM_CP_NO_RAW },
4265     REGINFO_SENTINEL
4266 };
4267 
4268 static uint64_t midr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4269 {
4270     unsigned int cur_el = arm_current_el(env);
4271 
4272     if (arm_is_el2_enabled(env) && cur_el == 1) {
4273         return env->cp15.vpidr_el2;
4274     }
4275     return raw_read(env, ri);
4276 }
4277 
4278 static uint64_t mpidr_read_val(CPUARMState *env)
4279 {
4280     ARMCPU *cpu = env_archcpu(env);
4281     uint64_t mpidr = cpu->mp_affinity;
4282 
4283     if (arm_feature(env, ARM_FEATURE_V7MP)) {
4284         mpidr |= (1U << 31);
4285         /* Cores which are uniprocessor (non-coherent)
4286          * but still implement the MP extensions set
4287          * bit 30. (For instance, Cortex-R5).
4288          */
4289         if (cpu->mp_is_up) {
4290             mpidr |= (1u << 30);
4291         }
4292     }
4293     return mpidr;
4294 }
4295 
4296 static uint64_t mpidr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4297 {
4298     unsigned int cur_el = arm_current_el(env);
4299 
4300     if (arm_is_el2_enabled(env) && cur_el == 1) {
4301         return env->cp15.vmpidr_el2;
4302     }
4303     return mpidr_read_val(env);
4304 }
4305 
4306 static const ARMCPRegInfo lpae_cp_reginfo[] = {
4307     /* NOP AMAIR0/1 */
4308     { .name = "AMAIR0", .state = ARM_CP_STATE_BOTH,
4309       .opc0 = 3, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 0,
4310       .access = PL1_RW, .accessfn = access_tvm_trvm,
4311       .type = ARM_CP_CONST, .resetvalue = 0 },
4312     /* AMAIR1 is mapped to AMAIR_EL1[63:32] */
4313     { .name = "AMAIR1", .cp = 15, .crn = 10, .crm = 3, .opc1 = 0, .opc2 = 1,
4314       .access = PL1_RW, .accessfn = access_tvm_trvm,
4315       .type = ARM_CP_CONST, .resetvalue = 0 },
4316     { .name = "PAR", .cp = 15, .crm = 7, .opc1 = 0,
4317       .access = PL1_RW, .type = ARM_CP_64BIT, .resetvalue = 0,
4318       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.par_s),
4319                              offsetof(CPUARMState, cp15.par_ns)} },
4320     { .name = "TTBR0", .cp = 15, .crm = 2, .opc1 = 0,
4321       .access = PL1_RW, .accessfn = access_tvm_trvm,
4322       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4323       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr0_s),
4324                              offsetof(CPUARMState, cp15.ttbr0_ns) },
4325       .writefn = vmsa_ttbr_write, },
4326     { .name = "TTBR1", .cp = 15, .crm = 2, .opc1 = 1,
4327       .access = PL1_RW, .accessfn = access_tvm_trvm,
4328       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
4329       .bank_fieldoffsets = { offsetof(CPUARMState, cp15.ttbr1_s),
4330                              offsetof(CPUARMState, cp15.ttbr1_ns) },
4331       .writefn = vmsa_ttbr_write, },
4332     REGINFO_SENTINEL
4333 };
4334 
4335 static uint64_t aa64_fpcr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4336 {
4337     return vfp_get_fpcr(env);
4338 }
4339 
4340 static void aa64_fpcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4341                             uint64_t value)
4342 {
4343     vfp_set_fpcr(env, value);
4344 }
4345 
4346 static uint64_t aa64_fpsr_read(CPUARMState *env, const ARMCPRegInfo *ri)
4347 {
4348     return vfp_get_fpsr(env);
4349 }
4350 
4351 static void aa64_fpsr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4352                             uint64_t value)
4353 {
4354     vfp_set_fpsr(env, value);
4355 }
4356 
4357 static CPAccessResult aa64_daif_access(CPUARMState *env, const ARMCPRegInfo *ri,
4358                                        bool isread)
4359 {
4360     if (arm_current_el(env) == 0 && !(arm_sctlr(env, 0) & SCTLR_UMA)) {
4361         return CP_ACCESS_TRAP;
4362     }
4363     return CP_ACCESS_OK;
4364 }
4365 
4366 static void aa64_daif_write(CPUARMState *env, const ARMCPRegInfo *ri,
4367                             uint64_t value)
4368 {
4369     env->daif = value & PSTATE_DAIF;
4370 }
4371 
4372 static uint64_t aa64_pan_read(CPUARMState *env, const ARMCPRegInfo *ri)
4373 {
4374     return env->pstate & PSTATE_PAN;
4375 }
4376 
4377 static void aa64_pan_write(CPUARMState *env, const ARMCPRegInfo *ri,
4378                            uint64_t value)
4379 {
4380     env->pstate = (env->pstate & ~PSTATE_PAN) | (value & PSTATE_PAN);
4381 }
4382 
4383 static const ARMCPRegInfo pan_reginfo = {
4384     .name = "PAN", .state = ARM_CP_STATE_AA64,
4385     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 3,
4386     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4387     .readfn = aa64_pan_read, .writefn = aa64_pan_write
4388 };
4389 
4390 static uint64_t aa64_uao_read(CPUARMState *env, const ARMCPRegInfo *ri)
4391 {
4392     return env->pstate & PSTATE_UAO;
4393 }
4394 
4395 static void aa64_uao_write(CPUARMState *env, const ARMCPRegInfo *ri,
4396                            uint64_t value)
4397 {
4398     env->pstate = (env->pstate & ~PSTATE_UAO) | (value & PSTATE_UAO);
4399 }
4400 
4401 static const ARMCPRegInfo uao_reginfo = {
4402     .name = "UAO", .state = ARM_CP_STATE_AA64,
4403     .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 4,
4404     .type = ARM_CP_NO_RAW, .access = PL1_RW,
4405     .readfn = aa64_uao_read, .writefn = aa64_uao_write
4406 };
4407 
4408 static uint64_t aa64_dit_read(CPUARMState *env, const ARMCPRegInfo *ri)
4409 {
4410     return env->pstate & PSTATE_DIT;
4411 }
4412 
4413 static void aa64_dit_write(CPUARMState *env, const ARMCPRegInfo *ri,
4414                            uint64_t value)
4415 {
4416     env->pstate = (env->pstate & ~PSTATE_DIT) | (value & PSTATE_DIT);
4417 }
4418 
4419 static const ARMCPRegInfo dit_reginfo = {
4420     .name = "DIT", .state = ARM_CP_STATE_AA64,
4421     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 5,
4422     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4423     .readfn = aa64_dit_read, .writefn = aa64_dit_write
4424 };
4425 
4426 static uint64_t aa64_ssbs_read(CPUARMState *env, const ARMCPRegInfo *ri)
4427 {
4428     return env->pstate & PSTATE_SSBS;
4429 }
4430 
4431 static void aa64_ssbs_write(CPUARMState *env, const ARMCPRegInfo *ri,
4432                            uint64_t value)
4433 {
4434     env->pstate = (env->pstate & ~PSTATE_SSBS) | (value & PSTATE_SSBS);
4435 }
4436 
4437 static const ARMCPRegInfo ssbs_reginfo = {
4438     .name = "SSBS", .state = ARM_CP_STATE_AA64,
4439     .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 6,
4440     .type = ARM_CP_NO_RAW, .access = PL0_RW,
4441     .readfn = aa64_ssbs_read, .writefn = aa64_ssbs_write
4442 };
4443 
4444 static CPAccessResult aa64_cacheop_poc_access(CPUARMState *env,
4445                                               const ARMCPRegInfo *ri,
4446                                               bool isread)
4447 {
4448     /* Cache invalidate/clean to Point of Coherency or Persistence...  */
4449     switch (arm_current_el(env)) {
4450     case 0:
4451         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4452         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4453             return CP_ACCESS_TRAP;
4454         }
4455         /* fall through */
4456     case 1:
4457         /* ... EL1 must trap to EL2 if HCR_EL2.TPCP is set.  */
4458         if (arm_hcr_el2_eff(env) & HCR_TPCP) {
4459             return CP_ACCESS_TRAP_EL2;
4460         }
4461         break;
4462     }
4463     return CP_ACCESS_OK;
4464 }
4465 
4466 static CPAccessResult aa64_cacheop_pou_access(CPUARMState *env,
4467                                               const ARMCPRegInfo *ri,
4468                                               bool isread)
4469 {
4470     /* Cache invalidate/clean to Point of Unification... */
4471     switch (arm_current_el(env)) {
4472     case 0:
4473         /* ... EL0 must UNDEF unless SCTLR_EL1.UCI is set.  */
4474         if (!(arm_sctlr(env, 0) & SCTLR_UCI)) {
4475             return CP_ACCESS_TRAP;
4476         }
4477         /* fall through */
4478     case 1:
4479         /* ... EL1 must trap to EL2 if HCR_EL2.TPU is set.  */
4480         if (arm_hcr_el2_eff(env) & HCR_TPU) {
4481             return CP_ACCESS_TRAP_EL2;
4482         }
4483         break;
4484     }
4485     return CP_ACCESS_OK;
4486 }
4487 
4488 /* See: D4.7.2 TLB maintenance requirements and the TLB maintenance instructions
4489  * Page D4-1736 (DDI0487A.b)
4490  */
4491 
4492 static int vae1_tlbmask(CPUARMState *env)
4493 {
4494     uint64_t hcr = arm_hcr_el2_eff(env);
4495     uint16_t mask;
4496 
4497     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4498         mask = ARMMMUIdxBit_E20_2 |
4499                ARMMMUIdxBit_E20_2_PAN |
4500                ARMMMUIdxBit_E20_0;
4501     } else {
4502         mask = ARMMMUIdxBit_E10_1 |
4503                ARMMMUIdxBit_E10_1_PAN |
4504                ARMMMUIdxBit_E10_0;
4505     }
4506 
4507     if (arm_is_secure_below_el3(env)) {
4508         mask >>= ARM_MMU_IDX_A_NS;
4509     }
4510 
4511     return mask;
4512 }
4513 
4514 /* Return 56 if TBI is enabled, 64 otherwise. */
4515 static int tlbbits_for_regime(CPUARMState *env, ARMMMUIdx mmu_idx,
4516                               uint64_t addr)
4517 {
4518     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
4519     int tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
4520     int select = extract64(addr, 55, 1);
4521 
4522     return (tbi >> select) & 1 ? 56 : 64;
4523 }
4524 
4525 static int vae1_tlbbits(CPUARMState *env, uint64_t addr)
4526 {
4527     uint64_t hcr = arm_hcr_el2_eff(env);
4528     ARMMMUIdx mmu_idx;
4529 
4530     /* Only the regime of the mmu_idx below is significant. */
4531     if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4532         mmu_idx = ARMMMUIdx_E20_0;
4533     } else {
4534         mmu_idx = ARMMMUIdx_E10_0;
4535     }
4536 
4537     if (arm_is_secure_below_el3(env)) {
4538         mmu_idx &= ~ARM_MMU_IDX_A_NS;
4539     }
4540 
4541     return tlbbits_for_regime(env, mmu_idx, addr);
4542 }
4543 
4544 static void tlbi_aa64_vmalle1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4545                                       uint64_t value)
4546 {
4547     CPUState *cs = env_cpu(env);
4548     int mask = vae1_tlbmask(env);
4549 
4550     tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4551 }
4552 
4553 static void tlbi_aa64_vmalle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4554                                     uint64_t value)
4555 {
4556     CPUState *cs = env_cpu(env);
4557     int mask = vae1_tlbmask(env);
4558 
4559     if (tlb_force_broadcast(env)) {
4560         tlb_flush_by_mmuidx_all_cpus_synced(cs, mask);
4561     } else {
4562         tlb_flush_by_mmuidx(cs, mask);
4563     }
4564 }
4565 
4566 static int alle1_tlbmask(CPUARMState *env)
4567 {
4568     /*
4569      * Note that the 'ALL' scope must invalidate both stage 1 and
4570      * stage 2 translations, whereas most other scopes only invalidate
4571      * stage 1 translations.
4572      */
4573     if (arm_is_secure_below_el3(env)) {
4574         return ARMMMUIdxBit_SE10_1 |
4575                ARMMMUIdxBit_SE10_1_PAN |
4576                ARMMMUIdxBit_SE10_0;
4577     } else {
4578         return ARMMMUIdxBit_E10_1 |
4579                ARMMMUIdxBit_E10_1_PAN |
4580                ARMMMUIdxBit_E10_0;
4581     }
4582 }
4583 
4584 static int e2_tlbmask(CPUARMState *env)
4585 {
4586     if (arm_is_secure_below_el3(env)) {
4587         return ARMMMUIdxBit_SE20_0 |
4588                ARMMMUIdxBit_SE20_2 |
4589                ARMMMUIdxBit_SE20_2_PAN |
4590                ARMMMUIdxBit_SE2;
4591     } else {
4592         return ARMMMUIdxBit_E20_0 |
4593                ARMMMUIdxBit_E20_2 |
4594                ARMMMUIdxBit_E20_2_PAN |
4595                ARMMMUIdxBit_E2;
4596     }
4597 }
4598 
4599 static void tlbi_aa64_alle1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4600                                   uint64_t value)
4601 {
4602     CPUState *cs = env_cpu(env);
4603     int mask = alle1_tlbmask(env);
4604 
4605     tlb_flush_by_mmuidx(cs, mask);
4606 }
4607 
4608 static void tlbi_aa64_alle2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4609                                   uint64_t value)
4610 {
4611     CPUState *cs = env_cpu(env);
4612     int mask = e2_tlbmask(env);
4613 
4614     tlb_flush_by_mmuidx(cs, mask);
4615 }
4616 
4617 static void tlbi_aa64_alle3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4618                                   uint64_t value)
4619 {
4620     ARMCPU *cpu = env_archcpu(env);
4621     CPUState *cs = CPU(cpu);
4622 
4623     tlb_flush_by_mmuidx(cs, ARMMMUIdxBit_SE3);
4624 }
4625 
4626 static void tlbi_aa64_alle1is_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_all_cpus_synced(cs, mask);
4633 }
4634 
4635 static void tlbi_aa64_alle2is_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_all_cpus_synced(cs, mask);
4642 }
4643 
4644 static void tlbi_aa64_alle3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4645                                     uint64_t value)
4646 {
4647     CPUState *cs = env_cpu(env);
4648 
4649     tlb_flush_by_mmuidx_all_cpus_synced(cs, ARMMMUIdxBit_SE3);
4650 }
4651 
4652 static void tlbi_aa64_vae2_write(CPUARMState *env, const ARMCPRegInfo *ri,
4653                                  uint64_t value)
4654 {
4655     /* Invalidate by VA, EL2
4656      * Currently handles both VAE2 and VALE2, since we don't support
4657      * flush-last-level-only.
4658      */
4659     CPUState *cs = env_cpu(env);
4660     int mask = e2_tlbmask(env);
4661     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4662 
4663     tlb_flush_page_by_mmuidx(cs, pageaddr, mask);
4664 }
4665 
4666 static void tlbi_aa64_vae3_write(CPUARMState *env, const ARMCPRegInfo *ri,
4667                                  uint64_t value)
4668 {
4669     /* Invalidate by VA, EL3
4670      * Currently handles both VAE3 and VALE3, since we don't support
4671      * flush-last-level-only.
4672      */
4673     ARMCPU *cpu = env_archcpu(env);
4674     CPUState *cs = CPU(cpu);
4675     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4676 
4677     tlb_flush_page_by_mmuidx(cs, pageaddr, ARMMMUIdxBit_SE3);
4678 }
4679 
4680 static void tlbi_aa64_vae1is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4681                                    uint64_t value)
4682 {
4683     CPUState *cs = env_cpu(env);
4684     int mask = vae1_tlbmask(env);
4685     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4686     int bits = vae1_tlbbits(env, pageaddr);
4687 
4688     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4689 }
4690 
4691 static void tlbi_aa64_vae1_write(CPUARMState *env, const ARMCPRegInfo *ri,
4692                                  uint64_t value)
4693 {
4694     /* Invalidate by VA, EL1&0 (AArch64 version).
4695      * Currently handles all of VAE1, VAAE1, VAALE1 and VALE1,
4696      * since we don't support flush-for-specific-ASID-only or
4697      * flush-last-level-only.
4698      */
4699     CPUState *cs = env_cpu(env);
4700     int mask = vae1_tlbmask(env);
4701     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4702     int bits = vae1_tlbbits(env, pageaddr);
4703 
4704     if (tlb_force_broadcast(env)) {
4705         tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4706     } else {
4707         tlb_flush_page_bits_by_mmuidx(cs, pageaddr, mask, bits);
4708     }
4709 }
4710 
4711 static void tlbi_aa64_vae2is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4712                                    uint64_t value)
4713 {
4714     CPUState *cs = env_cpu(env);
4715     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4716     bool secure = arm_is_secure_below_el3(env);
4717     int mask = secure ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2;
4718     int bits = tlbbits_for_regime(env, secure ? ARMMMUIdx_SE2 : ARMMMUIdx_E2,
4719                                   pageaddr);
4720 
4721     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr, mask, bits);
4722 }
4723 
4724 static void tlbi_aa64_vae3is_write(CPUARMState *env, const ARMCPRegInfo *ri,
4725                                    uint64_t value)
4726 {
4727     CPUState *cs = env_cpu(env);
4728     uint64_t pageaddr = sextract64(value << 12, 0, 56);
4729     int bits = tlbbits_for_regime(env, ARMMMUIdx_SE3, pageaddr);
4730 
4731     tlb_flush_page_bits_by_mmuidx_all_cpus_synced(cs, pageaddr,
4732                                                   ARMMMUIdxBit_SE3, bits);
4733 }
4734 
4735 #ifdef TARGET_AARCH64
4736 static uint64_t tlbi_aa64_range_get_length(CPUARMState *env,
4737                                            uint64_t value)
4738 {
4739     unsigned int page_shift;
4740     unsigned int page_size_granule;
4741     uint64_t num;
4742     uint64_t scale;
4743     uint64_t exponent;
4744     uint64_t length;
4745 
4746     num = extract64(value, 39, 4);
4747     scale = extract64(value, 44, 2);
4748     page_size_granule = extract64(value, 46, 2);
4749 
4750     page_shift = page_size_granule * 2 + 12;
4751 
4752     if (page_size_granule == 0) {
4753         qemu_log_mask(LOG_GUEST_ERROR, "Invalid page size granule %d\n",
4754                       page_size_granule);
4755         return 0;
4756     }
4757 
4758     exponent = (5 * scale) + 1;
4759     length = (num + 1) << (exponent + page_shift);
4760 
4761     return length;
4762 }
4763 
4764 static uint64_t tlbi_aa64_range_get_base(CPUARMState *env, uint64_t value,
4765                                         bool two_ranges)
4766 {
4767     /* TODO: ARMv8.7 FEAT_LPA2 */
4768     uint64_t pageaddr;
4769 
4770     if (two_ranges) {
4771         pageaddr = sextract64(value, 0, 37) << TARGET_PAGE_BITS;
4772     } else {
4773         pageaddr = extract64(value, 0, 37) << TARGET_PAGE_BITS;
4774     }
4775 
4776     return pageaddr;
4777 }
4778 
4779 static void do_rvae_write(CPUARMState *env, uint64_t value,
4780                           int idxmap, bool synced)
4781 {
4782     ARMMMUIdx one_idx = ARM_MMU_IDX_A | ctz32(idxmap);
4783     bool two_ranges = regime_has_2_ranges(one_idx);
4784     uint64_t baseaddr, length;
4785     int bits;
4786 
4787     baseaddr = tlbi_aa64_range_get_base(env, value, two_ranges);
4788     length = tlbi_aa64_range_get_length(env, value);
4789     bits = tlbbits_for_regime(env, one_idx, baseaddr);
4790 
4791     if (synced) {
4792         tlb_flush_range_by_mmuidx_all_cpus_synced(env_cpu(env),
4793                                                   baseaddr,
4794                                                   length,
4795                                                   idxmap,
4796                                                   bits);
4797     } else {
4798         tlb_flush_range_by_mmuidx(env_cpu(env), baseaddr,
4799                                   length, idxmap, bits);
4800     }
4801 }
4802 
4803 static void tlbi_aa64_rvae1_write(CPUARMState *env,
4804                                   const ARMCPRegInfo *ri,
4805                                   uint64_t value)
4806 {
4807     /*
4808      * Invalidate by VA range, EL1&0.
4809      * Currently handles all of RVAE1, RVAAE1, RVAALE1 and RVALE1,
4810      * since we don't support flush-for-specific-ASID-only or
4811      * flush-last-level-only.
4812      */
4813 
4814     do_rvae_write(env, value, vae1_tlbmask(env),
4815                   tlb_force_broadcast(env));
4816 }
4817 
4818 static void tlbi_aa64_rvae1is_write(CPUARMState *env,
4819                                     const ARMCPRegInfo *ri,
4820                                     uint64_t value)
4821 {
4822     /*
4823      * Invalidate by VA range, Inner/Outer Shareable EL1&0.
4824      * Currently handles all of RVAE1IS, RVAE1OS, RVAAE1IS, RVAAE1OS,
4825      * RVAALE1IS, RVAALE1OS, RVALE1IS and RVALE1OS, since we don't support
4826      * flush-for-specific-ASID-only, flush-last-level-only or inner/outer
4827      * shareable specific flushes.
4828      */
4829 
4830     do_rvae_write(env, value, vae1_tlbmask(env), true);
4831 }
4832 
4833 static int vae2_tlbmask(CPUARMState *env)
4834 {
4835     return (arm_is_secure_below_el3(env)
4836             ? ARMMMUIdxBit_SE2 : ARMMMUIdxBit_E2);
4837 }
4838 
4839 static void tlbi_aa64_rvae2_write(CPUARMState *env,
4840                                   const ARMCPRegInfo *ri,
4841                                   uint64_t value)
4842 {
4843     /*
4844      * Invalidate by VA range, EL2.
4845      * Currently handles all of RVAE2 and RVALE2,
4846      * since we don't support flush-for-specific-ASID-only or
4847      * flush-last-level-only.
4848      */
4849 
4850     do_rvae_write(env, value, vae2_tlbmask(env),
4851                   tlb_force_broadcast(env));
4852 
4853 
4854 }
4855 
4856 static void tlbi_aa64_rvae2is_write(CPUARMState *env,
4857                                     const ARMCPRegInfo *ri,
4858                                     uint64_t value)
4859 {
4860     /*
4861      * Invalidate by VA range, Inner/Outer Shareable, EL2.
4862      * Currently handles all of RVAE2IS, RVAE2OS, RVALE2IS and RVALE2OS,
4863      * since we don't support flush-for-specific-ASID-only,
4864      * flush-last-level-only or inner/outer shareable specific flushes.
4865      */
4866 
4867     do_rvae_write(env, value, vae2_tlbmask(env), true);
4868 
4869 }
4870 
4871 static void tlbi_aa64_rvae3_write(CPUARMState *env,
4872                                   const ARMCPRegInfo *ri,
4873                                   uint64_t value)
4874 {
4875     /*
4876      * Invalidate by VA range, EL3.
4877      * Currently handles all of RVAE3 and RVALE3,
4878      * since we don't support flush-for-specific-ASID-only or
4879      * flush-last-level-only.
4880      */
4881 
4882     do_rvae_write(env, value, ARMMMUIdxBit_SE3,
4883                   tlb_force_broadcast(env));
4884 }
4885 
4886 static void tlbi_aa64_rvae3is_write(CPUARMState *env,
4887                                     const ARMCPRegInfo *ri,
4888                                     uint64_t value)
4889 {
4890     /*
4891      * Invalidate by VA range, EL3, Inner/Outer Shareable.
4892      * Currently handles all of RVAE3IS, RVAE3OS, RVALE3IS and RVALE3OS,
4893      * since we don't support flush-for-specific-ASID-only,
4894      * flush-last-level-only or inner/outer specific flushes.
4895      */
4896 
4897     do_rvae_write(env, value, ARMMMUIdxBit_SE3, true);
4898 }
4899 #endif
4900 
4901 static CPAccessResult aa64_zva_access(CPUARMState *env, const ARMCPRegInfo *ri,
4902                                       bool isread)
4903 {
4904     int cur_el = arm_current_el(env);
4905 
4906     if (cur_el < 2) {
4907         uint64_t hcr = arm_hcr_el2_eff(env);
4908 
4909         if (cur_el == 0) {
4910             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
4911                 if (!(env->cp15.sctlr_el[2] & SCTLR_DZE)) {
4912                     return CP_ACCESS_TRAP_EL2;
4913                 }
4914             } else {
4915                 if (!(env->cp15.sctlr_el[1] & SCTLR_DZE)) {
4916                     return CP_ACCESS_TRAP;
4917                 }
4918                 if (hcr & HCR_TDZ) {
4919                     return CP_ACCESS_TRAP_EL2;
4920                 }
4921             }
4922         } else if (hcr & HCR_TDZ) {
4923             return CP_ACCESS_TRAP_EL2;
4924         }
4925     }
4926     return CP_ACCESS_OK;
4927 }
4928 
4929 static uint64_t aa64_dczid_read(CPUARMState *env, const ARMCPRegInfo *ri)
4930 {
4931     ARMCPU *cpu = env_archcpu(env);
4932     int dzp_bit = 1 << 4;
4933 
4934     /* DZP indicates whether DC ZVA access is allowed */
4935     if (aa64_zva_access(env, NULL, false) == CP_ACCESS_OK) {
4936         dzp_bit = 0;
4937     }
4938     return cpu->dcz_blocksize | dzp_bit;
4939 }
4940 
4941 static CPAccessResult sp_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
4942                                     bool isread)
4943 {
4944     if (!(env->pstate & PSTATE_SP)) {
4945         /* Access to SP_EL0 is undefined if it's being used as
4946          * the stack pointer.
4947          */
4948         return CP_ACCESS_TRAP_UNCATEGORIZED;
4949     }
4950     return CP_ACCESS_OK;
4951 }
4952 
4953 static uint64_t spsel_read(CPUARMState *env, const ARMCPRegInfo *ri)
4954 {
4955     return env->pstate & PSTATE_SP;
4956 }
4957 
4958 static void spsel_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
4959 {
4960     update_spsel(env, val);
4961 }
4962 
4963 static void sctlr_write(CPUARMState *env, const ARMCPRegInfo *ri,
4964                         uint64_t value)
4965 {
4966     ARMCPU *cpu = env_archcpu(env);
4967 
4968     if (arm_feature(env, ARM_FEATURE_PMSA) && !cpu->has_mpu) {
4969         /* M bit is RAZ/WI for PMSA with no MPU implemented */
4970         value &= ~SCTLR_M;
4971     }
4972 
4973     /* ??? Lots of these bits are not implemented.  */
4974 
4975     if (ri->state == ARM_CP_STATE_AA64 && !cpu_isar_feature(aa64_mte, cpu)) {
4976         if (ri->opc1 == 6) { /* SCTLR_EL3 */
4977             value &= ~(SCTLR_ITFSB | SCTLR_TCF | SCTLR_ATA);
4978         } else {
4979             value &= ~(SCTLR_ITFSB | SCTLR_TCF0 | SCTLR_TCF |
4980                        SCTLR_ATA0 | SCTLR_ATA);
4981         }
4982     }
4983 
4984     if (raw_read(env, ri) == value) {
4985         /* Skip the TLB flush if nothing actually changed; Linux likes
4986          * to do a lot of pointless SCTLR writes.
4987          */
4988         return;
4989     }
4990 
4991     raw_write(env, ri, value);
4992 
4993     /* This may enable/disable the MMU, so do a TLB flush.  */
4994     tlb_flush(CPU(cpu));
4995 
4996     if (ri->type & ARM_CP_SUPPRESS_TB_END) {
4997         /*
4998          * Normally we would always end the TB on an SCTLR write; see the
4999          * comment in ARMCPRegInfo sctlr initialization below for why Xscale
5000          * is special.  Setting ARM_CP_SUPPRESS_TB_END also stops the rebuild
5001          * of hflags from the translator, so do it here.
5002          */
5003         arm_rebuild_hflags(env);
5004     }
5005 }
5006 
5007 static CPAccessResult fpexc32_access(CPUARMState *env, const ARMCPRegInfo *ri,
5008                                      bool isread)
5009 {
5010     if ((env->cp15.cptr_el[2] & CPTR_TFP) && arm_current_el(env) == 2) {
5011         return CP_ACCESS_TRAP_FP_EL2;
5012     }
5013     if (env->cp15.cptr_el[3] & CPTR_TFP) {
5014         return CP_ACCESS_TRAP_FP_EL3;
5015     }
5016     return CP_ACCESS_OK;
5017 }
5018 
5019 static void sdcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
5020                        uint64_t value)
5021 {
5022     env->cp15.mdcr_el3 = value & SDCR_VALID_MASK;
5023 }
5024 
5025 static const ARMCPRegInfo v8_cp_reginfo[] = {
5026     /* Minimal set of EL0-visible registers. This will need to be expanded
5027      * significantly for system emulation of AArch64 CPUs.
5028      */
5029     { .name = "NZCV", .state = ARM_CP_STATE_AA64,
5030       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 2,
5031       .access = PL0_RW, .type = ARM_CP_NZCV },
5032     { .name = "DAIF", .state = ARM_CP_STATE_AA64,
5033       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 2,
5034       .type = ARM_CP_NO_RAW,
5035       .access = PL0_RW, .accessfn = aa64_daif_access,
5036       .fieldoffset = offsetof(CPUARMState, daif),
5037       .writefn = aa64_daif_write, .resetfn = arm_cp_reset_ignore },
5038     { .name = "FPCR", .state = ARM_CP_STATE_AA64,
5039       .opc0 = 3, .opc1 = 3, .opc2 = 0, .crn = 4, .crm = 4,
5040       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
5041       .readfn = aa64_fpcr_read, .writefn = aa64_fpcr_write },
5042     { .name = "FPSR", .state = ARM_CP_STATE_AA64,
5043       .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 4, .crm = 4,
5044       .access = PL0_RW, .type = ARM_CP_FPU | ARM_CP_SUPPRESS_TB_END,
5045       .readfn = aa64_fpsr_read, .writefn = aa64_fpsr_write },
5046     { .name = "DCZID_EL0", .state = ARM_CP_STATE_AA64,
5047       .opc0 = 3, .opc1 = 3, .opc2 = 7, .crn = 0, .crm = 0,
5048       .access = PL0_R, .type = ARM_CP_NO_RAW,
5049       .readfn = aa64_dczid_read },
5050     { .name = "DC_ZVA", .state = ARM_CP_STATE_AA64,
5051       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 1,
5052       .access = PL0_W, .type = ARM_CP_DC_ZVA,
5053 #ifndef CONFIG_USER_ONLY
5054       /* Avoid overhead of an access check that always passes in user-mode */
5055       .accessfn = aa64_zva_access,
5056 #endif
5057     },
5058     { .name = "CURRENTEL", .state = ARM_CP_STATE_AA64,
5059       .opc0 = 3, .opc1 = 0, .opc2 = 2, .crn = 4, .crm = 2,
5060       .access = PL1_R, .type = ARM_CP_CURRENTEL },
5061     /* Cache ops: all NOPs since we don't emulate caches */
5062     { .name = "IC_IALLUIS", .state = ARM_CP_STATE_AA64,
5063       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5064       .access = PL1_W, .type = ARM_CP_NOP,
5065       .accessfn = aa64_cacheop_pou_access },
5066     { .name = "IC_IALLU", .state = ARM_CP_STATE_AA64,
5067       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5068       .access = PL1_W, .type = ARM_CP_NOP,
5069       .accessfn = aa64_cacheop_pou_access },
5070     { .name = "IC_IVAU", .state = ARM_CP_STATE_AA64,
5071       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 5, .opc2 = 1,
5072       .access = PL0_W, .type = ARM_CP_NOP,
5073       .accessfn = aa64_cacheop_pou_access },
5074     { .name = "DC_IVAC", .state = ARM_CP_STATE_AA64,
5075       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5076       .access = PL1_W, .accessfn = aa64_cacheop_poc_access,
5077       .type = ARM_CP_NOP },
5078     { .name = "DC_ISW", .state = ARM_CP_STATE_AA64,
5079       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5080       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
5081     { .name = "DC_CVAC", .state = ARM_CP_STATE_AA64,
5082       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 1,
5083       .access = PL0_W, .type = ARM_CP_NOP,
5084       .accessfn = aa64_cacheop_poc_access },
5085     { .name = "DC_CSW", .state = ARM_CP_STATE_AA64,
5086       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5087       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
5088     { .name = "DC_CVAU", .state = ARM_CP_STATE_AA64,
5089       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 11, .opc2 = 1,
5090       .access = PL0_W, .type = ARM_CP_NOP,
5091       .accessfn = aa64_cacheop_pou_access },
5092     { .name = "DC_CIVAC", .state = ARM_CP_STATE_AA64,
5093       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 1,
5094       .access = PL0_W, .type = ARM_CP_NOP,
5095       .accessfn = aa64_cacheop_poc_access },
5096     { .name = "DC_CISW", .state = ARM_CP_STATE_AA64,
5097       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5098       .access = PL1_W, .accessfn = access_tsw, .type = ARM_CP_NOP },
5099     /* TLBI operations */
5100     { .name = "TLBI_VMALLE1IS", .state = ARM_CP_STATE_AA64,
5101       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 0,
5102       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5103       .writefn = tlbi_aa64_vmalle1is_write },
5104     { .name = "TLBI_VAE1IS", .state = ARM_CP_STATE_AA64,
5105       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 1,
5106       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5107       .writefn = tlbi_aa64_vae1is_write },
5108     { .name = "TLBI_ASIDE1IS", .state = ARM_CP_STATE_AA64,
5109       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 2,
5110       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5111       .writefn = tlbi_aa64_vmalle1is_write },
5112     { .name = "TLBI_VAAE1IS", .state = ARM_CP_STATE_AA64,
5113       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 3,
5114       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5115       .writefn = tlbi_aa64_vae1is_write },
5116     { .name = "TLBI_VALE1IS", .state = ARM_CP_STATE_AA64,
5117       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
5118       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5119       .writefn = tlbi_aa64_vae1is_write },
5120     { .name = "TLBI_VAALE1IS", .state = ARM_CP_STATE_AA64,
5121       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
5122       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5123       .writefn = tlbi_aa64_vae1is_write },
5124     { .name = "TLBI_VMALLE1", .state = ARM_CP_STATE_AA64,
5125       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 0,
5126       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5127       .writefn = tlbi_aa64_vmalle1_write },
5128     { .name = "TLBI_VAE1", .state = ARM_CP_STATE_AA64,
5129       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 1,
5130       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5131       .writefn = tlbi_aa64_vae1_write },
5132     { .name = "TLBI_ASIDE1", .state = ARM_CP_STATE_AA64,
5133       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 2,
5134       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5135       .writefn = tlbi_aa64_vmalle1_write },
5136     { .name = "TLBI_VAAE1", .state = ARM_CP_STATE_AA64,
5137       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 3,
5138       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5139       .writefn = tlbi_aa64_vae1_write },
5140     { .name = "TLBI_VALE1", .state = ARM_CP_STATE_AA64,
5141       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
5142       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5143       .writefn = tlbi_aa64_vae1_write },
5144     { .name = "TLBI_VAALE1", .state = ARM_CP_STATE_AA64,
5145       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
5146       .access = PL1_W, .accessfn = access_ttlb, .type = ARM_CP_NO_RAW,
5147       .writefn = tlbi_aa64_vae1_write },
5148     { .name = "TLBI_IPAS2E1IS", .state = ARM_CP_STATE_AA64,
5149       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5150       .access = PL2_W, .type = ARM_CP_NOP },
5151     { .name = "TLBI_IPAS2LE1IS", .state = ARM_CP_STATE_AA64,
5152       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5153       .access = PL2_W, .type = ARM_CP_NOP },
5154     { .name = "TLBI_ALLE1IS", .state = ARM_CP_STATE_AA64,
5155       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5156       .access = PL2_W, .type = ARM_CP_NO_RAW,
5157       .writefn = tlbi_aa64_alle1is_write },
5158     { .name = "TLBI_VMALLS12E1IS", .state = ARM_CP_STATE_AA64,
5159       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 6,
5160       .access = PL2_W, .type = ARM_CP_NO_RAW,
5161       .writefn = tlbi_aa64_alle1is_write },
5162     { .name = "TLBI_IPAS2E1", .state = ARM_CP_STATE_AA64,
5163       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5164       .access = PL2_W, .type = ARM_CP_NOP },
5165     { .name = "TLBI_IPAS2LE1", .state = ARM_CP_STATE_AA64,
5166       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5167       .access = PL2_W, .type = ARM_CP_NOP },
5168     { .name = "TLBI_ALLE1", .state = ARM_CP_STATE_AA64,
5169       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5170       .access = PL2_W, .type = ARM_CP_NO_RAW,
5171       .writefn = tlbi_aa64_alle1_write },
5172     { .name = "TLBI_VMALLS12E1", .state = ARM_CP_STATE_AA64,
5173       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 6,
5174       .access = PL2_W, .type = ARM_CP_NO_RAW,
5175       .writefn = tlbi_aa64_alle1is_write },
5176 #ifndef CONFIG_USER_ONLY
5177     /* 64 bit address translation operations */
5178     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
5179       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 0,
5180       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5181       .writefn = ats_write64 },
5182     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
5183       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 1,
5184       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5185       .writefn = ats_write64 },
5186     { .name = "AT_S1E0R", .state = ARM_CP_STATE_AA64,
5187       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 2,
5188       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5189       .writefn = ats_write64 },
5190     { .name = "AT_S1E0W", .state = ARM_CP_STATE_AA64,
5191       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 8, .opc2 = 3,
5192       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5193       .writefn = ats_write64 },
5194     { .name = "AT_S12E1R", .state = ARM_CP_STATE_AA64,
5195       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 4,
5196       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5197       .writefn = ats_write64 },
5198     { .name = "AT_S12E1W", .state = ARM_CP_STATE_AA64,
5199       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 5,
5200       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5201       .writefn = ats_write64 },
5202     { .name = "AT_S12E0R", .state = ARM_CP_STATE_AA64,
5203       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 6,
5204       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5205       .writefn = ats_write64 },
5206     { .name = "AT_S12E0W", .state = ARM_CP_STATE_AA64,
5207       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 7,
5208       .access = PL2_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5209       .writefn = ats_write64 },
5210     /* AT S1E2* are elsewhere as they UNDEF from EL3 if EL2 is not present */
5211     { .name = "AT_S1E3R", .state = ARM_CP_STATE_AA64,
5212       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 0,
5213       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5214       .writefn = ats_write64 },
5215     { .name = "AT_S1E3W", .state = ARM_CP_STATE_AA64,
5216       .opc0 = 1, .opc1 = 6, .crn = 7, .crm = 8, .opc2 = 1,
5217       .access = PL3_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
5218       .writefn = ats_write64 },
5219     { .name = "PAR_EL1", .state = ARM_CP_STATE_AA64,
5220       .type = ARM_CP_ALIAS,
5221       .opc0 = 3, .opc1 = 0, .crn = 7, .crm = 4, .opc2 = 0,
5222       .access = PL1_RW, .resetvalue = 0,
5223       .fieldoffset = offsetof(CPUARMState, cp15.par_el[1]),
5224       .writefn = par_write },
5225 #endif
5226     /* TLB invalidate last level of translation table walk */
5227     { .name = "TLBIMVALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 5,
5228       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5229       .writefn = tlbimva_is_write },
5230     { .name = "TLBIMVAALIS", .cp = 15, .opc1 = 0, .crn = 8, .crm = 3, .opc2 = 7,
5231       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5232       .writefn = tlbimvaa_is_write },
5233     { .name = "TLBIMVAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 5,
5234       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5235       .writefn = tlbimva_write },
5236     { .name = "TLBIMVAAL", .cp = 15, .opc1 = 0, .crn = 8, .crm = 7, .opc2 = 7,
5237       .type = ARM_CP_NO_RAW, .access = PL1_W, .accessfn = access_ttlb,
5238       .writefn = tlbimvaa_write },
5239     { .name = "TLBIMVALH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5240       .type = ARM_CP_NO_RAW, .access = PL2_W,
5241       .writefn = tlbimva_hyp_write },
5242     { .name = "TLBIMVALHIS",
5243       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5244       .type = ARM_CP_NO_RAW, .access = PL2_W,
5245       .writefn = tlbimva_hyp_is_write },
5246     { .name = "TLBIIPAS2",
5247       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 1,
5248       .type = ARM_CP_NOP, .access = PL2_W },
5249     { .name = "TLBIIPAS2IS",
5250       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 1,
5251       .type = ARM_CP_NOP, .access = PL2_W },
5252     { .name = "TLBIIPAS2L",
5253       .cp = 15, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 5,
5254       .type = ARM_CP_NOP, .access = PL2_W },
5255     { .name = "TLBIIPAS2LIS",
5256       .cp = 15, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 5,
5257       .type = ARM_CP_NOP, .access = PL2_W },
5258     /* 32 bit cache operations */
5259     { .name = "ICIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 0,
5260       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5261     { .name = "BPIALLUIS", .cp = 15, .opc1 = 0, .crn = 7, .crm = 1, .opc2 = 6,
5262       .type = ARM_CP_NOP, .access = PL1_W },
5263     { .name = "ICIALLU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 0,
5264       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5265     { .name = "ICIMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 1,
5266       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5267     { .name = "BPIALL", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 6,
5268       .type = ARM_CP_NOP, .access = PL1_W },
5269     { .name = "BPIMVA", .cp = 15, .opc1 = 0, .crn = 7, .crm = 5, .opc2 = 7,
5270       .type = ARM_CP_NOP, .access = PL1_W },
5271     { .name = "DCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 1,
5272       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5273     { .name = "DCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 2,
5274       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5275     { .name = "DCCMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 1,
5276       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5277     { .name = "DCCSW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 2,
5278       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5279     { .name = "DCCMVAU", .cp = 15, .opc1 = 0, .crn = 7, .crm = 11, .opc2 = 1,
5280       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_pou_access },
5281     { .name = "DCCIMVAC", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 1,
5282       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = aa64_cacheop_poc_access },
5283     { .name = "DCCISW", .cp = 15, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 2,
5284       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
5285     /* MMU Domain access control / MPU write buffer control */
5286     { .name = "DACR", .cp = 15, .opc1 = 0, .crn = 3, .crm = 0, .opc2 = 0,
5287       .access = PL1_RW, .accessfn = access_tvm_trvm, .resetvalue = 0,
5288       .writefn = dacr_write, .raw_writefn = raw_write,
5289       .bank_fieldoffsets = { offsetoflow32(CPUARMState, cp15.dacr_s),
5290                              offsetoflow32(CPUARMState, cp15.dacr_ns) } },
5291     { .name = "ELR_EL1", .state = ARM_CP_STATE_AA64,
5292       .type = ARM_CP_ALIAS,
5293       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 1,
5294       .access = PL1_RW,
5295       .fieldoffset = offsetof(CPUARMState, elr_el[1]) },
5296     { .name = "SPSR_EL1", .state = ARM_CP_STATE_AA64,
5297       .type = ARM_CP_ALIAS,
5298       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 0, .opc2 = 0,
5299       .access = PL1_RW,
5300       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_SVC]) },
5301     /* We rely on the access checks not allowing the guest to write to the
5302      * state field when SPSel indicates that it's being used as the stack
5303      * pointer.
5304      */
5305     { .name = "SP_EL0", .state = ARM_CP_STATE_AA64,
5306       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 1, .opc2 = 0,
5307       .access = PL1_RW, .accessfn = sp_el0_access,
5308       .type = ARM_CP_ALIAS,
5309       .fieldoffset = offsetof(CPUARMState, sp_el[0]) },
5310     { .name = "SP_EL1", .state = ARM_CP_STATE_AA64,
5311       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 1, .opc2 = 0,
5312       .access = PL2_RW, .type = ARM_CP_ALIAS,
5313       .fieldoffset = offsetof(CPUARMState, sp_el[1]) },
5314     { .name = "SPSel", .state = ARM_CP_STATE_AA64,
5315       .opc0 = 3, .opc1 = 0, .crn = 4, .crm = 2, .opc2 = 0,
5316       .type = ARM_CP_NO_RAW,
5317       .access = PL1_RW, .readfn = spsel_read, .writefn = spsel_write },
5318     { .name = "FPEXC32_EL2", .state = ARM_CP_STATE_AA64,
5319       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 3, .opc2 = 0,
5320       .type = ARM_CP_ALIAS,
5321       .fieldoffset = offsetof(CPUARMState, vfp.xregs[ARM_VFP_FPEXC]),
5322       .access = PL2_RW, .accessfn = fpexc32_access },
5323     { .name = "DACR32_EL2", .state = ARM_CP_STATE_AA64,
5324       .opc0 = 3, .opc1 = 4, .crn = 3, .crm = 0, .opc2 = 0,
5325       .access = PL2_RW, .resetvalue = 0,
5326       .writefn = dacr_write, .raw_writefn = raw_write,
5327       .fieldoffset = offsetof(CPUARMState, cp15.dacr32_el2) },
5328     { .name = "IFSR32_EL2", .state = ARM_CP_STATE_AA64,
5329       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 0, .opc2 = 1,
5330       .access = PL2_RW, .resetvalue = 0,
5331       .fieldoffset = offsetof(CPUARMState, cp15.ifsr32_el2) },
5332     { .name = "SPSR_IRQ", .state = ARM_CP_STATE_AA64,
5333       .type = ARM_CP_ALIAS,
5334       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 0,
5335       .access = PL2_RW,
5336       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_IRQ]) },
5337     { .name = "SPSR_ABT", .state = ARM_CP_STATE_AA64,
5338       .type = ARM_CP_ALIAS,
5339       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 1,
5340       .access = PL2_RW,
5341       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_ABT]) },
5342     { .name = "SPSR_UND", .state = ARM_CP_STATE_AA64,
5343       .type = ARM_CP_ALIAS,
5344       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 2,
5345       .access = PL2_RW,
5346       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_UND]) },
5347     { .name = "SPSR_FIQ", .state = ARM_CP_STATE_AA64,
5348       .type = ARM_CP_ALIAS,
5349       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 3, .opc2 = 3,
5350       .access = PL2_RW,
5351       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_FIQ]) },
5352     { .name = "MDCR_EL3", .state = ARM_CP_STATE_AA64,
5353       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 3, .opc2 = 1,
5354       .resetvalue = 0,
5355       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el3) },
5356     { .name = "SDCR", .type = ARM_CP_ALIAS,
5357       .cp = 15, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 1,
5358       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5359       .writefn = sdcr_write,
5360       .fieldoffset = offsetoflow32(CPUARMState, cp15.mdcr_el3) },
5361     REGINFO_SENTINEL
5362 };
5363 
5364 /* Used to describe the behaviour of EL2 regs when EL2 does not exist.  */
5365 static const ARMCPRegInfo el3_no_el2_cp_reginfo[] = {
5366     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5367       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5368       .access = PL2_RW,
5369       .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore },
5370     { .name = "HCR_EL2", .state = ARM_CP_STATE_BOTH,
5371       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5372       .access = PL2_RW,
5373       .type = ARM_CP_CONST, .resetvalue = 0 },
5374     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5375       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5376       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5377     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5378       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5379       .access = PL2_RW,
5380       .type = ARM_CP_CONST, .resetvalue = 0 },
5381     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5382       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5383       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5384     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5385       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5386       .access = PL2_RW, .type = ARM_CP_CONST,
5387       .resetvalue = 0 },
5388     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5389       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5390       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5391     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5392       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5393       .access = PL2_RW, .type = ARM_CP_CONST,
5394       .resetvalue = 0 },
5395     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5396       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5397       .access = PL2_RW, .type = ARM_CP_CONST,
5398       .resetvalue = 0 },
5399     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5400       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5401       .access = PL2_RW, .type = ARM_CP_CONST,
5402       .resetvalue = 0 },
5403     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5404       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5405       .access = PL2_RW, .type = ARM_CP_CONST,
5406       .resetvalue = 0 },
5407     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5408       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5409       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5410     { .name = "VTCR_EL2", .state = ARM_CP_STATE_BOTH,
5411       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5412       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5413       .type = ARM_CP_CONST, .resetvalue = 0 },
5414     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5415       .cp = 15, .opc1 = 6, .crm = 2,
5416       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5417       .type = ARM_CP_CONST | ARM_CP_64BIT, .resetvalue = 0 },
5418     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5419       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5420       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5421     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5422       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5423       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5424     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5425       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5426       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5427     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5428       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5429       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5430     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5431       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5432       .resetvalue = 0 },
5433     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5434       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5435       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5436     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5437       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5438       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5439     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5440       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5441       .resetvalue = 0 },
5442     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5443       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5444       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5445     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5446       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_CONST,
5447       .resetvalue = 0 },
5448     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5449       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5450       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5451     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5452       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5453       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5454     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5455       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5456       .access = PL2_RW, .accessfn = access_tda,
5457       .type = ARM_CP_CONST, .resetvalue = 0 },
5458     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_BOTH,
5459       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5460       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5461       .type = ARM_CP_CONST, .resetvalue = 0 },
5462     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5463       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5464       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5465     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5466       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5467       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5468     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5469       .type = ARM_CP_CONST,
5470       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5471       .access = PL2_RW, .resetvalue = 0 },
5472     REGINFO_SENTINEL
5473 };
5474 
5475 /* Ditto, but for registers which exist in ARMv8 but not v7 */
5476 static const ARMCPRegInfo el3_no_el2_v8_cp_reginfo[] = {
5477     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5478       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5479       .access = PL2_RW,
5480       .type = ARM_CP_CONST, .resetvalue = 0 },
5481     REGINFO_SENTINEL
5482 };
5483 
5484 static void do_hcr_write(CPUARMState *env, uint64_t value, uint64_t valid_mask)
5485 {
5486     ARMCPU *cpu = env_archcpu(env);
5487 
5488     if (arm_feature(env, ARM_FEATURE_V8)) {
5489         valid_mask |= MAKE_64BIT_MASK(0, 34);  /* ARMv8.0 */
5490     } else {
5491         valid_mask |= MAKE_64BIT_MASK(0, 28);  /* ARMv7VE */
5492     }
5493 
5494     if (arm_feature(env, ARM_FEATURE_EL3)) {
5495         valid_mask &= ~HCR_HCD;
5496     } else if (cpu->psci_conduit != QEMU_PSCI_CONDUIT_SMC) {
5497         /* Architecturally HCR.TSC is RES0 if EL3 is not implemented.
5498          * However, if we're using the SMC PSCI conduit then QEMU is
5499          * effectively acting like EL3 firmware and so the guest at
5500          * EL2 should retain the ability to prevent EL1 from being
5501          * able to make SMC calls into the ersatz firmware, so in
5502          * that case HCR.TSC should be read/write.
5503          */
5504         valid_mask &= ~HCR_TSC;
5505     }
5506 
5507     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
5508         if (cpu_isar_feature(aa64_vh, cpu)) {
5509             valid_mask |= HCR_E2H;
5510         }
5511         if (cpu_isar_feature(aa64_lor, cpu)) {
5512             valid_mask |= HCR_TLOR;
5513         }
5514         if (cpu_isar_feature(aa64_pauth, cpu)) {
5515             valid_mask |= HCR_API | HCR_APK;
5516         }
5517         if (cpu_isar_feature(aa64_mte, cpu)) {
5518             valid_mask |= HCR_ATA | HCR_DCT | HCR_TID5;
5519         }
5520     }
5521 
5522     /* Clear RES0 bits.  */
5523     value &= valid_mask;
5524 
5525     /*
5526      * These bits change the MMU setup:
5527      * HCR_VM enables stage 2 translation
5528      * HCR_PTW forbids certain page-table setups
5529      * HCR_DC disables stage1 and enables stage2 translation
5530      * HCR_DCT enables tagging on (disabled) stage1 translation
5531      */
5532     if ((env->cp15.hcr_el2 ^ value) & (HCR_VM | HCR_PTW | HCR_DC | HCR_DCT)) {
5533         tlb_flush(CPU(cpu));
5534     }
5535     env->cp15.hcr_el2 = value;
5536 
5537     /*
5538      * Updates to VI and VF require us to update the status of
5539      * virtual interrupts, which are the logical OR of these bits
5540      * and the state of the input lines from the GIC. (This requires
5541      * that we have the iothread lock, which is done by marking the
5542      * reginfo structs as ARM_CP_IO.)
5543      * Note that if a write to HCR pends a VIRQ or VFIQ it is never
5544      * possible for it to be taken immediately, because VIRQ and
5545      * VFIQ are masked unless running at EL0 or EL1, and HCR
5546      * can only be written at EL2.
5547      */
5548     g_assert(qemu_mutex_iothread_locked());
5549     arm_cpu_update_virq(cpu);
5550     arm_cpu_update_vfiq(cpu);
5551 }
5552 
5553 static void hcr_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
5554 {
5555     do_hcr_write(env, value, 0);
5556 }
5557 
5558 static void hcr_writehigh(CPUARMState *env, const ARMCPRegInfo *ri,
5559                           uint64_t value)
5560 {
5561     /* Handle HCR2 write, i.e. write to high half of HCR_EL2 */
5562     value = deposit64(env->cp15.hcr_el2, 32, 32, value);
5563     do_hcr_write(env, value, MAKE_64BIT_MASK(0, 32));
5564 }
5565 
5566 static void hcr_writelow(CPUARMState *env, const ARMCPRegInfo *ri,
5567                          uint64_t value)
5568 {
5569     /* Handle HCR write, i.e. write to low half of HCR_EL2 */
5570     value = deposit64(env->cp15.hcr_el2, 0, 32, value);
5571     do_hcr_write(env, value, MAKE_64BIT_MASK(32, 32));
5572 }
5573 
5574 /*
5575  * Return the effective value of HCR_EL2.
5576  * Bits that are not included here:
5577  * RW       (read from SCR_EL3.RW as needed)
5578  */
5579 uint64_t arm_hcr_el2_eff(CPUARMState *env)
5580 {
5581     uint64_t ret = env->cp15.hcr_el2;
5582 
5583     if (!arm_is_el2_enabled(env)) {
5584         /*
5585          * "This register has no effect if EL2 is not enabled in the
5586          * current Security state".  This is ARMv8.4-SecEL2 speak for
5587          * !(SCR_EL3.NS==1 || SCR_EL3.EEL2==1).
5588          *
5589          * Prior to that, the language was "In an implementation that
5590          * includes EL3, when the value of SCR_EL3.NS is 0 the PE behaves
5591          * as if this field is 0 for all purposes other than a direct
5592          * read or write access of HCR_EL2".  With lots of enumeration
5593          * on a per-field basis.  In current QEMU, this is condition
5594          * is arm_is_secure_below_el3.
5595          *
5596          * Since the v8.4 language applies to the entire register, and
5597          * appears to be backward compatible, use that.
5598          */
5599         return 0;
5600     }
5601 
5602     /*
5603      * For a cpu that supports both aarch64 and aarch32, we can set bits
5604      * in HCR_EL2 (e.g. via EL3) that are RES0 when we enter EL2 as aa32.
5605      * Ignore all of the bits in HCR+HCR2 that are not valid for aarch32.
5606      */
5607     if (!arm_el_is_aa64(env, 2)) {
5608         uint64_t aa32_valid;
5609 
5610         /*
5611          * These bits are up-to-date as of ARMv8.6.
5612          * For HCR, it's easiest to list just the 2 bits that are invalid.
5613          * For HCR2, list those that are valid.
5614          */
5615         aa32_valid = MAKE_64BIT_MASK(0, 32) & ~(HCR_RW | HCR_TDZ);
5616         aa32_valid |= (HCR_CD | HCR_ID | HCR_TERR | HCR_TEA | HCR_MIOCNCE |
5617                        HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_TTLBIS);
5618         ret &= aa32_valid;
5619     }
5620 
5621     if (ret & HCR_TGE) {
5622         /* These bits are up-to-date as of ARMv8.6.  */
5623         if (ret & HCR_E2H) {
5624             ret &= ~(HCR_VM | HCR_FMO | HCR_IMO | HCR_AMO |
5625                      HCR_BSU_MASK | HCR_DC | HCR_TWI | HCR_TWE |
5626                      HCR_TID0 | HCR_TID2 | HCR_TPCP | HCR_TPU |
5627                      HCR_TDZ | HCR_CD | HCR_ID | HCR_MIOCNCE |
5628                      HCR_TID4 | HCR_TICAB | HCR_TOCU | HCR_ENSCXT |
5629                      HCR_TTLBIS | HCR_TTLBOS | HCR_TID5);
5630         } else {
5631             ret |= HCR_FMO | HCR_IMO | HCR_AMO;
5632         }
5633         ret &= ~(HCR_SWIO | HCR_PTW | HCR_VF | HCR_VI | HCR_VSE |
5634                  HCR_FB | HCR_TID1 | HCR_TID3 | HCR_TSC | HCR_TACR |
5635                  HCR_TSW | HCR_TTLB | HCR_TVM | HCR_HCD | HCR_TRVM |
5636                  HCR_TLOR);
5637     }
5638 
5639     return ret;
5640 }
5641 
5642 static void cptr_el2_write(CPUARMState *env, const ARMCPRegInfo *ri,
5643                            uint64_t value)
5644 {
5645     /*
5646      * For A-profile AArch32 EL3, if NSACR.CP10
5647      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5648      */
5649     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5650         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5651         value &= ~(0x3 << 10);
5652         value |= env->cp15.cptr_el[2] & (0x3 << 10);
5653     }
5654     env->cp15.cptr_el[2] = value;
5655 }
5656 
5657 static uint64_t cptr_el2_read(CPUARMState *env, const ARMCPRegInfo *ri)
5658 {
5659     /*
5660      * For A-profile AArch32 EL3, if NSACR.CP10
5661      * is 0 then HCPTR.{TCP11,TCP10} ignore writes and read as 1.
5662      */
5663     uint64_t value = env->cp15.cptr_el[2];
5664 
5665     if (arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
5666         !arm_is_secure(env) && !extract32(env->cp15.nsacr, 10, 1)) {
5667         value |= 0x3 << 10;
5668     }
5669     return value;
5670 }
5671 
5672 static const ARMCPRegInfo el2_cp_reginfo[] = {
5673     { .name = "HCR_EL2", .state = ARM_CP_STATE_AA64,
5674       .type = ARM_CP_IO,
5675       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5676       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5677       .writefn = hcr_write },
5678     { .name = "HCR", .state = ARM_CP_STATE_AA32,
5679       .type = ARM_CP_ALIAS | ARM_CP_IO,
5680       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 0,
5681       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.hcr_el2),
5682       .writefn = hcr_writelow },
5683     { .name = "HACR_EL2", .state = ARM_CP_STATE_BOTH,
5684       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 7,
5685       .access = PL2_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
5686     { .name = "ELR_EL2", .state = ARM_CP_STATE_AA64,
5687       .type = ARM_CP_ALIAS,
5688       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 1,
5689       .access = PL2_RW,
5690       .fieldoffset = offsetof(CPUARMState, elr_el[2]) },
5691     { .name = "ESR_EL2", .state = ARM_CP_STATE_BOTH,
5692       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 2, .opc2 = 0,
5693       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[2]) },
5694     { .name = "FAR_EL2", .state = ARM_CP_STATE_BOTH,
5695       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 0,
5696       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[2]) },
5697     { .name = "HIFAR", .state = ARM_CP_STATE_AA32,
5698       .type = ARM_CP_ALIAS,
5699       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 2,
5700       .access = PL2_RW,
5701       .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[2]) },
5702     { .name = "SPSR_EL2", .state = ARM_CP_STATE_AA64,
5703       .type = ARM_CP_ALIAS,
5704       .opc0 = 3, .opc1 = 4, .crn = 4, .crm = 0, .opc2 = 0,
5705       .access = PL2_RW,
5706       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_HYP]) },
5707     { .name = "VBAR_EL2", .state = ARM_CP_STATE_BOTH,
5708       .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 0,
5709       .access = PL2_RW, .writefn = vbar_write,
5710       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[2]),
5711       .resetvalue = 0 },
5712     { .name = "SP_EL2", .state = ARM_CP_STATE_AA64,
5713       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 1, .opc2 = 0,
5714       .access = PL3_RW, .type = ARM_CP_ALIAS,
5715       .fieldoffset = offsetof(CPUARMState, sp_el[2]) },
5716     { .name = "CPTR_EL2", .state = ARM_CP_STATE_BOTH,
5717       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 2,
5718       .access = PL2_RW, .accessfn = cptr_access, .resetvalue = 0,
5719       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[2]),
5720       .readfn = cptr_el2_read, .writefn = cptr_el2_write },
5721     { .name = "MAIR_EL2", .state = ARM_CP_STATE_BOTH,
5722       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 0,
5723       .access = PL2_RW, .fieldoffset = offsetof(CPUARMState, cp15.mair_el[2]),
5724       .resetvalue = 0 },
5725     { .name = "HMAIR1", .state = ARM_CP_STATE_AA32,
5726       .cp = 15, .opc1 = 4, .crn = 10, .crm = 2, .opc2 = 1,
5727       .access = PL2_RW, .type = ARM_CP_ALIAS,
5728       .fieldoffset = offsetofhigh32(CPUARMState, cp15.mair_el[2]) },
5729     { .name = "AMAIR_EL2", .state = ARM_CP_STATE_BOTH,
5730       .opc0 = 3, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 0,
5731       .access = PL2_RW, .type = ARM_CP_CONST,
5732       .resetvalue = 0 },
5733     /* HAMAIR1 is mapped to AMAIR_EL2[63:32] */
5734     { .name = "HAMAIR1", .state = ARM_CP_STATE_AA32,
5735       .cp = 15, .opc1 = 4, .crn = 10, .crm = 3, .opc2 = 1,
5736       .access = PL2_RW, .type = ARM_CP_CONST,
5737       .resetvalue = 0 },
5738     { .name = "AFSR0_EL2", .state = ARM_CP_STATE_BOTH,
5739       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 0,
5740       .access = PL2_RW, .type = ARM_CP_CONST,
5741       .resetvalue = 0 },
5742     { .name = "AFSR1_EL2", .state = ARM_CP_STATE_BOTH,
5743       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 1, .opc2 = 1,
5744       .access = PL2_RW, .type = ARM_CP_CONST,
5745       .resetvalue = 0 },
5746     { .name = "TCR_EL2", .state = ARM_CP_STATE_BOTH,
5747       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 2,
5748       .access = PL2_RW, .writefn = vmsa_tcr_el12_write,
5749       /* no .raw_writefn or .resetfn needed as we never use mask/base_mask */
5750       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[2]) },
5751     { .name = "VTCR", .state = ARM_CP_STATE_AA32,
5752       .cp = 15, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5753       .type = ARM_CP_ALIAS,
5754       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5755       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5756     { .name = "VTCR_EL2", .state = ARM_CP_STATE_AA64,
5757       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 2,
5758       .access = PL2_RW,
5759       /* no .writefn needed as this can't cause an ASID change;
5760        * no .raw_writefn or .resetfn needed as we never use mask/base_mask
5761        */
5762       .fieldoffset = offsetof(CPUARMState, cp15.vtcr_el2) },
5763     { .name = "VTTBR", .state = ARM_CP_STATE_AA32,
5764       .cp = 15, .opc1 = 6, .crm = 2,
5765       .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5766       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5767       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2),
5768       .writefn = vttbr_write },
5769     { .name = "VTTBR_EL2", .state = ARM_CP_STATE_AA64,
5770       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 1, .opc2 = 0,
5771       .access = PL2_RW, .writefn = vttbr_write,
5772       .fieldoffset = offsetof(CPUARMState, cp15.vttbr_el2) },
5773     { .name = "SCTLR_EL2", .state = ARM_CP_STATE_BOTH,
5774       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 0,
5775       .access = PL2_RW, .raw_writefn = raw_write, .writefn = sctlr_write,
5776       .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[2]) },
5777     { .name = "TPIDR_EL2", .state = ARM_CP_STATE_BOTH,
5778       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 2,
5779       .access = PL2_RW, .resetvalue = 0,
5780       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[2]) },
5781     { .name = "TTBR0_EL2", .state = ARM_CP_STATE_AA64,
5782       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 0,
5783       .access = PL2_RW, .resetvalue = 0, .writefn = vmsa_tcr_ttbr_el2_write,
5784       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5785     { .name = "HTTBR", .cp = 15, .opc1 = 4, .crm = 2,
5786       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS,
5787       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[2]) },
5788     { .name = "TLBIALLNSNH",
5789       .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 4,
5790       .type = ARM_CP_NO_RAW, .access = PL2_W,
5791       .writefn = tlbiall_nsnh_write },
5792     { .name = "TLBIALLNSNHIS",
5793       .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 4,
5794       .type = ARM_CP_NO_RAW, .access = PL2_W,
5795       .writefn = tlbiall_nsnh_is_write },
5796     { .name = "TLBIALLH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5797       .type = ARM_CP_NO_RAW, .access = PL2_W,
5798       .writefn = tlbiall_hyp_write },
5799     { .name = "TLBIALLHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5800       .type = ARM_CP_NO_RAW, .access = PL2_W,
5801       .writefn = tlbiall_hyp_is_write },
5802     { .name = "TLBIMVAH", .cp = 15, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5803       .type = ARM_CP_NO_RAW, .access = PL2_W,
5804       .writefn = tlbimva_hyp_write },
5805     { .name = "TLBIMVAHIS", .cp = 15, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5806       .type = ARM_CP_NO_RAW, .access = PL2_W,
5807       .writefn = tlbimva_hyp_is_write },
5808     { .name = "TLBI_ALLE2", .state = ARM_CP_STATE_AA64,
5809       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 0,
5810       .type = ARM_CP_NO_RAW, .access = PL2_W,
5811       .writefn = tlbi_aa64_alle2_write },
5812     { .name = "TLBI_VAE2", .state = ARM_CP_STATE_AA64,
5813       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 1,
5814       .type = ARM_CP_NO_RAW, .access = PL2_W,
5815       .writefn = tlbi_aa64_vae2_write },
5816     { .name = "TLBI_VALE2", .state = ARM_CP_STATE_AA64,
5817       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 7, .opc2 = 5,
5818       .access = PL2_W, .type = ARM_CP_NO_RAW,
5819       .writefn = tlbi_aa64_vae2_write },
5820     { .name = "TLBI_ALLE2IS", .state = ARM_CP_STATE_AA64,
5821       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 0,
5822       .access = PL2_W, .type = ARM_CP_NO_RAW,
5823       .writefn = tlbi_aa64_alle2is_write },
5824     { .name = "TLBI_VAE2IS", .state = ARM_CP_STATE_AA64,
5825       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 1,
5826       .type = ARM_CP_NO_RAW, .access = PL2_W,
5827       .writefn = tlbi_aa64_vae2is_write },
5828     { .name = "TLBI_VALE2IS", .state = ARM_CP_STATE_AA64,
5829       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 3, .opc2 = 5,
5830       .access = PL2_W, .type = ARM_CP_NO_RAW,
5831       .writefn = tlbi_aa64_vae2is_write },
5832 #ifndef CONFIG_USER_ONLY
5833     /* Unlike the other EL2-related AT operations, these must
5834      * UNDEF from EL3 if EL2 is not implemented, which is why we
5835      * define them here rather than with the rest of the AT ops.
5836      */
5837     { .name = "AT_S1E2R", .state = ARM_CP_STATE_AA64,
5838       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5839       .access = PL2_W, .accessfn = at_s1e2_access,
5840       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5841     { .name = "AT_S1E2W", .state = ARM_CP_STATE_AA64,
5842       .opc0 = 1, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5843       .access = PL2_W, .accessfn = at_s1e2_access,
5844       .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC, .writefn = ats_write64 },
5845     /* The AArch32 ATS1H* operations are CONSTRAINED UNPREDICTABLE
5846      * if EL2 is not implemented; we choose to UNDEF. Behaviour at EL3
5847      * with SCR.NS == 0 outside Monitor mode is UNPREDICTABLE; we choose
5848      * to behave as if SCR.NS was 1.
5849      */
5850     { .name = "ATS1HR", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 0,
5851       .access = PL2_W,
5852       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5853     { .name = "ATS1HW", .cp = 15, .opc1 = 4, .crn = 7, .crm = 8, .opc2 = 1,
5854       .access = PL2_W,
5855       .writefn = ats1h_write, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC },
5856     { .name = "CNTHCTL_EL2", .state = ARM_CP_STATE_BOTH,
5857       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 1, .opc2 = 0,
5858       /* ARMv7 requires bit 0 and 1 to reset to 1. ARMv8 defines the
5859        * reset values as IMPDEF. We choose to reset to 3 to comply with
5860        * both ARMv7 and ARMv8.
5861        */
5862       .access = PL2_RW, .resetvalue = 3,
5863       .fieldoffset = offsetof(CPUARMState, cp15.cnthctl_el2) },
5864     { .name = "CNTVOFF_EL2", .state = ARM_CP_STATE_AA64,
5865       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 0, .opc2 = 3,
5866       .access = PL2_RW, .type = ARM_CP_IO, .resetvalue = 0,
5867       .writefn = gt_cntvoff_write,
5868       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5869     { .name = "CNTVOFF", .cp = 15, .opc1 = 4, .crm = 14,
5870       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_ALIAS | ARM_CP_IO,
5871       .writefn = gt_cntvoff_write,
5872       .fieldoffset = offsetof(CPUARMState, cp15.cntvoff_el2) },
5873     { .name = "CNTHP_CVAL_EL2", .state = ARM_CP_STATE_AA64,
5874       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 2,
5875       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5876       .type = ARM_CP_IO, .access = PL2_RW,
5877       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5878     { .name = "CNTHP_CVAL", .cp = 15, .opc1 = 6, .crm = 14,
5879       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].cval),
5880       .access = PL2_RW, .type = ARM_CP_64BIT | ARM_CP_IO,
5881       .writefn = gt_hyp_cval_write, .raw_writefn = raw_write },
5882     { .name = "CNTHP_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
5883       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 0,
5884       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
5885       .resetfn = gt_hyp_timer_reset,
5886       .readfn = gt_hyp_tval_read, .writefn = gt_hyp_tval_write },
5887     { .name = "CNTHP_CTL_EL2", .state = ARM_CP_STATE_BOTH,
5888       .type = ARM_CP_IO,
5889       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 2, .opc2 = 1,
5890       .access = PL2_RW,
5891       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYP].ctl),
5892       .resetvalue = 0,
5893       .writefn = gt_hyp_ctl_write, .raw_writefn = raw_write },
5894 #endif
5895     /* The only field of MDCR_EL2 that has a defined architectural reset value
5896      * is MDCR_EL2.HPMN which should reset to the value of PMCR_EL0.N.
5897      */
5898     { .name = "MDCR_EL2", .state = ARM_CP_STATE_BOTH,
5899       .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 1,
5900       .access = PL2_RW, .resetvalue = PMCR_NUM_COUNTERS,
5901       .fieldoffset = offsetof(CPUARMState, cp15.mdcr_el2), },
5902     { .name = "HPFAR", .state = ARM_CP_STATE_AA32,
5903       .cp = 15, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5904       .access = PL2_RW, .accessfn = access_el3_aa32ns,
5905       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5906     { .name = "HPFAR_EL2", .state = ARM_CP_STATE_AA64,
5907       .opc0 = 3, .opc1 = 4, .crn = 6, .crm = 0, .opc2 = 4,
5908       .access = PL2_RW,
5909       .fieldoffset = offsetof(CPUARMState, cp15.hpfar_el2) },
5910     { .name = "HSTR_EL2", .state = ARM_CP_STATE_BOTH,
5911       .cp = 15, .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 3,
5912       .access = PL2_RW,
5913       .fieldoffset = offsetof(CPUARMState, cp15.hstr_el2) },
5914     REGINFO_SENTINEL
5915 };
5916 
5917 static const ARMCPRegInfo el2_v8_cp_reginfo[] = {
5918     { .name = "HCR2", .state = ARM_CP_STATE_AA32,
5919       .type = ARM_CP_ALIAS | ARM_CP_IO,
5920       .cp = 15, .opc1 = 4, .crn = 1, .crm = 1, .opc2 = 4,
5921       .access = PL2_RW,
5922       .fieldoffset = offsetofhigh32(CPUARMState, cp15.hcr_el2),
5923       .writefn = hcr_writehigh },
5924     REGINFO_SENTINEL
5925 };
5926 
5927 static CPAccessResult sel2_access(CPUARMState *env, const ARMCPRegInfo *ri,
5928                                   bool isread)
5929 {
5930     if (arm_current_el(env) == 3 || arm_is_secure_below_el3(env)) {
5931         return CP_ACCESS_OK;
5932     }
5933     return CP_ACCESS_TRAP_UNCATEGORIZED;
5934 }
5935 
5936 static const ARMCPRegInfo el2_sec_cp_reginfo[] = {
5937     { .name = "VSTTBR_EL2", .state = ARM_CP_STATE_AA64,
5938       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 0,
5939       .access = PL2_RW, .accessfn = sel2_access,
5940       .fieldoffset = offsetof(CPUARMState, cp15.vsttbr_el2) },
5941     { .name = "VSTCR_EL2", .state = ARM_CP_STATE_AA64,
5942       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 6, .opc2 = 2,
5943       .access = PL2_RW, .accessfn = sel2_access,
5944       .fieldoffset = offsetof(CPUARMState, cp15.vstcr_el2) },
5945     REGINFO_SENTINEL
5946 };
5947 
5948 static CPAccessResult nsacr_access(CPUARMState *env, const ARMCPRegInfo *ri,
5949                                    bool isread)
5950 {
5951     /* The NSACR is RW at EL3, and RO for NS EL1 and NS EL2.
5952      * At Secure EL1 it traps to EL3 or EL2.
5953      */
5954     if (arm_current_el(env) == 3) {
5955         return CP_ACCESS_OK;
5956     }
5957     if (arm_is_secure_below_el3(env)) {
5958         if (env->cp15.scr_el3 & SCR_EEL2) {
5959             return CP_ACCESS_TRAP_EL2;
5960         }
5961         return CP_ACCESS_TRAP_EL3;
5962     }
5963     /* Accesses from EL1 NS and EL2 NS are UNDEF for write but allow reads. */
5964     if (isread) {
5965         return CP_ACCESS_OK;
5966     }
5967     return CP_ACCESS_TRAP_UNCATEGORIZED;
5968 }
5969 
5970 static const ARMCPRegInfo el3_cp_reginfo[] = {
5971     { .name = "SCR_EL3", .state = ARM_CP_STATE_AA64,
5972       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 0,
5973       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.scr_el3),
5974       .resetfn = scr_reset, .writefn = scr_write },
5975     { .name = "SCR",  .type = ARM_CP_ALIAS | ARM_CP_NEWEL,
5976       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 0,
5977       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5978       .fieldoffset = offsetoflow32(CPUARMState, cp15.scr_el3),
5979       .writefn = scr_write },
5980     { .name = "SDER32_EL3", .state = ARM_CP_STATE_AA64,
5981       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 1,
5982       .access = PL3_RW, .resetvalue = 0,
5983       .fieldoffset = offsetof(CPUARMState, cp15.sder) },
5984     { .name = "SDER",
5985       .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 1,
5986       .access = PL3_RW, .resetvalue = 0,
5987       .fieldoffset = offsetoflow32(CPUARMState, cp15.sder) },
5988     { .name = "MVBAR", .cp = 15, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
5989       .access = PL1_RW, .accessfn = access_trap_aa32s_el1,
5990       .writefn = vbar_write, .resetvalue = 0,
5991       .fieldoffset = offsetof(CPUARMState, cp15.mvbar) },
5992     { .name = "TTBR0_EL3", .state = ARM_CP_STATE_AA64,
5993       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 0,
5994       .access = PL3_RW, .resetvalue = 0,
5995       .fieldoffset = offsetof(CPUARMState, cp15.ttbr0_el[3]) },
5996     { .name = "TCR_EL3", .state = ARM_CP_STATE_AA64,
5997       .opc0 = 3, .opc1 = 6, .crn = 2, .crm = 0, .opc2 = 2,
5998       .access = PL3_RW,
5999       /* no .writefn needed as this can't cause an ASID change;
6000        * we must provide a .raw_writefn and .resetfn because we handle
6001        * reset and migration for the AArch32 TTBCR(S), which might be
6002        * using mask and base_mask.
6003        */
6004       .resetfn = vmsa_ttbcr_reset, .raw_writefn = vmsa_ttbcr_raw_write,
6005       .fieldoffset = offsetof(CPUARMState, cp15.tcr_el[3]) },
6006     { .name = "ELR_EL3", .state = ARM_CP_STATE_AA64,
6007       .type = ARM_CP_ALIAS,
6008       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 1,
6009       .access = PL3_RW,
6010       .fieldoffset = offsetof(CPUARMState, elr_el[3]) },
6011     { .name = "ESR_EL3", .state = ARM_CP_STATE_AA64,
6012       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 2, .opc2 = 0,
6013       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.esr_el[3]) },
6014     { .name = "FAR_EL3", .state = ARM_CP_STATE_AA64,
6015       .opc0 = 3, .opc1 = 6, .crn = 6, .crm = 0, .opc2 = 0,
6016       .access = PL3_RW, .fieldoffset = offsetof(CPUARMState, cp15.far_el[3]) },
6017     { .name = "SPSR_EL3", .state = ARM_CP_STATE_AA64,
6018       .type = ARM_CP_ALIAS,
6019       .opc0 = 3, .opc1 = 6, .crn = 4, .crm = 0, .opc2 = 0,
6020       .access = PL3_RW,
6021       .fieldoffset = offsetof(CPUARMState, banked_spsr[BANK_MON]) },
6022     { .name = "VBAR_EL3", .state = ARM_CP_STATE_AA64,
6023       .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 0,
6024       .access = PL3_RW, .writefn = vbar_write,
6025       .fieldoffset = offsetof(CPUARMState, cp15.vbar_el[3]),
6026       .resetvalue = 0 },
6027     { .name = "CPTR_EL3", .state = ARM_CP_STATE_AA64,
6028       .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 1, .opc2 = 2,
6029       .access = PL3_RW, .accessfn = cptr_access, .resetvalue = 0,
6030       .fieldoffset = offsetof(CPUARMState, cp15.cptr_el[3]) },
6031     { .name = "TPIDR_EL3", .state = ARM_CP_STATE_AA64,
6032       .opc0 = 3, .opc1 = 6, .crn = 13, .crm = 0, .opc2 = 2,
6033       .access = PL3_RW, .resetvalue = 0,
6034       .fieldoffset = offsetof(CPUARMState, cp15.tpidr_el[3]) },
6035     { .name = "AMAIR_EL3", .state = ARM_CP_STATE_AA64,
6036       .opc0 = 3, .opc1 = 6, .crn = 10, .crm = 3, .opc2 = 0,
6037       .access = PL3_RW, .type = ARM_CP_CONST,
6038       .resetvalue = 0 },
6039     { .name = "AFSR0_EL3", .state = ARM_CP_STATE_BOTH,
6040       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 0,
6041       .access = PL3_RW, .type = ARM_CP_CONST,
6042       .resetvalue = 0 },
6043     { .name = "AFSR1_EL3", .state = ARM_CP_STATE_BOTH,
6044       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 1, .opc2 = 1,
6045       .access = PL3_RW, .type = ARM_CP_CONST,
6046       .resetvalue = 0 },
6047     { .name = "TLBI_ALLE3IS", .state = ARM_CP_STATE_AA64,
6048       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 0,
6049       .access = PL3_W, .type = ARM_CP_NO_RAW,
6050       .writefn = tlbi_aa64_alle3is_write },
6051     { .name = "TLBI_VAE3IS", .state = ARM_CP_STATE_AA64,
6052       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 1,
6053       .access = PL3_W, .type = ARM_CP_NO_RAW,
6054       .writefn = tlbi_aa64_vae3is_write },
6055     { .name = "TLBI_VALE3IS", .state = ARM_CP_STATE_AA64,
6056       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 3, .opc2 = 5,
6057       .access = PL3_W, .type = ARM_CP_NO_RAW,
6058       .writefn = tlbi_aa64_vae3is_write },
6059     { .name = "TLBI_ALLE3", .state = ARM_CP_STATE_AA64,
6060       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 0,
6061       .access = PL3_W, .type = ARM_CP_NO_RAW,
6062       .writefn = tlbi_aa64_alle3_write },
6063     { .name = "TLBI_VAE3", .state = ARM_CP_STATE_AA64,
6064       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 1,
6065       .access = PL3_W, .type = ARM_CP_NO_RAW,
6066       .writefn = tlbi_aa64_vae3_write },
6067     { .name = "TLBI_VALE3", .state = ARM_CP_STATE_AA64,
6068       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 7, .opc2 = 5,
6069       .access = PL3_W, .type = ARM_CP_NO_RAW,
6070       .writefn = tlbi_aa64_vae3_write },
6071     REGINFO_SENTINEL
6072 };
6073 
6074 #ifndef CONFIG_USER_ONLY
6075 /* Test if system register redirection is to occur in the current state.  */
6076 static bool redirect_for_e2h(CPUARMState *env)
6077 {
6078     return arm_current_el(env) == 2 && (arm_hcr_el2_eff(env) & HCR_E2H);
6079 }
6080 
6081 static uint64_t el2_e2h_read(CPUARMState *env, const ARMCPRegInfo *ri)
6082 {
6083     CPReadFn *readfn;
6084 
6085     if (redirect_for_e2h(env)) {
6086         /* Switch to the saved EL2 version of the register.  */
6087         ri = ri->opaque;
6088         readfn = ri->readfn;
6089     } else {
6090         readfn = ri->orig_readfn;
6091     }
6092     if (readfn == NULL) {
6093         readfn = raw_read;
6094     }
6095     return readfn(env, ri);
6096 }
6097 
6098 static void el2_e2h_write(CPUARMState *env, const ARMCPRegInfo *ri,
6099                           uint64_t value)
6100 {
6101     CPWriteFn *writefn;
6102 
6103     if (redirect_for_e2h(env)) {
6104         /* Switch to the saved EL2 version of the register.  */
6105         ri = ri->opaque;
6106         writefn = ri->writefn;
6107     } else {
6108         writefn = ri->orig_writefn;
6109     }
6110     if (writefn == NULL) {
6111         writefn = raw_write;
6112     }
6113     writefn(env, ri, value);
6114 }
6115 
6116 static void define_arm_vh_e2h_redirects_aliases(ARMCPU *cpu)
6117 {
6118     struct E2HAlias {
6119         uint32_t src_key, dst_key, new_key;
6120         const char *src_name, *dst_name, *new_name;
6121         bool (*feature)(const ARMISARegisters *id);
6122     };
6123 
6124 #define K(op0, op1, crn, crm, op2) \
6125     ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP, crn, crm, op0, op1, op2)
6126 
6127     static const struct E2HAlias aliases[] = {
6128         { K(3, 0,  1, 0, 0), K(3, 4,  1, 0, 0), K(3, 5, 1, 0, 0),
6129           "SCTLR", "SCTLR_EL2", "SCTLR_EL12" },
6130         { K(3, 0,  1, 0, 2), K(3, 4,  1, 1, 2), K(3, 5, 1, 0, 2),
6131           "CPACR", "CPTR_EL2", "CPACR_EL12" },
6132         { K(3, 0,  2, 0, 0), K(3, 4,  2, 0, 0), K(3, 5, 2, 0, 0),
6133           "TTBR0_EL1", "TTBR0_EL2", "TTBR0_EL12" },
6134         { K(3, 0,  2, 0, 1), K(3, 4,  2, 0, 1), K(3, 5, 2, 0, 1),
6135           "TTBR1_EL1", "TTBR1_EL2", "TTBR1_EL12" },
6136         { K(3, 0,  2, 0, 2), K(3, 4,  2, 0, 2), K(3, 5, 2, 0, 2),
6137           "TCR_EL1", "TCR_EL2", "TCR_EL12" },
6138         { K(3, 0,  4, 0, 0), K(3, 4,  4, 0, 0), K(3, 5, 4, 0, 0),
6139           "SPSR_EL1", "SPSR_EL2", "SPSR_EL12" },
6140         { K(3, 0,  4, 0, 1), K(3, 4,  4, 0, 1), K(3, 5, 4, 0, 1),
6141           "ELR_EL1", "ELR_EL2", "ELR_EL12" },
6142         { K(3, 0,  5, 1, 0), K(3, 4,  5, 1, 0), K(3, 5, 5, 1, 0),
6143           "AFSR0_EL1", "AFSR0_EL2", "AFSR0_EL12" },
6144         { K(3, 0,  5, 1, 1), K(3, 4,  5, 1, 1), K(3, 5, 5, 1, 1),
6145           "AFSR1_EL1", "AFSR1_EL2", "AFSR1_EL12" },
6146         { K(3, 0,  5, 2, 0), K(3, 4,  5, 2, 0), K(3, 5, 5, 2, 0),
6147           "ESR_EL1", "ESR_EL2", "ESR_EL12" },
6148         { K(3, 0,  6, 0, 0), K(3, 4,  6, 0, 0), K(3, 5, 6, 0, 0),
6149           "FAR_EL1", "FAR_EL2", "FAR_EL12" },
6150         { K(3, 0, 10, 2, 0), K(3, 4, 10, 2, 0), K(3, 5, 10, 2, 0),
6151           "MAIR_EL1", "MAIR_EL2", "MAIR_EL12" },
6152         { K(3, 0, 10, 3, 0), K(3, 4, 10, 3, 0), K(3, 5, 10, 3, 0),
6153           "AMAIR0", "AMAIR_EL2", "AMAIR_EL12" },
6154         { K(3, 0, 12, 0, 0), K(3, 4, 12, 0, 0), K(3, 5, 12, 0, 0),
6155           "VBAR", "VBAR_EL2", "VBAR_EL12" },
6156         { K(3, 0, 13, 0, 1), K(3, 4, 13, 0, 1), K(3, 5, 13, 0, 1),
6157           "CONTEXTIDR_EL1", "CONTEXTIDR_EL2", "CONTEXTIDR_EL12" },
6158         { K(3, 0, 14, 1, 0), K(3, 4, 14, 1, 0), K(3, 5, 14, 1, 0),
6159           "CNTKCTL", "CNTHCTL_EL2", "CNTKCTL_EL12" },
6160 
6161         /*
6162          * Note that redirection of ZCR is mentioned in the description
6163          * of ZCR_EL2, and aliasing in the description of ZCR_EL1, but
6164          * not in the summary table.
6165          */
6166         { K(3, 0,  1, 2, 0), K(3, 4,  1, 2, 0), K(3, 5, 1, 2, 0),
6167           "ZCR_EL1", "ZCR_EL2", "ZCR_EL12", isar_feature_aa64_sve },
6168 
6169         { K(3, 0,  5, 6, 0), K(3, 4,  5, 6, 0), K(3, 5, 5, 6, 0),
6170           "TFSR_EL1", "TFSR_EL2", "TFSR_EL12", isar_feature_aa64_mte },
6171 
6172         /* TODO: ARMv8.2-SPE -- PMSCR_EL2 */
6173         /* TODO: ARMv8.4-Trace -- TRFCR_EL2 */
6174     };
6175 #undef K
6176 
6177     size_t i;
6178 
6179     for (i = 0; i < ARRAY_SIZE(aliases); i++) {
6180         const struct E2HAlias *a = &aliases[i];
6181         ARMCPRegInfo *src_reg, *dst_reg;
6182 
6183         if (a->feature && !a->feature(&cpu->isar)) {
6184             continue;
6185         }
6186 
6187         src_reg = g_hash_table_lookup(cpu->cp_regs, &a->src_key);
6188         dst_reg = g_hash_table_lookup(cpu->cp_regs, &a->dst_key);
6189         g_assert(src_reg != NULL);
6190         g_assert(dst_reg != NULL);
6191 
6192         /* Cross-compare names to detect typos in the keys.  */
6193         g_assert(strcmp(src_reg->name, a->src_name) == 0);
6194         g_assert(strcmp(dst_reg->name, a->dst_name) == 0);
6195 
6196         /* None of the core system registers use opaque; we will.  */
6197         g_assert(src_reg->opaque == NULL);
6198 
6199         /* Create alias before redirection so we dup the right data. */
6200         if (a->new_key) {
6201             ARMCPRegInfo *new_reg = g_memdup(src_reg, sizeof(ARMCPRegInfo));
6202             uint32_t *new_key = g_memdup(&a->new_key, sizeof(uint32_t));
6203             bool ok;
6204 
6205             new_reg->name = a->new_name;
6206             new_reg->type |= ARM_CP_ALIAS;
6207             /* Remove PL1/PL0 access, leaving PL2/PL3 R/W in place.  */
6208             new_reg->access &= PL2_RW | PL3_RW;
6209 
6210             ok = g_hash_table_insert(cpu->cp_regs, new_key, new_reg);
6211             g_assert(ok);
6212         }
6213 
6214         src_reg->opaque = dst_reg;
6215         src_reg->orig_readfn = src_reg->readfn ?: raw_read;
6216         src_reg->orig_writefn = src_reg->writefn ?: raw_write;
6217         if (!src_reg->raw_readfn) {
6218             src_reg->raw_readfn = raw_read;
6219         }
6220         if (!src_reg->raw_writefn) {
6221             src_reg->raw_writefn = raw_write;
6222         }
6223         src_reg->readfn = el2_e2h_read;
6224         src_reg->writefn = el2_e2h_write;
6225     }
6226 }
6227 #endif
6228 
6229 static CPAccessResult ctr_el0_access(CPUARMState *env, const ARMCPRegInfo *ri,
6230                                      bool isread)
6231 {
6232     int cur_el = arm_current_el(env);
6233 
6234     if (cur_el < 2) {
6235         uint64_t hcr = arm_hcr_el2_eff(env);
6236 
6237         if (cur_el == 0) {
6238             if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
6239                 if (!(env->cp15.sctlr_el[2] & SCTLR_UCT)) {
6240                     return CP_ACCESS_TRAP_EL2;
6241                 }
6242             } else {
6243                 if (!(env->cp15.sctlr_el[1] & SCTLR_UCT)) {
6244                     return CP_ACCESS_TRAP;
6245                 }
6246                 if (hcr & HCR_TID2) {
6247                     return CP_ACCESS_TRAP_EL2;
6248                 }
6249             }
6250         } else if (hcr & HCR_TID2) {
6251             return CP_ACCESS_TRAP_EL2;
6252         }
6253     }
6254 
6255     if (arm_current_el(env) < 2 && arm_hcr_el2_eff(env) & HCR_TID2) {
6256         return CP_ACCESS_TRAP_EL2;
6257     }
6258 
6259     return CP_ACCESS_OK;
6260 }
6261 
6262 static void oslar_write(CPUARMState *env, const ARMCPRegInfo *ri,
6263                         uint64_t value)
6264 {
6265     /* Writes to OSLAR_EL1 may update the OS lock status, which can be
6266      * read via a bit in OSLSR_EL1.
6267      */
6268     int oslock;
6269 
6270     if (ri->state == ARM_CP_STATE_AA32) {
6271         oslock = (value == 0xC5ACCE55);
6272     } else {
6273         oslock = value & 1;
6274     }
6275 
6276     env->cp15.oslsr_el1 = deposit32(env->cp15.oslsr_el1, 1, 1, oslock);
6277 }
6278 
6279 static const ARMCPRegInfo debug_cp_reginfo[] = {
6280     /* DBGDRAR, DBGDSAR: always RAZ since we don't implement memory mapped
6281      * debug components. The AArch64 version of DBGDRAR is named MDRAR_EL1;
6282      * unlike DBGDRAR it is never accessible from EL0.
6283      * DBGDSAR is deprecated and must RAZ from v8 anyway, so it has no AArch64
6284      * accessor.
6285      */
6286     { .name = "DBGDRAR", .cp = 14, .crn = 1, .crm = 0, .opc1 = 0, .opc2 = 0,
6287       .access = PL0_R, .accessfn = access_tdra,
6288       .type = ARM_CP_CONST, .resetvalue = 0 },
6289     { .name = "MDRAR_EL1", .state = ARM_CP_STATE_AA64,
6290       .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
6291       .access = PL1_R, .accessfn = access_tdra,
6292       .type = ARM_CP_CONST, .resetvalue = 0 },
6293     { .name = "DBGDSAR", .cp = 14, .crn = 2, .crm = 0, .opc1 = 0, .opc2 = 0,
6294       .access = PL0_R, .accessfn = access_tdra,
6295       .type = ARM_CP_CONST, .resetvalue = 0 },
6296     /* Monitor debug system control register; the 32-bit alias is DBGDSCRext. */
6297     { .name = "MDSCR_EL1", .state = ARM_CP_STATE_BOTH,
6298       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
6299       .access = PL1_RW, .accessfn = access_tda,
6300       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1),
6301       .resetvalue = 0 },
6302     /*
6303      * MDCCSR_EL0[30:29] map to EDSCR[30:29].  Simply RAZ as the external
6304      * Debug Communication Channel is not implemented.
6305      */
6306     { .name = "MDCCSR_EL0", .state = ARM_CP_STATE_AA64,
6307       .opc0 = 2, .opc1 = 3, .crn = 0, .crm = 1, .opc2 = 0,
6308       .access = PL0_R, .accessfn = access_tda,
6309       .type = ARM_CP_CONST, .resetvalue = 0 },
6310     /*
6311      * DBGDSCRint[15,12,5:2] map to MDSCR_EL1[15,12,5:2].  Map all bits as
6312      * it is unlikely a guest will care.
6313      * We don't implement the configurable EL0 access.
6314      */
6315     { .name = "DBGDSCRint", .state = ARM_CP_STATE_AA32,
6316       .cp = 14, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
6317       .type = ARM_CP_ALIAS,
6318       .access = PL1_R, .accessfn = access_tda,
6319       .fieldoffset = offsetof(CPUARMState, cp15.mdscr_el1), },
6320     { .name = "OSLAR_EL1", .state = ARM_CP_STATE_BOTH,
6321       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 4,
6322       .access = PL1_W, .type = ARM_CP_NO_RAW,
6323       .accessfn = access_tdosa,
6324       .writefn = oslar_write },
6325     { .name = "OSLSR_EL1", .state = ARM_CP_STATE_BOTH,
6326       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 4,
6327       .access = PL1_R, .resetvalue = 10,
6328       .accessfn = access_tdosa,
6329       .fieldoffset = offsetof(CPUARMState, cp15.oslsr_el1) },
6330     /* Dummy OSDLR_EL1: 32-bit Linux will read this */
6331     { .name = "OSDLR_EL1", .state = ARM_CP_STATE_BOTH,
6332       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 1, .crm = 3, .opc2 = 4,
6333       .access = PL1_RW, .accessfn = access_tdosa,
6334       .type = ARM_CP_NOP },
6335     /* Dummy DBGVCR: Linux wants to clear this on startup, but we don't
6336      * implement vector catch debug events yet.
6337      */
6338     { .name = "DBGVCR",
6339       .cp = 14, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
6340       .access = PL1_RW, .accessfn = access_tda,
6341       .type = ARM_CP_NOP },
6342     /* Dummy DBGVCR32_EL2 (which is only for a 64-bit hypervisor
6343      * to save and restore a 32-bit guest's DBGVCR)
6344      */
6345     { .name = "DBGVCR32_EL2", .state = ARM_CP_STATE_AA64,
6346       .opc0 = 2, .opc1 = 4, .crn = 0, .crm = 7, .opc2 = 0,
6347       .access = PL2_RW, .accessfn = access_tda,
6348       .type = ARM_CP_NOP },
6349     /* Dummy MDCCINT_EL1, since we don't implement the Debug Communications
6350      * Channel but Linux may try to access this register. The 32-bit
6351      * alias is DBGDCCINT.
6352      */
6353     { .name = "MDCCINT_EL1", .state = ARM_CP_STATE_BOTH,
6354       .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
6355       .access = PL1_RW, .accessfn = access_tda,
6356       .type = ARM_CP_NOP },
6357     REGINFO_SENTINEL
6358 };
6359 
6360 static const ARMCPRegInfo debug_lpae_cp_reginfo[] = {
6361     /* 64 bit access versions of the (dummy) debug registers */
6362     { .name = "DBGDRAR", .cp = 14, .crm = 1, .opc1 = 0,
6363       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6364     { .name = "DBGDSAR", .cp = 14, .crm = 2, .opc1 = 0,
6365       .access = PL0_R, .type = ARM_CP_CONST|ARM_CP_64BIT, .resetvalue = 0 },
6366     REGINFO_SENTINEL
6367 };
6368 
6369 /* Return the exception level to which exceptions should be taken
6370  * via SVEAccessTrap.  If an exception should be routed through
6371  * AArch64.AdvSIMDFPAccessTrap, return 0; fp_exception_el should
6372  * take care of raising that exception.
6373  * C.f. the ARM pseudocode function CheckSVEEnabled.
6374  */
6375 int sve_exception_el(CPUARMState *env, int el)
6376 {
6377 #ifndef CONFIG_USER_ONLY
6378     uint64_t hcr_el2 = arm_hcr_el2_eff(env);
6379 
6380     if (el <= 1 && (hcr_el2 & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
6381         bool disabled = false;
6382 
6383         /* The CPACR.ZEN controls traps to EL1:
6384          * 0, 2 : trap EL0 and EL1 accesses
6385          * 1    : trap only EL0 accesses
6386          * 3    : trap no accesses
6387          */
6388         if (!extract32(env->cp15.cpacr_el1, 16, 1)) {
6389             disabled = true;
6390         } else if (!extract32(env->cp15.cpacr_el1, 17, 1)) {
6391             disabled = el == 0;
6392         }
6393         if (disabled) {
6394             /* route_to_el2 */
6395             return hcr_el2 & HCR_TGE ? 2 : 1;
6396         }
6397 
6398         /* Check CPACR.FPEN.  */
6399         if (!extract32(env->cp15.cpacr_el1, 20, 1)) {
6400             disabled = true;
6401         } else if (!extract32(env->cp15.cpacr_el1, 21, 1)) {
6402             disabled = el == 0;
6403         }
6404         if (disabled) {
6405             return 0;
6406         }
6407     }
6408 
6409     /* CPTR_EL2.  Since TZ and TFP are positive,
6410      * they will be zero when EL2 is not present.
6411      */
6412     if (el <= 2 && arm_is_el2_enabled(env)) {
6413         if (env->cp15.cptr_el[2] & CPTR_TZ) {
6414             return 2;
6415         }
6416         if (env->cp15.cptr_el[2] & CPTR_TFP) {
6417             return 0;
6418         }
6419     }
6420 
6421     /* CPTR_EL3.  Since EZ is negative we must check for EL3.  */
6422     if (arm_feature(env, ARM_FEATURE_EL3)
6423         && !(env->cp15.cptr_el[3] & CPTR_EZ)) {
6424         return 3;
6425     }
6426 #endif
6427     return 0;
6428 }
6429 
6430 uint32_t aarch64_sve_zcr_get_valid_len(ARMCPU *cpu, uint32_t start_len)
6431 {
6432     uint32_t end_len;
6433 
6434     start_len = MIN(start_len, ARM_MAX_VQ - 1);
6435     end_len = start_len;
6436 
6437     if (!test_bit(start_len, cpu->sve_vq_map)) {
6438         end_len = find_last_bit(cpu->sve_vq_map, start_len);
6439         assert(end_len < start_len);
6440     }
6441     return end_len;
6442 }
6443 
6444 /*
6445  * Given that SVE is enabled, return the vector length for EL.
6446  */
6447 uint32_t sve_zcr_len_for_el(CPUARMState *env, int el)
6448 {
6449     ARMCPU *cpu = env_archcpu(env);
6450     uint32_t zcr_len = cpu->sve_max_vq - 1;
6451 
6452     if (el <= 1) {
6453         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[1]);
6454     }
6455     if (el <= 2 && arm_feature(env, ARM_FEATURE_EL2)) {
6456         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[2]);
6457     }
6458     if (arm_feature(env, ARM_FEATURE_EL3)) {
6459         zcr_len = MIN(zcr_len, 0xf & (uint32_t)env->vfp.zcr_el[3]);
6460     }
6461 
6462     return aarch64_sve_zcr_get_valid_len(cpu, zcr_len);
6463 }
6464 
6465 static void zcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6466                       uint64_t value)
6467 {
6468     int cur_el = arm_current_el(env);
6469     int old_len = sve_zcr_len_for_el(env, cur_el);
6470     int new_len;
6471 
6472     /* Bits other than [3:0] are RAZ/WI.  */
6473     QEMU_BUILD_BUG_ON(ARM_MAX_VQ > 16);
6474     raw_write(env, ri, value & 0xf);
6475 
6476     /*
6477      * Because we arrived here, we know both FP and SVE are enabled;
6478      * otherwise we would have trapped access to the ZCR_ELn register.
6479      */
6480     new_len = sve_zcr_len_for_el(env, cur_el);
6481     if (new_len < old_len) {
6482         aarch64_sve_narrow_vq(env, new_len + 1);
6483     }
6484 }
6485 
6486 static const ARMCPRegInfo zcr_el1_reginfo = {
6487     .name = "ZCR_EL1", .state = ARM_CP_STATE_AA64,
6488     .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 2, .opc2 = 0,
6489     .access = PL1_RW, .type = ARM_CP_SVE,
6490     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[1]),
6491     .writefn = zcr_write, .raw_writefn = raw_write
6492 };
6493 
6494 static const ARMCPRegInfo zcr_el2_reginfo = {
6495     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6496     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6497     .access = PL2_RW, .type = ARM_CP_SVE,
6498     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[2]),
6499     .writefn = zcr_write, .raw_writefn = raw_write
6500 };
6501 
6502 static const ARMCPRegInfo zcr_no_el2_reginfo = {
6503     .name = "ZCR_EL2", .state = ARM_CP_STATE_AA64,
6504     .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 2, .opc2 = 0,
6505     .access = PL2_RW, .type = ARM_CP_SVE,
6506     .readfn = arm_cp_read_zero, .writefn = arm_cp_write_ignore
6507 };
6508 
6509 static const ARMCPRegInfo zcr_el3_reginfo = {
6510     .name = "ZCR_EL3", .state = ARM_CP_STATE_AA64,
6511     .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 2, .opc2 = 0,
6512     .access = PL3_RW, .type = ARM_CP_SVE,
6513     .fieldoffset = offsetof(CPUARMState, vfp.zcr_el[3]),
6514     .writefn = zcr_write, .raw_writefn = raw_write
6515 };
6516 
6517 void hw_watchpoint_update(ARMCPU *cpu, int n)
6518 {
6519     CPUARMState *env = &cpu->env;
6520     vaddr len = 0;
6521     vaddr wvr = env->cp15.dbgwvr[n];
6522     uint64_t wcr = env->cp15.dbgwcr[n];
6523     int mask;
6524     int flags = BP_CPU | BP_STOP_BEFORE_ACCESS;
6525 
6526     if (env->cpu_watchpoint[n]) {
6527         cpu_watchpoint_remove_by_ref(CPU(cpu), env->cpu_watchpoint[n]);
6528         env->cpu_watchpoint[n] = NULL;
6529     }
6530 
6531     if (!extract64(wcr, 0, 1)) {
6532         /* E bit clear : watchpoint disabled */
6533         return;
6534     }
6535 
6536     switch (extract64(wcr, 3, 2)) {
6537     case 0:
6538         /* LSC 00 is reserved and must behave as if the wp is disabled */
6539         return;
6540     case 1:
6541         flags |= BP_MEM_READ;
6542         break;
6543     case 2:
6544         flags |= BP_MEM_WRITE;
6545         break;
6546     case 3:
6547         flags |= BP_MEM_ACCESS;
6548         break;
6549     }
6550 
6551     /* Attempts to use both MASK and BAS fields simultaneously are
6552      * CONSTRAINED UNPREDICTABLE; we opt to ignore BAS in this case,
6553      * thus generating a watchpoint for every byte in the masked region.
6554      */
6555     mask = extract64(wcr, 24, 4);
6556     if (mask == 1 || mask == 2) {
6557         /* Reserved values of MASK; we must act as if the mask value was
6558          * some non-reserved value, or as if the watchpoint were disabled.
6559          * We choose the latter.
6560          */
6561         return;
6562     } else if (mask) {
6563         /* Watchpoint covers an aligned area up to 2GB in size */
6564         len = 1ULL << mask;
6565         /* If masked bits in WVR are not zero it's CONSTRAINED UNPREDICTABLE
6566          * whether the watchpoint fires when the unmasked bits match; we opt
6567          * to generate the exceptions.
6568          */
6569         wvr &= ~(len - 1);
6570     } else {
6571         /* Watchpoint covers bytes defined by the byte address select bits */
6572         int bas = extract64(wcr, 5, 8);
6573         int basstart;
6574 
6575         if (extract64(wvr, 2, 1)) {
6576             /* Deprecated case of an only 4-aligned address. BAS[7:4] are
6577              * ignored, and BAS[3:0] define which bytes to watch.
6578              */
6579             bas &= 0xf;
6580         }
6581 
6582         if (bas == 0) {
6583             /* This must act as if the watchpoint is disabled */
6584             return;
6585         }
6586 
6587         /* The BAS bits are supposed to be programmed to indicate a contiguous
6588          * range of bytes. Otherwise it is CONSTRAINED UNPREDICTABLE whether
6589          * we fire for each byte in the word/doubleword addressed by the WVR.
6590          * We choose to ignore any non-zero bits after the first range of 1s.
6591          */
6592         basstart = ctz32(bas);
6593         len = cto32(bas >> basstart);
6594         wvr += basstart;
6595     }
6596 
6597     cpu_watchpoint_insert(CPU(cpu), wvr, len, flags,
6598                           &env->cpu_watchpoint[n]);
6599 }
6600 
6601 void hw_watchpoint_update_all(ARMCPU *cpu)
6602 {
6603     int i;
6604     CPUARMState *env = &cpu->env;
6605 
6606     /* Completely clear out existing QEMU watchpoints and our array, to
6607      * avoid possible stale entries following migration load.
6608      */
6609     cpu_watchpoint_remove_all(CPU(cpu), BP_CPU);
6610     memset(env->cpu_watchpoint, 0, sizeof(env->cpu_watchpoint));
6611 
6612     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_watchpoint); i++) {
6613         hw_watchpoint_update(cpu, i);
6614     }
6615 }
6616 
6617 static void dbgwvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6618                          uint64_t value)
6619 {
6620     ARMCPU *cpu = env_archcpu(env);
6621     int i = ri->crm;
6622 
6623     /* Bits [63:49] are hardwired to the value of bit [48]; that is, the
6624      * register reads and behaves as if values written are sign extended.
6625      * Bits [1:0] are RES0.
6626      */
6627     value = sextract64(value, 0, 49) & ~3ULL;
6628 
6629     raw_write(env, ri, value);
6630     hw_watchpoint_update(cpu, i);
6631 }
6632 
6633 static void dbgwcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6634                          uint64_t value)
6635 {
6636     ARMCPU *cpu = env_archcpu(env);
6637     int i = ri->crm;
6638 
6639     raw_write(env, ri, value);
6640     hw_watchpoint_update(cpu, i);
6641 }
6642 
6643 void hw_breakpoint_update(ARMCPU *cpu, int n)
6644 {
6645     CPUARMState *env = &cpu->env;
6646     uint64_t bvr = env->cp15.dbgbvr[n];
6647     uint64_t bcr = env->cp15.dbgbcr[n];
6648     vaddr addr;
6649     int bt;
6650     int flags = BP_CPU;
6651 
6652     if (env->cpu_breakpoint[n]) {
6653         cpu_breakpoint_remove_by_ref(CPU(cpu), env->cpu_breakpoint[n]);
6654         env->cpu_breakpoint[n] = NULL;
6655     }
6656 
6657     if (!extract64(bcr, 0, 1)) {
6658         /* E bit clear : watchpoint disabled */
6659         return;
6660     }
6661 
6662     bt = extract64(bcr, 20, 4);
6663 
6664     switch (bt) {
6665     case 4: /* unlinked address mismatch (reserved if AArch64) */
6666     case 5: /* linked address mismatch (reserved if AArch64) */
6667         qemu_log_mask(LOG_UNIMP,
6668                       "arm: address mismatch breakpoint types not implemented\n");
6669         return;
6670     case 0: /* unlinked address match */
6671     case 1: /* linked address match */
6672     {
6673         /* Bits [63:49] are hardwired to the value of bit [48]; that is,
6674          * we behave as if the register was sign extended. Bits [1:0] are
6675          * RES0. The BAS field is used to allow setting breakpoints on 16
6676          * bit wide instructions; it is CONSTRAINED UNPREDICTABLE whether
6677          * a bp will fire if the addresses covered by the bp and the addresses
6678          * covered by the insn overlap but the insn doesn't start at the
6679          * start of the bp address range. We choose to require the insn and
6680          * the bp to have the same address. The constraints on writing to
6681          * BAS enforced in dbgbcr_write mean we have only four cases:
6682          *  0b0000  => no breakpoint
6683          *  0b0011  => breakpoint on addr
6684          *  0b1100  => breakpoint on addr + 2
6685          *  0b1111  => breakpoint on addr
6686          * See also figure D2-3 in the v8 ARM ARM (DDI0487A.c).
6687          */
6688         int bas = extract64(bcr, 5, 4);
6689         addr = sextract64(bvr, 0, 49) & ~3ULL;
6690         if (bas == 0) {
6691             return;
6692         }
6693         if (bas == 0xc) {
6694             addr += 2;
6695         }
6696         break;
6697     }
6698     case 2: /* unlinked context ID match */
6699     case 8: /* unlinked VMID match (reserved if no EL2) */
6700     case 10: /* unlinked context ID and VMID match (reserved if no EL2) */
6701         qemu_log_mask(LOG_UNIMP,
6702                       "arm: unlinked context breakpoint types not implemented\n");
6703         return;
6704     case 9: /* linked VMID match (reserved if no EL2) */
6705     case 11: /* linked context ID and VMID match (reserved if no EL2) */
6706     case 3: /* linked context ID match */
6707     default:
6708         /* We must generate no events for Linked context matches (unless
6709          * they are linked to by some other bp/wp, which is handled in
6710          * updates for the linking bp/wp). We choose to also generate no events
6711          * for reserved values.
6712          */
6713         return;
6714     }
6715 
6716     cpu_breakpoint_insert(CPU(cpu), addr, flags, &env->cpu_breakpoint[n]);
6717 }
6718 
6719 void hw_breakpoint_update_all(ARMCPU *cpu)
6720 {
6721     int i;
6722     CPUARMState *env = &cpu->env;
6723 
6724     /* Completely clear out existing QEMU breakpoints and our array, to
6725      * avoid possible stale entries following migration load.
6726      */
6727     cpu_breakpoint_remove_all(CPU(cpu), BP_CPU);
6728     memset(env->cpu_breakpoint, 0, sizeof(env->cpu_breakpoint));
6729 
6730     for (i = 0; i < ARRAY_SIZE(cpu->env.cpu_breakpoint); i++) {
6731         hw_breakpoint_update(cpu, i);
6732     }
6733 }
6734 
6735 static void dbgbvr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6736                          uint64_t value)
6737 {
6738     ARMCPU *cpu = env_archcpu(env);
6739     int i = ri->crm;
6740 
6741     raw_write(env, ri, value);
6742     hw_breakpoint_update(cpu, i);
6743 }
6744 
6745 static void dbgbcr_write(CPUARMState *env, const ARMCPRegInfo *ri,
6746                          uint64_t value)
6747 {
6748     ARMCPU *cpu = env_archcpu(env);
6749     int i = ri->crm;
6750 
6751     /* BAS[3] is a read-only copy of BAS[2], and BAS[1] a read-only
6752      * copy of BAS[0].
6753      */
6754     value = deposit64(value, 6, 1, extract64(value, 5, 1));
6755     value = deposit64(value, 8, 1, extract64(value, 7, 1));
6756 
6757     raw_write(env, ri, value);
6758     hw_breakpoint_update(cpu, i);
6759 }
6760 
6761 static void define_debug_regs(ARMCPU *cpu)
6762 {
6763     /* Define v7 and v8 architectural debug registers.
6764      * These are just dummy implementations for now.
6765      */
6766     int i;
6767     int wrps, brps, ctx_cmps;
6768 
6769     /*
6770      * The Arm ARM says DBGDIDR is optional and deprecated if EL1 cannot
6771      * use AArch32.  Given that bit 15 is RES1, if the value is 0 then
6772      * the register must not exist for this cpu.
6773      */
6774     if (cpu->isar.dbgdidr != 0) {
6775         ARMCPRegInfo dbgdidr = {
6776             .name = "DBGDIDR", .cp = 14, .crn = 0, .crm = 0,
6777             .opc1 = 0, .opc2 = 0,
6778             .access = PL0_R, .accessfn = access_tda,
6779             .type = ARM_CP_CONST, .resetvalue = cpu->isar.dbgdidr,
6780         };
6781         define_one_arm_cp_reg(cpu, &dbgdidr);
6782     }
6783 
6784     /* Note that all these register fields hold "number of Xs minus 1". */
6785     brps = arm_num_brps(cpu);
6786     wrps = arm_num_wrps(cpu);
6787     ctx_cmps = arm_num_ctx_cmps(cpu);
6788 
6789     assert(ctx_cmps <= brps);
6790 
6791     define_arm_cp_regs(cpu, debug_cp_reginfo);
6792 
6793     if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
6794         define_arm_cp_regs(cpu, debug_lpae_cp_reginfo);
6795     }
6796 
6797     for (i = 0; i < brps; i++) {
6798         ARMCPRegInfo dbgregs[] = {
6799             { .name = "DBGBVR", .state = ARM_CP_STATE_BOTH,
6800               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,
6801               .access = PL1_RW, .accessfn = access_tda,
6802               .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]),
6803               .writefn = dbgbvr_write, .raw_writefn = raw_write
6804             },
6805             { .name = "DBGBCR", .state = ARM_CP_STATE_BOTH,
6806               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,
6807               .access = PL1_RW, .accessfn = access_tda,
6808               .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]),
6809               .writefn = dbgbcr_write, .raw_writefn = raw_write
6810             },
6811             REGINFO_SENTINEL
6812         };
6813         define_arm_cp_regs(cpu, dbgregs);
6814     }
6815 
6816     for (i = 0; i < wrps; i++) {
6817         ARMCPRegInfo dbgregs[] = {
6818             { .name = "DBGWVR", .state = ARM_CP_STATE_BOTH,
6819               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,
6820               .access = PL1_RW, .accessfn = access_tda,
6821               .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]),
6822               .writefn = dbgwvr_write, .raw_writefn = raw_write
6823             },
6824             { .name = "DBGWCR", .state = ARM_CP_STATE_BOTH,
6825               .cp = 14, .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,
6826               .access = PL1_RW, .accessfn = access_tda,
6827               .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]),
6828               .writefn = dbgwcr_write, .raw_writefn = raw_write
6829             },
6830             REGINFO_SENTINEL
6831         };
6832         define_arm_cp_regs(cpu, dbgregs);
6833     }
6834 }
6835 
6836 static void define_pmu_regs(ARMCPU *cpu)
6837 {
6838     /*
6839      * v7 performance monitor control register: same implementor
6840      * field as main ID register, and we implement four counters in
6841      * addition to the cycle count register.
6842      */
6843     unsigned int i, pmcrn = PMCR_NUM_COUNTERS;
6844     ARMCPRegInfo pmcr = {
6845         .name = "PMCR", .cp = 15, .crn = 9, .crm = 12, .opc1 = 0, .opc2 = 0,
6846         .access = PL0_RW,
6847         .type = ARM_CP_IO | ARM_CP_ALIAS,
6848         .fieldoffset = offsetoflow32(CPUARMState, cp15.c9_pmcr),
6849         .accessfn = pmreg_access, .writefn = pmcr_write,
6850         .raw_writefn = raw_write,
6851     };
6852     ARMCPRegInfo pmcr64 = {
6853         .name = "PMCR_EL0", .state = ARM_CP_STATE_AA64,
6854         .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 0,
6855         .access = PL0_RW, .accessfn = pmreg_access,
6856         .type = ARM_CP_IO,
6857         .fieldoffset = offsetof(CPUARMState, cp15.c9_pmcr),
6858         .resetvalue = (cpu->midr & 0xff000000) | (pmcrn << PMCRN_SHIFT) |
6859                       PMCRLC,
6860         .writefn = pmcr_write, .raw_writefn = raw_write,
6861     };
6862     define_one_arm_cp_reg(cpu, &pmcr);
6863     define_one_arm_cp_reg(cpu, &pmcr64);
6864     for (i = 0; i < pmcrn; i++) {
6865         char *pmevcntr_name = g_strdup_printf("PMEVCNTR%d", i);
6866         char *pmevcntr_el0_name = g_strdup_printf("PMEVCNTR%d_EL0", i);
6867         char *pmevtyper_name = g_strdup_printf("PMEVTYPER%d", i);
6868         char *pmevtyper_el0_name = g_strdup_printf("PMEVTYPER%d_EL0", i);
6869         ARMCPRegInfo pmev_regs[] = {
6870             { .name = pmevcntr_name, .cp = 15, .crn = 14,
6871               .crm = 8 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6872               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6873               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6874               .accessfn = pmreg_access },
6875             { .name = pmevcntr_el0_name, .state = ARM_CP_STATE_AA64,
6876               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 8 | (3 & (i >> 3)),
6877               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6878               .type = ARM_CP_IO,
6879               .readfn = pmevcntr_readfn, .writefn = pmevcntr_writefn,
6880               .raw_readfn = pmevcntr_rawread,
6881               .raw_writefn = pmevcntr_rawwrite },
6882             { .name = pmevtyper_name, .cp = 15, .crn = 14,
6883               .crm = 12 | (3 & (i >> 3)), .opc1 = 0, .opc2 = i & 7,
6884               .access = PL0_RW, .type = ARM_CP_IO | ARM_CP_ALIAS,
6885               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6886               .accessfn = pmreg_access },
6887             { .name = pmevtyper_el0_name, .state = ARM_CP_STATE_AA64,
6888               .opc0 = 3, .opc1 = 3, .crn = 14, .crm = 12 | (3 & (i >> 3)),
6889               .opc2 = i & 7, .access = PL0_RW, .accessfn = pmreg_access,
6890               .type = ARM_CP_IO,
6891               .readfn = pmevtyper_readfn, .writefn = pmevtyper_writefn,
6892               .raw_writefn = pmevtyper_rawwrite },
6893             REGINFO_SENTINEL
6894         };
6895         define_arm_cp_regs(cpu, pmev_regs);
6896         g_free(pmevcntr_name);
6897         g_free(pmevcntr_el0_name);
6898         g_free(pmevtyper_name);
6899         g_free(pmevtyper_el0_name);
6900     }
6901     if (cpu_isar_feature(aa32_pmu_8_1, cpu)) {
6902         ARMCPRegInfo v81_pmu_regs[] = {
6903             { .name = "PMCEID2", .state = ARM_CP_STATE_AA32,
6904               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 4,
6905               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6906               .resetvalue = extract64(cpu->pmceid0, 32, 32) },
6907             { .name = "PMCEID3", .state = ARM_CP_STATE_AA32,
6908               .cp = 15, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 5,
6909               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6910               .resetvalue = extract64(cpu->pmceid1, 32, 32) },
6911             REGINFO_SENTINEL
6912         };
6913         define_arm_cp_regs(cpu, v81_pmu_regs);
6914     }
6915     if (cpu_isar_feature(any_pmu_8_4, cpu)) {
6916         static const ARMCPRegInfo v84_pmmir = {
6917             .name = "PMMIR_EL1", .state = ARM_CP_STATE_BOTH,
6918             .opc0 = 3, .opc1 = 0, .crn = 9, .crm = 14, .opc2 = 6,
6919             .access = PL1_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
6920             .resetvalue = 0
6921         };
6922         define_one_arm_cp_reg(cpu, &v84_pmmir);
6923     }
6924 }
6925 
6926 /* We don't know until after realize whether there's a GICv3
6927  * attached, and that is what registers the gicv3 sysregs.
6928  * So we have to fill in the GIC fields in ID_PFR/ID_PFR1_EL1/ID_AA64PFR0_EL1
6929  * at runtime.
6930  */
6931 static uint64_t id_pfr1_read(CPUARMState *env, const ARMCPRegInfo *ri)
6932 {
6933     ARMCPU *cpu = env_archcpu(env);
6934     uint64_t pfr1 = cpu->isar.id_pfr1;
6935 
6936     if (env->gicv3state) {
6937         pfr1 |= 1 << 28;
6938     }
6939     return pfr1;
6940 }
6941 
6942 #ifndef CONFIG_USER_ONLY
6943 static uint64_t id_aa64pfr0_read(CPUARMState *env, const ARMCPRegInfo *ri)
6944 {
6945     ARMCPU *cpu = env_archcpu(env);
6946     uint64_t pfr0 = cpu->isar.id_aa64pfr0;
6947 
6948     if (env->gicv3state) {
6949         pfr0 |= 1 << 24;
6950     }
6951     return pfr0;
6952 }
6953 #endif
6954 
6955 /* Shared logic between LORID and the rest of the LOR* registers.
6956  * Secure state exclusion has already been dealt with.
6957  */
6958 static CPAccessResult access_lor_ns(CPUARMState *env,
6959                                     const ARMCPRegInfo *ri, bool isread)
6960 {
6961     int el = arm_current_el(env);
6962 
6963     if (el < 2 && (arm_hcr_el2_eff(env) & HCR_TLOR)) {
6964         return CP_ACCESS_TRAP_EL2;
6965     }
6966     if (el < 3 && (env->cp15.scr_el3 & SCR_TLOR)) {
6967         return CP_ACCESS_TRAP_EL3;
6968     }
6969     return CP_ACCESS_OK;
6970 }
6971 
6972 static CPAccessResult access_lor_other(CPUARMState *env,
6973                                        const ARMCPRegInfo *ri, bool isread)
6974 {
6975     if (arm_is_secure_below_el3(env)) {
6976         /* Access denied in secure mode.  */
6977         return CP_ACCESS_TRAP;
6978     }
6979     return access_lor_ns(env, ri, isread);
6980 }
6981 
6982 /*
6983  * A trivial implementation of ARMv8.1-LOR leaves all of these
6984  * registers fixed at 0, which indicates that there are zero
6985  * supported Limited Ordering regions.
6986  */
6987 static const ARMCPRegInfo lor_reginfo[] = {
6988     { .name = "LORSA_EL1", .state = ARM_CP_STATE_AA64,
6989       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 0,
6990       .access = PL1_RW, .accessfn = access_lor_other,
6991       .type = ARM_CP_CONST, .resetvalue = 0 },
6992     { .name = "LOREA_EL1", .state = ARM_CP_STATE_AA64,
6993       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 1,
6994       .access = PL1_RW, .accessfn = access_lor_other,
6995       .type = ARM_CP_CONST, .resetvalue = 0 },
6996     { .name = "LORN_EL1", .state = ARM_CP_STATE_AA64,
6997       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 2,
6998       .access = PL1_RW, .accessfn = access_lor_other,
6999       .type = ARM_CP_CONST, .resetvalue = 0 },
7000     { .name = "LORC_EL1", .state = ARM_CP_STATE_AA64,
7001       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 3,
7002       .access = PL1_RW, .accessfn = access_lor_other,
7003       .type = ARM_CP_CONST, .resetvalue = 0 },
7004     { .name = "LORID_EL1", .state = ARM_CP_STATE_AA64,
7005       .opc0 = 3, .opc1 = 0, .crn = 10, .crm = 4, .opc2 = 7,
7006       .access = PL1_R, .accessfn = access_lor_ns,
7007       .type = ARM_CP_CONST, .resetvalue = 0 },
7008     REGINFO_SENTINEL
7009 };
7010 
7011 #ifdef TARGET_AARCH64
7012 static CPAccessResult access_pauth(CPUARMState *env, const ARMCPRegInfo *ri,
7013                                    bool isread)
7014 {
7015     int el = arm_current_el(env);
7016 
7017     if (el < 2 &&
7018         arm_feature(env, ARM_FEATURE_EL2) &&
7019         !(arm_hcr_el2_eff(env) & HCR_APK)) {
7020         return CP_ACCESS_TRAP_EL2;
7021     }
7022     if (el < 3 &&
7023         arm_feature(env, ARM_FEATURE_EL3) &&
7024         !(env->cp15.scr_el3 & SCR_APK)) {
7025         return CP_ACCESS_TRAP_EL3;
7026     }
7027     return CP_ACCESS_OK;
7028 }
7029 
7030 static const ARMCPRegInfo pauth_reginfo[] = {
7031     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
7032       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
7033       .access = PL1_RW, .accessfn = access_pauth,
7034       .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
7035     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
7036       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
7037       .access = PL1_RW, .accessfn = access_pauth,
7038       .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
7039     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
7040       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
7041       .access = PL1_RW, .accessfn = access_pauth,
7042       .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
7043     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
7044       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
7045       .access = PL1_RW, .accessfn = access_pauth,
7046       .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
7047     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
7048       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
7049       .access = PL1_RW, .accessfn = access_pauth,
7050       .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
7051     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
7052       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
7053       .access = PL1_RW, .accessfn = access_pauth,
7054       .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
7055     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
7056       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
7057       .access = PL1_RW, .accessfn = access_pauth,
7058       .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
7059     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
7060       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
7061       .access = PL1_RW, .accessfn = access_pauth,
7062       .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
7063     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
7064       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
7065       .access = PL1_RW, .accessfn = access_pauth,
7066       .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
7067     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
7068       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
7069       .access = PL1_RW, .accessfn = access_pauth,
7070       .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
7071     REGINFO_SENTINEL
7072 };
7073 
7074 static const ARMCPRegInfo tlbirange_reginfo[] = {
7075     { .name = "TLBI_RVAE1IS", .state = ARM_CP_STATE_AA64,
7076       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 1,
7077       .access = PL1_W, .type = ARM_CP_NO_RAW,
7078       .writefn = tlbi_aa64_rvae1is_write },
7079     { .name = "TLBI_RVAAE1IS", .state = ARM_CP_STATE_AA64,
7080       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 3,
7081       .access = PL1_W, .type = ARM_CP_NO_RAW,
7082       .writefn = tlbi_aa64_rvae1is_write },
7083    { .name = "TLBI_RVALE1IS", .state = ARM_CP_STATE_AA64,
7084       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 5,
7085       .access = PL1_W, .type = ARM_CP_NO_RAW,
7086       .writefn = tlbi_aa64_rvae1is_write },
7087     { .name = "TLBI_RVAALE1IS", .state = ARM_CP_STATE_AA64,
7088       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 2, .opc2 = 7,
7089       .access = PL1_W, .type = ARM_CP_NO_RAW,
7090       .writefn = tlbi_aa64_rvae1is_write },
7091     { .name = "TLBI_RVAE1OS", .state = ARM_CP_STATE_AA64,
7092       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 1,
7093       .access = PL1_W, .type = ARM_CP_NO_RAW,
7094       .writefn = tlbi_aa64_rvae1is_write },
7095     { .name = "TLBI_RVAAE1OS", .state = ARM_CP_STATE_AA64,
7096       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 3,
7097       .access = PL1_W, .type = ARM_CP_NO_RAW,
7098       .writefn = tlbi_aa64_rvae1is_write },
7099    { .name = "TLBI_RVALE1OS", .state = ARM_CP_STATE_AA64,
7100       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 5,
7101       .access = PL1_W, .type = ARM_CP_NO_RAW,
7102       .writefn = tlbi_aa64_rvae1is_write },
7103     { .name = "TLBI_RVAALE1OS", .state = ARM_CP_STATE_AA64,
7104       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 5, .opc2 = 7,
7105       .access = PL1_W, .type = ARM_CP_NO_RAW,
7106       .writefn = tlbi_aa64_rvae1is_write },
7107     { .name = "TLBI_RVAE1", .state = ARM_CP_STATE_AA64,
7108       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 1,
7109       .access = PL1_W, .type = ARM_CP_NO_RAW,
7110       .writefn = tlbi_aa64_rvae1_write },
7111     { .name = "TLBI_RVAAE1", .state = ARM_CP_STATE_AA64,
7112       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 3,
7113       .access = PL1_W, .type = ARM_CP_NO_RAW,
7114       .writefn = tlbi_aa64_rvae1_write },
7115    { .name = "TLBI_RVALE1", .state = ARM_CP_STATE_AA64,
7116       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 5,
7117       .access = PL1_W, .type = ARM_CP_NO_RAW,
7118       .writefn = tlbi_aa64_rvae1_write },
7119     { .name = "TLBI_RVAALE1", .state = ARM_CP_STATE_AA64,
7120       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 6, .opc2 = 7,
7121       .access = PL1_W, .type = ARM_CP_NO_RAW,
7122       .writefn = tlbi_aa64_rvae1_write },
7123     { .name = "TLBI_RIPAS2E1IS", .state = ARM_CP_STATE_AA64,
7124       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 2,
7125       .access = PL2_W, .type = ARM_CP_NOP },
7126     { .name = "TLBI_RIPAS2LE1IS", .state = ARM_CP_STATE_AA64,
7127       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 0, .opc2 = 6,
7128       .access = PL2_W, .type = ARM_CP_NOP },
7129     { .name = "TLBI_RVAE2IS", .state = ARM_CP_STATE_AA64,
7130       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 1,
7131       .access = PL2_W, .type = ARM_CP_NO_RAW,
7132       .writefn = tlbi_aa64_rvae2is_write },
7133    { .name = "TLBI_RVALE2IS", .state = ARM_CP_STATE_AA64,
7134       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 2, .opc2 = 5,
7135       .access = PL2_W, .type = ARM_CP_NO_RAW,
7136       .writefn = tlbi_aa64_rvae2is_write },
7137     { .name = "TLBI_RIPAS2E1", .state = ARM_CP_STATE_AA64,
7138       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 2,
7139       .access = PL2_W, .type = ARM_CP_NOP },
7140    { .name = "TLBI_RIPAS2LE1", .state = ARM_CP_STATE_AA64,
7141       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 6,
7142       .access = PL2_W, .type = ARM_CP_NOP },
7143    { .name = "TLBI_RVAE2OS", .state = ARM_CP_STATE_AA64,
7144       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 1,
7145       .access = PL2_W, .type = ARM_CP_NO_RAW,
7146       .writefn = tlbi_aa64_rvae2is_write },
7147    { .name = "TLBI_RVALE2OS", .state = ARM_CP_STATE_AA64,
7148       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 5, .opc2 = 5,
7149       .access = PL2_W, .type = ARM_CP_NO_RAW,
7150       .writefn = tlbi_aa64_rvae2is_write },
7151     { .name = "TLBI_RVAE2", .state = ARM_CP_STATE_AA64,
7152       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 1,
7153       .access = PL2_W, .type = ARM_CP_NO_RAW,
7154       .writefn = tlbi_aa64_rvae2_write },
7155    { .name = "TLBI_RVALE2", .state = ARM_CP_STATE_AA64,
7156       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 6, .opc2 = 5,
7157       .access = PL2_W, .type = ARM_CP_NO_RAW,
7158       .writefn = tlbi_aa64_rvae2_write },
7159    { .name = "TLBI_RVAE3IS", .state = ARM_CP_STATE_AA64,
7160       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 1,
7161       .access = PL3_W, .type = ARM_CP_NO_RAW,
7162       .writefn = tlbi_aa64_rvae3is_write },
7163    { .name = "TLBI_RVALE3IS", .state = ARM_CP_STATE_AA64,
7164       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 2, .opc2 = 5,
7165       .access = PL3_W, .type = ARM_CP_NO_RAW,
7166       .writefn = tlbi_aa64_rvae3is_write },
7167    { .name = "TLBI_RVAE3OS", .state = ARM_CP_STATE_AA64,
7168       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 1,
7169       .access = PL3_W, .type = ARM_CP_NO_RAW,
7170       .writefn = tlbi_aa64_rvae3is_write },
7171    { .name = "TLBI_RVALE3OS", .state = ARM_CP_STATE_AA64,
7172       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 5, .opc2 = 5,
7173       .access = PL3_W, .type = ARM_CP_NO_RAW,
7174       .writefn = tlbi_aa64_rvae3is_write },
7175    { .name = "TLBI_RVAE3", .state = ARM_CP_STATE_AA64,
7176       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 1,
7177       .access = PL3_W, .type = ARM_CP_NO_RAW,
7178       .writefn = tlbi_aa64_rvae3_write },
7179    { .name = "TLBI_RVALE3", .state = ARM_CP_STATE_AA64,
7180       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 6, .opc2 = 5,
7181       .access = PL3_W, .type = ARM_CP_NO_RAW,
7182       .writefn = tlbi_aa64_rvae3_write },
7183     REGINFO_SENTINEL
7184 };
7185 
7186 static const ARMCPRegInfo tlbios_reginfo[] = {
7187     { .name = "TLBI_VMALLE1OS", .state = ARM_CP_STATE_AA64,
7188       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 0,
7189       .access = PL1_W, .type = ARM_CP_NO_RAW,
7190       .writefn = tlbi_aa64_vmalle1is_write },
7191     { .name = "TLBI_ASIDE1OS", .state = ARM_CP_STATE_AA64,
7192       .opc0 = 1, .opc1 = 0, .crn = 8, .crm = 1, .opc2 = 2,
7193       .access = PL1_W, .type = ARM_CP_NO_RAW,
7194       .writefn = tlbi_aa64_vmalle1is_write },
7195     { .name = "TLBI_ALLE2OS", .state = ARM_CP_STATE_AA64,
7196       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 0,
7197       .access = PL2_W, .type = ARM_CP_NO_RAW,
7198       .writefn = tlbi_aa64_alle2is_write },
7199    { .name = "TLBI_ALLE1OS", .state = ARM_CP_STATE_AA64,
7200       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 4,
7201       .access = PL2_W, .type = ARM_CP_NO_RAW,
7202       .writefn = tlbi_aa64_alle1is_write },
7203     { .name = "TLBI_VMALLS12E1OS", .state = ARM_CP_STATE_AA64,
7204       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 1, .opc2 = 6,
7205       .access = PL2_W, .type = ARM_CP_NO_RAW,
7206       .writefn = tlbi_aa64_alle1is_write },
7207     { .name = "TLBI_IPAS2E1OS", .state = ARM_CP_STATE_AA64,
7208       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 0,
7209       .access = PL2_W, .type = ARM_CP_NOP },
7210     { .name = "TLBI_RIPAS2E1OS", .state = ARM_CP_STATE_AA64,
7211       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 3,
7212       .access = PL2_W, .type = ARM_CP_NOP },
7213     { .name = "TLBI_IPAS2LE1OS", .state = ARM_CP_STATE_AA64,
7214       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 4,
7215       .access = PL2_W, .type = ARM_CP_NOP },
7216     { .name = "TLBI_RIPAS2LE1OS", .state = ARM_CP_STATE_AA64,
7217       .opc0 = 1, .opc1 = 4, .crn = 8, .crm = 4, .opc2 = 7,
7218       .access = PL2_W, .type = ARM_CP_NOP },
7219     { .name = "TLBI_ALLE3OS", .state = ARM_CP_STATE_AA64,
7220       .opc0 = 1, .opc1 = 6, .crn = 8, .crm = 1, .opc2 = 0,
7221       .access = PL3_W, .type = ARM_CP_NO_RAW,
7222       .writefn = tlbi_aa64_alle3is_write },
7223     REGINFO_SENTINEL
7224 };
7225 
7226 static uint64_t rndr_readfn(CPUARMState *env, const ARMCPRegInfo *ri)
7227 {
7228     Error *err = NULL;
7229     uint64_t ret;
7230 
7231     /* Success sets NZCV = 0000.  */
7232     env->NF = env->CF = env->VF = 0, env->ZF = 1;
7233 
7234     if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
7235         /*
7236          * ??? Failed, for unknown reasons in the crypto subsystem.
7237          * The best we can do is log the reason and return the
7238          * timed-out indication to the guest.  There is no reason
7239          * we know to expect this failure to be transitory, so the
7240          * guest may well hang retrying the operation.
7241          */
7242         qemu_log_mask(LOG_UNIMP, "%s: Crypto failure: %s",
7243                       ri->name, error_get_pretty(err));
7244         error_free(err);
7245 
7246         env->ZF = 0; /* NZCF = 0100 */
7247         return 0;
7248     }
7249     return ret;
7250 }
7251 
7252 /* We do not support re-seeding, so the two registers operate the same.  */
7253 static const ARMCPRegInfo rndr_reginfo[] = {
7254     { .name = "RNDR", .state = ARM_CP_STATE_AA64,
7255       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7256       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 0,
7257       .access = PL0_R, .readfn = rndr_readfn },
7258     { .name = "RNDRRS", .state = ARM_CP_STATE_AA64,
7259       .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END | ARM_CP_IO,
7260       .opc0 = 3, .opc1 = 3, .crn = 2, .crm = 4, .opc2 = 1,
7261       .access = PL0_R, .readfn = rndr_readfn },
7262     REGINFO_SENTINEL
7263 };
7264 
7265 #ifndef CONFIG_USER_ONLY
7266 static void dccvap_writefn(CPUARMState *env, const ARMCPRegInfo *opaque,
7267                           uint64_t value)
7268 {
7269     ARMCPU *cpu = env_archcpu(env);
7270     /* CTR_EL0 System register -> DminLine, bits [19:16] */
7271     uint64_t dline_size = 4 << ((cpu->ctr >> 16) & 0xF);
7272     uint64_t vaddr_in = (uint64_t) value;
7273     uint64_t vaddr = vaddr_in & ~(dline_size - 1);
7274     void *haddr;
7275     int mem_idx = cpu_mmu_index(env, false);
7276 
7277     /* This won't be crossing page boundaries */
7278     haddr = probe_read(env, vaddr, dline_size, mem_idx, GETPC());
7279     if (haddr) {
7280 
7281         ram_addr_t offset;
7282         MemoryRegion *mr;
7283 
7284         /* RCU lock is already being held */
7285         mr = memory_region_from_host(haddr, &offset);
7286 
7287         if (mr) {
7288             memory_region_writeback(mr, offset, dline_size);
7289         }
7290     }
7291 }
7292 
7293 static const ARMCPRegInfo dcpop_reg[] = {
7294     { .name = "DC_CVAP", .state = ARM_CP_STATE_AA64,
7295       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 1,
7296       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7297       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7298     REGINFO_SENTINEL
7299 };
7300 
7301 static const ARMCPRegInfo dcpodp_reg[] = {
7302     { .name = "DC_CVADP", .state = ARM_CP_STATE_AA64,
7303       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 1,
7304       .access = PL0_W, .type = ARM_CP_NO_RAW | ARM_CP_SUPPRESS_TB_END,
7305       .accessfn = aa64_cacheop_poc_access, .writefn = dccvap_writefn },
7306     REGINFO_SENTINEL
7307 };
7308 #endif /*CONFIG_USER_ONLY*/
7309 
7310 static CPAccessResult access_aa64_tid5(CPUARMState *env, const ARMCPRegInfo *ri,
7311                                        bool isread)
7312 {
7313     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID5)) {
7314         return CP_ACCESS_TRAP_EL2;
7315     }
7316 
7317     return CP_ACCESS_OK;
7318 }
7319 
7320 static CPAccessResult access_mte(CPUARMState *env, const ARMCPRegInfo *ri,
7321                                  bool isread)
7322 {
7323     int el = arm_current_el(env);
7324 
7325     if (el < 2 && arm_feature(env, ARM_FEATURE_EL2)) {
7326         uint64_t hcr = arm_hcr_el2_eff(env);
7327         if (!(hcr & HCR_ATA) && (!(hcr & HCR_E2H) || !(hcr & HCR_TGE))) {
7328             return CP_ACCESS_TRAP_EL2;
7329         }
7330     }
7331     if (el < 3 &&
7332         arm_feature(env, ARM_FEATURE_EL3) &&
7333         !(env->cp15.scr_el3 & SCR_ATA)) {
7334         return CP_ACCESS_TRAP_EL3;
7335     }
7336     return CP_ACCESS_OK;
7337 }
7338 
7339 static uint64_t tco_read(CPUARMState *env, const ARMCPRegInfo *ri)
7340 {
7341     return env->pstate & PSTATE_TCO;
7342 }
7343 
7344 static void tco_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t val)
7345 {
7346     env->pstate = (env->pstate & ~PSTATE_TCO) | (val & PSTATE_TCO);
7347 }
7348 
7349 static const ARMCPRegInfo mte_reginfo[] = {
7350     { .name = "TFSRE0_EL1", .state = ARM_CP_STATE_AA64,
7351       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 1,
7352       .access = PL1_RW, .accessfn = access_mte,
7353       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[0]) },
7354     { .name = "TFSR_EL1", .state = ARM_CP_STATE_AA64,
7355       .opc0 = 3, .opc1 = 0, .crn = 5, .crm = 6, .opc2 = 0,
7356       .access = PL1_RW, .accessfn = access_mte,
7357       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[1]) },
7358     { .name = "TFSR_EL2", .state = ARM_CP_STATE_AA64,
7359       .opc0 = 3, .opc1 = 4, .crn = 5, .crm = 6, .opc2 = 0,
7360       .access = PL2_RW, .accessfn = access_mte,
7361       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[2]) },
7362     { .name = "TFSR_EL3", .state = ARM_CP_STATE_AA64,
7363       .opc0 = 3, .opc1 = 6, .crn = 5, .crm = 6, .opc2 = 0,
7364       .access = PL3_RW,
7365       .fieldoffset = offsetof(CPUARMState, cp15.tfsr_el[3]) },
7366     { .name = "RGSR_EL1", .state = ARM_CP_STATE_AA64,
7367       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 5,
7368       .access = PL1_RW, .accessfn = access_mte,
7369       .fieldoffset = offsetof(CPUARMState, cp15.rgsr_el1) },
7370     { .name = "GCR_EL1", .state = ARM_CP_STATE_AA64,
7371       .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 6,
7372       .access = PL1_RW, .accessfn = access_mte,
7373       .fieldoffset = offsetof(CPUARMState, cp15.gcr_el1) },
7374     { .name = "GMID_EL1", .state = ARM_CP_STATE_AA64,
7375       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 4,
7376       .access = PL1_R, .accessfn = access_aa64_tid5,
7377       .type = ARM_CP_CONST, .resetvalue = GMID_EL1_BS },
7378     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7379       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7380       .type = ARM_CP_NO_RAW,
7381       .access = PL0_RW, .readfn = tco_read, .writefn = tco_write },
7382     { .name = "DC_IGVAC", .state = ARM_CP_STATE_AA64,
7383       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 3,
7384       .type = ARM_CP_NOP, .access = PL1_W,
7385       .accessfn = aa64_cacheop_poc_access },
7386     { .name = "DC_IGSW", .state = ARM_CP_STATE_AA64,
7387       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 4,
7388       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7389     { .name = "DC_IGDVAC", .state = ARM_CP_STATE_AA64,
7390       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 5,
7391       .type = ARM_CP_NOP, .access = PL1_W,
7392       .accessfn = aa64_cacheop_poc_access },
7393     { .name = "DC_IGDSW", .state = ARM_CP_STATE_AA64,
7394       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 6, .opc2 = 6,
7395       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7396     { .name = "DC_CGSW", .state = ARM_CP_STATE_AA64,
7397       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 4,
7398       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7399     { .name = "DC_CGDSW", .state = ARM_CP_STATE_AA64,
7400       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 10, .opc2 = 6,
7401       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7402     { .name = "DC_CIGSW", .state = ARM_CP_STATE_AA64,
7403       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 4,
7404       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7405     { .name = "DC_CIGDSW", .state = ARM_CP_STATE_AA64,
7406       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 14, .opc2 = 6,
7407       .type = ARM_CP_NOP, .access = PL1_W, .accessfn = access_tsw },
7408     REGINFO_SENTINEL
7409 };
7410 
7411 static const ARMCPRegInfo mte_tco_ro_reginfo[] = {
7412     { .name = "TCO", .state = ARM_CP_STATE_AA64,
7413       .opc0 = 3, .opc1 = 3, .crn = 4, .crm = 2, .opc2 = 7,
7414       .type = ARM_CP_CONST, .access = PL0_RW, },
7415     REGINFO_SENTINEL
7416 };
7417 
7418 static const ARMCPRegInfo mte_el0_cacheop_reginfo[] = {
7419     { .name = "DC_CGVAC", .state = ARM_CP_STATE_AA64,
7420       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 3,
7421       .type = ARM_CP_NOP, .access = PL0_W,
7422       .accessfn = aa64_cacheop_poc_access },
7423     { .name = "DC_CGDVAC", .state = ARM_CP_STATE_AA64,
7424       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 10, .opc2 = 5,
7425       .type = ARM_CP_NOP, .access = PL0_W,
7426       .accessfn = aa64_cacheop_poc_access },
7427     { .name = "DC_CGVAP", .state = ARM_CP_STATE_AA64,
7428       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 3,
7429       .type = ARM_CP_NOP, .access = PL0_W,
7430       .accessfn = aa64_cacheop_poc_access },
7431     { .name = "DC_CGDVAP", .state = ARM_CP_STATE_AA64,
7432       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 12, .opc2 = 5,
7433       .type = ARM_CP_NOP, .access = PL0_W,
7434       .accessfn = aa64_cacheop_poc_access },
7435     { .name = "DC_CGVADP", .state = ARM_CP_STATE_AA64,
7436       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 3,
7437       .type = ARM_CP_NOP, .access = PL0_W,
7438       .accessfn = aa64_cacheop_poc_access },
7439     { .name = "DC_CGDVADP", .state = ARM_CP_STATE_AA64,
7440       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 13, .opc2 = 5,
7441       .type = ARM_CP_NOP, .access = PL0_W,
7442       .accessfn = aa64_cacheop_poc_access },
7443     { .name = "DC_CIGVAC", .state = ARM_CP_STATE_AA64,
7444       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 3,
7445       .type = ARM_CP_NOP, .access = PL0_W,
7446       .accessfn = aa64_cacheop_poc_access },
7447     { .name = "DC_CIGDVAC", .state = ARM_CP_STATE_AA64,
7448       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 14, .opc2 = 5,
7449       .type = ARM_CP_NOP, .access = PL0_W,
7450       .accessfn = aa64_cacheop_poc_access },
7451     { .name = "DC_GVA", .state = ARM_CP_STATE_AA64,
7452       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 3,
7453       .access = PL0_W, .type = ARM_CP_DC_GVA,
7454 #ifndef CONFIG_USER_ONLY
7455       /* Avoid overhead of an access check that always passes in user-mode */
7456       .accessfn = aa64_zva_access,
7457 #endif
7458     },
7459     { .name = "DC_GZVA", .state = ARM_CP_STATE_AA64,
7460       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 4, .opc2 = 4,
7461       .access = PL0_W, .type = ARM_CP_DC_GZVA,
7462 #ifndef CONFIG_USER_ONLY
7463       /* Avoid overhead of an access check that always passes in user-mode */
7464       .accessfn = aa64_zva_access,
7465 #endif
7466     },
7467     REGINFO_SENTINEL
7468 };
7469 
7470 #endif
7471 
7472 static CPAccessResult access_predinv(CPUARMState *env, const ARMCPRegInfo *ri,
7473                                      bool isread)
7474 {
7475     int el = arm_current_el(env);
7476 
7477     if (el == 0) {
7478         uint64_t sctlr = arm_sctlr(env, el);
7479         if (!(sctlr & SCTLR_EnRCTX)) {
7480             return CP_ACCESS_TRAP;
7481         }
7482     } else if (el == 1) {
7483         uint64_t hcr = arm_hcr_el2_eff(env);
7484         if (hcr & HCR_NV) {
7485             return CP_ACCESS_TRAP_EL2;
7486         }
7487     }
7488     return CP_ACCESS_OK;
7489 }
7490 
7491 static const ARMCPRegInfo predinv_reginfo[] = {
7492     { .name = "CFP_RCTX", .state = ARM_CP_STATE_AA64,
7493       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 4,
7494       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7495     { .name = "DVP_RCTX", .state = ARM_CP_STATE_AA64,
7496       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 5,
7497       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7498     { .name = "CPP_RCTX", .state = ARM_CP_STATE_AA64,
7499       .opc0 = 1, .opc1 = 3, .crn = 7, .crm = 3, .opc2 = 7,
7500       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7501     /*
7502      * Note the AArch32 opcodes have a different OPC1.
7503      */
7504     { .name = "CFPRCTX", .state = ARM_CP_STATE_AA32,
7505       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 4,
7506       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7507     { .name = "DVPRCTX", .state = ARM_CP_STATE_AA32,
7508       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 5,
7509       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7510     { .name = "CPPRCTX", .state = ARM_CP_STATE_AA32,
7511       .cp = 15, .opc1 = 0, .crn = 7, .crm = 3, .opc2 = 7,
7512       .type = ARM_CP_NOP, .access = PL0_W, .accessfn = access_predinv },
7513     REGINFO_SENTINEL
7514 };
7515 
7516 static uint64_t ccsidr2_read(CPUARMState *env, const ARMCPRegInfo *ri)
7517 {
7518     /* Read the high 32 bits of the current CCSIDR */
7519     return extract64(ccsidr_read(env, ri), 32, 32);
7520 }
7521 
7522 static const ARMCPRegInfo ccsidr2_reginfo[] = {
7523     { .name = "CCSIDR2", .state = ARM_CP_STATE_BOTH,
7524       .opc0 = 3, .opc1 = 1, .crn = 0, .crm = 0, .opc2 = 2,
7525       .access = PL1_R,
7526       .accessfn = access_aa64_tid2,
7527       .readfn = ccsidr2_read, .type = ARM_CP_NO_RAW },
7528     REGINFO_SENTINEL
7529 };
7530 
7531 static CPAccessResult access_aa64_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7532                                        bool isread)
7533 {
7534     if ((arm_current_el(env) < 2) && (arm_hcr_el2_eff(env) & HCR_TID3)) {
7535         return CP_ACCESS_TRAP_EL2;
7536     }
7537 
7538     return CP_ACCESS_OK;
7539 }
7540 
7541 static CPAccessResult access_aa32_tid3(CPUARMState *env, const ARMCPRegInfo *ri,
7542                                        bool isread)
7543 {
7544     if (arm_feature(env, ARM_FEATURE_V8)) {
7545         return access_aa64_tid3(env, ri, isread);
7546     }
7547 
7548     return CP_ACCESS_OK;
7549 }
7550 
7551 static CPAccessResult access_jazelle(CPUARMState *env, const ARMCPRegInfo *ri,
7552                                      bool isread)
7553 {
7554     if (arm_current_el(env) == 1 && (arm_hcr_el2_eff(env) & HCR_TID0)) {
7555         return CP_ACCESS_TRAP_EL2;
7556     }
7557 
7558     return CP_ACCESS_OK;
7559 }
7560 
7561 static CPAccessResult access_joscr_jmcr(CPUARMState *env,
7562                                         const ARMCPRegInfo *ri, bool isread)
7563 {
7564     /*
7565      * HSTR.TJDBX traps JOSCR and JMCR accesses, but it exists only
7566      * in v7A, not in v8A.
7567      */
7568     if (!arm_feature(env, ARM_FEATURE_V8) &&
7569         arm_current_el(env) < 2 && !arm_is_secure_below_el3(env) &&
7570         (env->cp15.hstr_el2 & HSTR_TJDBX)) {
7571         return CP_ACCESS_TRAP_EL2;
7572     }
7573     return CP_ACCESS_OK;
7574 }
7575 
7576 static const ARMCPRegInfo jazelle_regs[] = {
7577     { .name = "JIDR",
7578       .cp = 14, .crn = 0, .crm = 0, .opc1 = 7, .opc2 = 0,
7579       .access = PL1_R, .accessfn = access_jazelle,
7580       .type = ARM_CP_CONST, .resetvalue = 0 },
7581     { .name = "JOSCR",
7582       .cp = 14, .crn = 1, .crm = 0, .opc1 = 7, .opc2 = 0,
7583       .accessfn = access_joscr_jmcr,
7584       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7585     { .name = "JMCR",
7586       .cp = 14, .crn = 2, .crm = 0, .opc1 = 7, .opc2 = 0,
7587       .accessfn = access_joscr_jmcr,
7588       .access = PL1_RW, .type = ARM_CP_CONST, .resetvalue = 0 },
7589     REGINFO_SENTINEL
7590 };
7591 
7592 static const ARMCPRegInfo vhe_reginfo[] = {
7593     { .name = "CONTEXTIDR_EL2", .state = ARM_CP_STATE_AA64,
7594       .opc0 = 3, .opc1 = 4, .crn = 13, .crm = 0, .opc2 = 1,
7595       .access = PL2_RW,
7596       .fieldoffset = offsetof(CPUARMState, cp15.contextidr_el[2]) },
7597     { .name = "TTBR1_EL2", .state = ARM_CP_STATE_AA64,
7598       .opc0 = 3, .opc1 = 4, .crn = 2, .crm = 0, .opc2 = 1,
7599       .access = PL2_RW, .writefn = vmsa_tcr_ttbr_el2_write,
7600       .fieldoffset = offsetof(CPUARMState, cp15.ttbr1_el[2]) },
7601 #ifndef CONFIG_USER_ONLY
7602     { .name = "CNTHV_CVAL_EL2", .state = ARM_CP_STATE_AA64,
7603       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 2,
7604       .fieldoffset =
7605         offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].cval),
7606       .type = ARM_CP_IO, .access = PL2_RW,
7607       .writefn = gt_hv_cval_write, .raw_writefn = raw_write },
7608     { .name = "CNTHV_TVAL_EL2", .state = ARM_CP_STATE_BOTH,
7609       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 0,
7610       .type = ARM_CP_NO_RAW | ARM_CP_IO, .access = PL2_RW,
7611       .resetfn = gt_hv_timer_reset,
7612       .readfn = gt_hv_tval_read, .writefn = gt_hv_tval_write },
7613     { .name = "CNTHV_CTL_EL2", .state = ARM_CP_STATE_BOTH,
7614       .type = ARM_CP_IO,
7615       .opc0 = 3, .opc1 = 4, .crn = 14, .crm = 3, .opc2 = 1,
7616       .access = PL2_RW,
7617       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_HYPVIRT].ctl),
7618       .writefn = gt_hv_ctl_write, .raw_writefn = raw_write },
7619     { .name = "CNTP_CTL_EL02", .state = ARM_CP_STATE_AA64,
7620       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 1,
7621       .type = ARM_CP_IO | ARM_CP_ALIAS,
7622       .access = PL2_RW, .accessfn = e2h_access,
7623       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].ctl),
7624       .writefn = gt_phys_ctl_write, .raw_writefn = raw_write },
7625     { .name = "CNTV_CTL_EL02", .state = ARM_CP_STATE_AA64,
7626       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 1,
7627       .type = ARM_CP_IO | ARM_CP_ALIAS,
7628       .access = PL2_RW, .accessfn = e2h_access,
7629       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].ctl),
7630       .writefn = gt_virt_ctl_write, .raw_writefn = raw_write },
7631     { .name = "CNTP_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7632       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 0,
7633       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7634       .access = PL2_RW, .accessfn = e2h_access,
7635       .readfn = gt_phys_tval_read, .writefn = gt_phys_tval_write },
7636     { .name = "CNTV_TVAL_EL02", .state = ARM_CP_STATE_AA64,
7637       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 0,
7638       .type = ARM_CP_NO_RAW | ARM_CP_IO | ARM_CP_ALIAS,
7639       .access = PL2_RW, .accessfn = e2h_access,
7640       .readfn = gt_virt_tval_read, .writefn = gt_virt_tval_write },
7641     { .name = "CNTP_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7642       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 2, .opc2 = 2,
7643       .type = ARM_CP_IO | ARM_CP_ALIAS,
7644       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_PHYS].cval),
7645       .access = PL2_RW, .accessfn = e2h_access,
7646       .writefn = gt_phys_cval_write, .raw_writefn = raw_write },
7647     { .name = "CNTV_CVAL_EL02", .state = ARM_CP_STATE_AA64,
7648       .opc0 = 3, .opc1 = 5, .crn = 14, .crm = 3, .opc2 = 2,
7649       .type = ARM_CP_IO | ARM_CP_ALIAS,
7650       .fieldoffset = offsetof(CPUARMState, cp15.c14_timer[GTIMER_VIRT].cval),
7651       .access = PL2_RW, .accessfn = e2h_access,
7652       .writefn = gt_virt_cval_write, .raw_writefn = raw_write },
7653 #endif
7654     REGINFO_SENTINEL
7655 };
7656 
7657 #ifndef CONFIG_USER_ONLY
7658 static const ARMCPRegInfo ats1e1_reginfo[] = {
7659     { .name = "AT_S1E1R", .state = ARM_CP_STATE_AA64,
7660       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7661       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7662       .writefn = ats_write64 },
7663     { .name = "AT_S1E1W", .state = ARM_CP_STATE_AA64,
7664       .opc0 = 1, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7665       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7666       .writefn = ats_write64 },
7667     REGINFO_SENTINEL
7668 };
7669 
7670 static const ARMCPRegInfo ats1cp_reginfo[] = {
7671     { .name = "ATS1CPRP",
7672       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 0,
7673       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7674       .writefn = ats_write },
7675     { .name = "ATS1CPWP",
7676       .cp = 15, .opc1 = 0, .crn = 7, .crm = 9, .opc2 = 1,
7677       .access = PL1_W, .type = ARM_CP_NO_RAW | ARM_CP_RAISES_EXC,
7678       .writefn = ats_write },
7679     REGINFO_SENTINEL
7680 };
7681 #endif
7682 
7683 /*
7684  * ACTLR2 and HACTLR2 map to ACTLR_EL1[63:32] and
7685  * ACTLR_EL2[63:32]. They exist only if the ID_MMFR4.AC2 field
7686  * is non-zero, which is never for ARMv7, optionally in ARMv8
7687  * and mandatorily for ARMv8.2 and up.
7688  * ACTLR2 is banked for S and NS if EL3 is AArch32. Since QEMU's
7689  * implementation is RAZ/WI we can ignore this detail, as we
7690  * do for ACTLR.
7691  */
7692 static const ARMCPRegInfo actlr2_hactlr2_reginfo[] = {
7693     { .name = "ACTLR2", .state = ARM_CP_STATE_AA32,
7694       .cp = 15, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 3,
7695       .access = PL1_RW, .accessfn = access_tacr,
7696       .type = ARM_CP_CONST, .resetvalue = 0 },
7697     { .name = "HACTLR2", .state = ARM_CP_STATE_AA32,
7698       .cp = 15, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 3,
7699       .access = PL2_RW, .type = ARM_CP_CONST,
7700       .resetvalue = 0 },
7701     REGINFO_SENTINEL
7702 };
7703 
7704 void register_cp_regs_for_features(ARMCPU *cpu)
7705 {
7706     /* Register all the coprocessor registers based on feature bits */
7707     CPUARMState *env = &cpu->env;
7708     if (arm_feature(env, ARM_FEATURE_M)) {
7709         /* M profile has no coprocessor registers */
7710         return;
7711     }
7712 
7713     define_arm_cp_regs(cpu, cp_reginfo);
7714     if (!arm_feature(env, ARM_FEATURE_V8)) {
7715         /* Must go early as it is full of wildcards that may be
7716          * overridden by later definitions.
7717          */
7718         define_arm_cp_regs(cpu, not_v8_cp_reginfo);
7719     }
7720 
7721     if (arm_feature(env, ARM_FEATURE_V6)) {
7722         /* The ID registers all have impdef reset values */
7723         ARMCPRegInfo v6_idregs[] = {
7724             { .name = "ID_PFR0", .state = ARM_CP_STATE_BOTH,
7725               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 0,
7726               .access = PL1_R, .type = ARM_CP_CONST,
7727               .accessfn = access_aa32_tid3,
7728               .resetvalue = cpu->isar.id_pfr0 },
7729             /* ID_PFR1 is not a plain ARM_CP_CONST because we don't know
7730              * the value of the GIC field until after we define these regs.
7731              */
7732             { .name = "ID_PFR1", .state = ARM_CP_STATE_BOTH,
7733               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 1,
7734               .access = PL1_R, .type = ARM_CP_NO_RAW,
7735               .accessfn = access_aa32_tid3,
7736               .readfn = id_pfr1_read,
7737               .writefn = arm_cp_write_ignore },
7738             { .name = "ID_DFR0", .state = ARM_CP_STATE_BOTH,
7739               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 2,
7740               .access = PL1_R, .type = ARM_CP_CONST,
7741               .accessfn = access_aa32_tid3,
7742               .resetvalue = cpu->isar.id_dfr0 },
7743             { .name = "ID_AFR0", .state = ARM_CP_STATE_BOTH,
7744               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 3,
7745               .access = PL1_R, .type = ARM_CP_CONST,
7746               .accessfn = access_aa32_tid3,
7747               .resetvalue = cpu->id_afr0 },
7748             { .name = "ID_MMFR0", .state = ARM_CP_STATE_BOTH,
7749               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 4,
7750               .access = PL1_R, .type = ARM_CP_CONST,
7751               .accessfn = access_aa32_tid3,
7752               .resetvalue = cpu->isar.id_mmfr0 },
7753             { .name = "ID_MMFR1", .state = ARM_CP_STATE_BOTH,
7754               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 5,
7755               .access = PL1_R, .type = ARM_CP_CONST,
7756               .accessfn = access_aa32_tid3,
7757               .resetvalue = cpu->isar.id_mmfr1 },
7758             { .name = "ID_MMFR2", .state = ARM_CP_STATE_BOTH,
7759               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 6,
7760               .access = PL1_R, .type = ARM_CP_CONST,
7761               .accessfn = access_aa32_tid3,
7762               .resetvalue = cpu->isar.id_mmfr2 },
7763             { .name = "ID_MMFR3", .state = ARM_CP_STATE_BOTH,
7764               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 1, .opc2 = 7,
7765               .access = PL1_R, .type = ARM_CP_CONST,
7766               .accessfn = access_aa32_tid3,
7767               .resetvalue = cpu->isar.id_mmfr3 },
7768             { .name = "ID_ISAR0", .state = ARM_CP_STATE_BOTH,
7769               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 0,
7770               .access = PL1_R, .type = ARM_CP_CONST,
7771               .accessfn = access_aa32_tid3,
7772               .resetvalue = cpu->isar.id_isar0 },
7773             { .name = "ID_ISAR1", .state = ARM_CP_STATE_BOTH,
7774               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 1,
7775               .access = PL1_R, .type = ARM_CP_CONST,
7776               .accessfn = access_aa32_tid3,
7777               .resetvalue = cpu->isar.id_isar1 },
7778             { .name = "ID_ISAR2", .state = ARM_CP_STATE_BOTH,
7779               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 2,
7780               .access = PL1_R, .type = ARM_CP_CONST,
7781               .accessfn = access_aa32_tid3,
7782               .resetvalue = cpu->isar.id_isar2 },
7783             { .name = "ID_ISAR3", .state = ARM_CP_STATE_BOTH,
7784               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 3,
7785               .access = PL1_R, .type = ARM_CP_CONST,
7786               .accessfn = access_aa32_tid3,
7787               .resetvalue = cpu->isar.id_isar3 },
7788             { .name = "ID_ISAR4", .state = ARM_CP_STATE_BOTH,
7789               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 4,
7790               .access = PL1_R, .type = ARM_CP_CONST,
7791               .accessfn = access_aa32_tid3,
7792               .resetvalue = cpu->isar.id_isar4 },
7793             { .name = "ID_ISAR5", .state = ARM_CP_STATE_BOTH,
7794               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 5,
7795               .access = PL1_R, .type = ARM_CP_CONST,
7796               .accessfn = access_aa32_tid3,
7797               .resetvalue = cpu->isar.id_isar5 },
7798             { .name = "ID_MMFR4", .state = ARM_CP_STATE_BOTH,
7799               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 6,
7800               .access = PL1_R, .type = ARM_CP_CONST,
7801               .accessfn = access_aa32_tid3,
7802               .resetvalue = cpu->isar.id_mmfr4 },
7803             { .name = "ID_ISAR6", .state = ARM_CP_STATE_BOTH,
7804               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 2, .opc2 = 7,
7805               .access = PL1_R, .type = ARM_CP_CONST,
7806               .accessfn = access_aa32_tid3,
7807               .resetvalue = cpu->isar.id_isar6 },
7808             REGINFO_SENTINEL
7809         };
7810         define_arm_cp_regs(cpu, v6_idregs);
7811         define_arm_cp_regs(cpu, v6_cp_reginfo);
7812     } else {
7813         define_arm_cp_regs(cpu, not_v6_cp_reginfo);
7814     }
7815     if (arm_feature(env, ARM_FEATURE_V6K)) {
7816         define_arm_cp_regs(cpu, v6k_cp_reginfo);
7817     }
7818     if (arm_feature(env, ARM_FEATURE_V7MP) &&
7819         !arm_feature(env, ARM_FEATURE_PMSA)) {
7820         define_arm_cp_regs(cpu, v7mp_cp_reginfo);
7821     }
7822     if (arm_feature(env, ARM_FEATURE_V7VE)) {
7823         define_arm_cp_regs(cpu, pmovsset_cp_reginfo);
7824     }
7825     if (arm_feature(env, ARM_FEATURE_V7)) {
7826         ARMCPRegInfo clidr = {
7827             .name = "CLIDR", .state = ARM_CP_STATE_BOTH,
7828             .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 1, .opc2 = 1,
7829             .access = PL1_R, .type = ARM_CP_CONST,
7830             .accessfn = access_aa64_tid2,
7831             .resetvalue = cpu->clidr
7832         };
7833         define_one_arm_cp_reg(cpu, &clidr);
7834         define_arm_cp_regs(cpu, v7_cp_reginfo);
7835         define_debug_regs(cpu);
7836         define_pmu_regs(cpu);
7837     } else {
7838         define_arm_cp_regs(cpu, not_v7_cp_reginfo);
7839     }
7840     if (arm_feature(env, ARM_FEATURE_V8)) {
7841         /* AArch64 ID registers, which all have impdef reset values.
7842          * Note that within the ID register ranges the unused slots
7843          * must all RAZ, not UNDEF; future architecture versions may
7844          * define new registers here.
7845          */
7846         ARMCPRegInfo v8_idregs[] = {
7847             /*
7848              * ID_AA64PFR0_EL1 is not a plain ARM_CP_CONST in system
7849              * emulation because we don't know the right value for the
7850              * GIC field until after we define these regs.
7851              */
7852             { .name = "ID_AA64PFR0_EL1", .state = ARM_CP_STATE_AA64,
7853               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 0,
7854               .access = PL1_R,
7855 #ifdef CONFIG_USER_ONLY
7856               .type = ARM_CP_CONST,
7857               .resetvalue = cpu->isar.id_aa64pfr0
7858 #else
7859               .type = ARM_CP_NO_RAW,
7860               .accessfn = access_aa64_tid3,
7861               .readfn = id_aa64pfr0_read,
7862               .writefn = arm_cp_write_ignore
7863 #endif
7864             },
7865             { .name = "ID_AA64PFR1_EL1", .state = ARM_CP_STATE_AA64,
7866               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 1,
7867               .access = PL1_R, .type = ARM_CP_CONST,
7868               .accessfn = access_aa64_tid3,
7869               .resetvalue = cpu->isar.id_aa64pfr1},
7870             { .name = "ID_AA64PFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7871               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 2,
7872               .access = PL1_R, .type = ARM_CP_CONST,
7873               .accessfn = access_aa64_tid3,
7874               .resetvalue = 0 },
7875             { .name = "ID_AA64PFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7876               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 3,
7877               .access = PL1_R, .type = ARM_CP_CONST,
7878               .accessfn = access_aa64_tid3,
7879               .resetvalue = 0 },
7880             { .name = "ID_AA64ZFR0_EL1", .state = ARM_CP_STATE_AA64,
7881               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 4,
7882               .access = PL1_R, .type = ARM_CP_CONST,
7883               .accessfn = access_aa64_tid3,
7884               .resetvalue = cpu->isar.id_aa64zfr0 },
7885             { .name = "ID_AA64PFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7886               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 5,
7887               .access = PL1_R, .type = ARM_CP_CONST,
7888               .accessfn = access_aa64_tid3,
7889               .resetvalue = 0 },
7890             { .name = "ID_AA64PFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7891               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 6,
7892               .access = PL1_R, .type = ARM_CP_CONST,
7893               .accessfn = access_aa64_tid3,
7894               .resetvalue = 0 },
7895             { .name = "ID_AA64PFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7896               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 4, .opc2 = 7,
7897               .access = PL1_R, .type = ARM_CP_CONST,
7898               .accessfn = access_aa64_tid3,
7899               .resetvalue = 0 },
7900             { .name = "ID_AA64DFR0_EL1", .state = ARM_CP_STATE_AA64,
7901               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 0,
7902               .access = PL1_R, .type = ARM_CP_CONST,
7903               .accessfn = access_aa64_tid3,
7904               .resetvalue = cpu->isar.id_aa64dfr0 },
7905             { .name = "ID_AA64DFR1_EL1", .state = ARM_CP_STATE_AA64,
7906               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 1,
7907               .access = PL1_R, .type = ARM_CP_CONST,
7908               .accessfn = access_aa64_tid3,
7909               .resetvalue = cpu->isar.id_aa64dfr1 },
7910             { .name = "ID_AA64DFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7911               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 2,
7912               .access = PL1_R, .type = ARM_CP_CONST,
7913               .accessfn = access_aa64_tid3,
7914               .resetvalue = 0 },
7915             { .name = "ID_AA64DFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7916               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 3,
7917               .access = PL1_R, .type = ARM_CP_CONST,
7918               .accessfn = access_aa64_tid3,
7919               .resetvalue = 0 },
7920             { .name = "ID_AA64AFR0_EL1", .state = ARM_CP_STATE_AA64,
7921               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 4,
7922               .access = PL1_R, .type = ARM_CP_CONST,
7923               .accessfn = access_aa64_tid3,
7924               .resetvalue = cpu->id_aa64afr0 },
7925             { .name = "ID_AA64AFR1_EL1", .state = ARM_CP_STATE_AA64,
7926               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 5,
7927               .access = PL1_R, .type = ARM_CP_CONST,
7928               .accessfn = access_aa64_tid3,
7929               .resetvalue = cpu->id_aa64afr1 },
7930             { .name = "ID_AA64AFR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7931               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 6,
7932               .access = PL1_R, .type = ARM_CP_CONST,
7933               .accessfn = access_aa64_tid3,
7934               .resetvalue = 0 },
7935             { .name = "ID_AA64AFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7936               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 5, .opc2 = 7,
7937               .access = PL1_R, .type = ARM_CP_CONST,
7938               .accessfn = access_aa64_tid3,
7939               .resetvalue = 0 },
7940             { .name = "ID_AA64ISAR0_EL1", .state = ARM_CP_STATE_AA64,
7941               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 0,
7942               .access = PL1_R, .type = ARM_CP_CONST,
7943               .accessfn = access_aa64_tid3,
7944               .resetvalue = cpu->isar.id_aa64isar0 },
7945             { .name = "ID_AA64ISAR1_EL1", .state = ARM_CP_STATE_AA64,
7946               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 1,
7947               .access = PL1_R, .type = ARM_CP_CONST,
7948               .accessfn = access_aa64_tid3,
7949               .resetvalue = cpu->isar.id_aa64isar1 },
7950             { .name = "ID_AA64ISAR2_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7951               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 2,
7952               .access = PL1_R, .type = ARM_CP_CONST,
7953               .accessfn = access_aa64_tid3,
7954               .resetvalue = 0 },
7955             { .name = "ID_AA64ISAR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7956               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 3,
7957               .access = PL1_R, .type = ARM_CP_CONST,
7958               .accessfn = access_aa64_tid3,
7959               .resetvalue = 0 },
7960             { .name = "ID_AA64ISAR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7961               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 4,
7962               .access = PL1_R, .type = ARM_CP_CONST,
7963               .accessfn = access_aa64_tid3,
7964               .resetvalue = 0 },
7965             { .name = "ID_AA64ISAR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7966               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 5,
7967               .access = PL1_R, .type = ARM_CP_CONST,
7968               .accessfn = access_aa64_tid3,
7969               .resetvalue = 0 },
7970             { .name = "ID_AA64ISAR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7971               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 6,
7972               .access = PL1_R, .type = ARM_CP_CONST,
7973               .accessfn = access_aa64_tid3,
7974               .resetvalue = 0 },
7975             { .name = "ID_AA64ISAR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7976               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 6, .opc2 = 7,
7977               .access = PL1_R, .type = ARM_CP_CONST,
7978               .accessfn = access_aa64_tid3,
7979               .resetvalue = 0 },
7980             { .name = "ID_AA64MMFR0_EL1", .state = ARM_CP_STATE_AA64,
7981               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 0,
7982               .access = PL1_R, .type = ARM_CP_CONST,
7983               .accessfn = access_aa64_tid3,
7984               .resetvalue = cpu->isar.id_aa64mmfr0 },
7985             { .name = "ID_AA64MMFR1_EL1", .state = ARM_CP_STATE_AA64,
7986               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 1,
7987               .access = PL1_R, .type = ARM_CP_CONST,
7988               .accessfn = access_aa64_tid3,
7989               .resetvalue = cpu->isar.id_aa64mmfr1 },
7990             { .name = "ID_AA64MMFR2_EL1", .state = ARM_CP_STATE_AA64,
7991               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 2,
7992               .access = PL1_R, .type = ARM_CP_CONST,
7993               .accessfn = access_aa64_tid3,
7994               .resetvalue = cpu->isar.id_aa64mmfr2 },
7995             { .name = "ID_AA64MMFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
7996               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 3,
7997               .access = PL1_R, .type = ARM_CP_CONST,
7998               .accessfn = access_aa64_tid3,
7999               .resetvalue = 0 },
8000             { .name = "ID_AA64MMFR4_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8001               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 4,
8002               .access = PL1_R, .type = ARM_CP_CONST,
8003               .accessfn = access_aa64_tid3,
8004               .resetvalue = 0 },
8005             { .name = "ID_AA64MMFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8006               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 5,
8007               .access = PL1_R, .type = ARM_CP_CONST,
8008               .accessfn = access_aa64_tid3,
8009               .resetvalue = 0 },
8010             { .name = "ID_AA64MMFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8011               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 6,
8012               .access = PL1_R, .type = ARM_CP_CONST,
8013               .accessfn = access_aa64_tid3,
8014               .resetvalue = 0 },
8015             { .name = "ID_AA64MMFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8016               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 7, .opc2 = 7,
8017               .access = PL1_R, .type = ARM_CP_CONST,
8018               .accessfn = access_aa64_tid3,
8019               .resetvalue = 0 },
8020             { .name = "MVFR0_EL1", .state = ARM_CP_STATE_AA64,
8021               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 0,
8022               .access = PL1_R, .type = ARM_CP_CONST,
8023               .accessfn = access_aa64_tid3,
8024               .resetvalue = cpu->isar.mvfr0 },
8025             { .name = "MVFR1_EL1", .state = ARM_CP_STATE_AA64,
8026               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 1,
8027               .access = PL1_R, .type = ARM_CP_CONST,
8028               .accessfn = access_aa64_tid3,
8029               .resetvalue = cpu->isar.mvfr1 },
8030             { .name = "MVFR2_EL1", .state = ARM_CP_STATE_AA64,
8031               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 2,
8032               .access = PL1_R, .type = ARM_CP_CONST,
8033               .accessfn = access_aa64_tid3,
8034               .resetvalue = cpu->isar.mvfr2 },
8035             { .name = "MVFR3_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8036               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 3,
8037               .access = PL1_R, .type = ARM_CP_CONST,
8038               .accessfn = access_aa64_tid3,
8039               .resetvalue = 0 },
8040             { .name = "ID_PFR2", .state = ARM_CP_STATE_BOTH,
8041               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 4,
8042               .access = PL1_R, .type = ARM_CP_CONST,
8043               .accessfn = access_aa64_tid3,
8044               .resetvalue = cpu->isar.id_pfr2 },
8045             { .name = "MVFR5_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8046               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 5,
8047               .access = PL1_R, .type = ARM_CP_CONST,
8048               .accessfn = access_aa64_tid3,
8049               .resetvalue = 0 },
8050             { .name = "MVFR6_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8051               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 6,
8052               .access = PL1_R, .type = ARM_CP_CONST,
8053               .accessfn = access_aa64_tid3,
8054               .resetvalue = 0 },
8055             { .name = "MVFR7_EL1_RESERVED", .state = ARM_CP_STATE_AA64,
8056               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 3, .opc2 = 7,
8057               .access = PL1_R, .type = ARM_CP_CONST,
8058               .accessfn = access_aa64_tid3,
8059               .resetvalue = 0 },
8060             { .name = "PMCEID0", .state = ARM_CP_STATE_AA32,
8061               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 6,
8062               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
8063               .resetvalue = extract64(cpu->pmceid0, 0, 32) },
8064             { .name = "PMCEID0_EL0", .state = ARM_CP_STATE_AA64,
8065               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 6,
8066               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
8067               .resetvalue = cpu->pmceid0 },
8068             { .name = "PMCEID1", .state = ARM_CP_STATE_AA32,
8069               .cp = 15, .opc1 = 0, .crn = 9, .crm = 12, .opc2 = 7,
8070               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
8071               .resetvalue = extract64(cpu->pmceid1, 0, 32) },
8072             { .name = "PMCEID1_EL0", .state = ARM_CP_STATE_AA64,
8073               .opc0 = 3, .opc1 = 3, .crn = 9, .crm = 12, .opc2 = 7,
8074               .access = PL0_R, .accessfn = pmreg_access, .type = ARM_CP_CONST,
8075               .resetvalue = cpu->pmceid1 },
8076             REGINFO_SENTINEL
8077         };
8078 #ifdef CONFIG_USER_ONLY
8079         ARMCPRegUserSpaceInfo v8_user_idregs[] = {
8080             { .name = "ID_AA64PFR0_EL1",
8081               .exported_bits = 0x000f000f00ff0000,
8082               .fixed_bits    = 0x0000000000000011 },
8083             { .name = "ID_AA64PFR1_EL1",
8084               .exported_bits = 0x00000000000000f0 },
8085             { .name = "ID_AA64PFR*_EL1_RESERVED",
8086               .is_glob = true                     },
8087             { .name = "ID_AA64ZFR0_EL1"           },
8088             { .name = "ID_AA64MMFR0_EL1",
8089               .fixed_bits    = 0x00000000ff000000 },
8090             { .name = "ID_AA64MMFR1_EL1"          },
8091             { .name = "ID_AA64MMFR*_EL1_RESERVED",
8092               .is_glob = true                     },
8093             { .name = "ID_AA64DFR0_EL1",
8094               .fixed_bits    = 0x0000000000000006 },
8095             { .name = "ID_AA64DFR1_EL1"           },
8096             { .name = "ID_AA64DFR*_EL1_RESERVED",
8097               .is_glob = true                     },
8098             { .name = "ID_AA64AFR*",
8099               .is_glob = true                     },
8100             { .name = "ID_AA64ISAR0_EL1",
8101               .exported_bits = 0x00fffffff0fffff0 },
8102             { .name = "ID_AA64ISAR1_EL1",
8103               .exported_bits = 0x000000f0ffffffff },
8104             { .name = "ID_AA64ISAR*_EL1_RESERVED",
8105               .is_glob = true                     },
8106             REGUSERINFO_SENTINEL
8107         };
8108         modify_arm_cp_regs(v8_idregs, v8_user_idregs);
8109 #endif
8110         /* RVBAR_EL1 is only implemented if EL1 is the highest EL */
8111         if (!arm_feature(env, ARM_FEATURE_EL3) &&
8112             !arm_feature(env, ARM_FEATURE_EL2)) {
8113             ARMCPRegInfo rvbar = {
8114                 .name = "RVBAR_EL1", .state = ARM_CP_STATE_AA64,
8115                 .opc0 = 3, .opc1 = 0, .crn = 12, .crm = 0, .opc2 = 1,
8116                 .type = ARM_CP_CONST, .access = PL1_R, .resetvalue = cpu->rvbar
8117             };
8118             define_one_arm_cp_reg(cpu, &rvbar);
8119         }
8120         define_arm_cp_regs(cpu, v8_idregs);
8121         define_arm_cp_regs(cpu, v8_cp_reginfo);
8122     }
8123     if (arm_feature(env, ARM_FEATURE_EL2)) {
8124         uint64_t vmpidr_def = mpidr_read_val(env);
8125         ARMCPRegInfo vpidr_regs[] = {
8126             { .name = "VPIDR", .state = ARM_CP_STATE_AA32,
8127               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
8128               .access = PL2_RW, .accessfn = access_el3_aa32ns,
8129               .resetvalue = cpu->midr, .type = ARM_CP_ALIAS,
8130               .fieldoffset = offsetoflow32(CPUARMState, cp15.vpidr_el2) },
8131             { .name = "VPIDR_EL2", .state = ARM_CP_STATE_AA64,
8132               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
8133               .access = PL2_RW, .resetvalue = cpu->midr,
8134               .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
8135             { .name = "VMPIDR", .state = ARM_CP_STATE_AA32,
8136               .cp = 15, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
8137               .access = PL2_RW, .accessfn = access_el3_aa32ns,
8138               .resetvalue = vmpidr_def, .type = ARM_CP_ALIAS,
8139               .fieldoffset = offsetoflow32(CPUARMState, cp15.vmpidr_el2) },
8140             { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_AA64,
8141               .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
8142               .access = PL2_RW,
8143               .resetvalue = vmpidr_def,
8144               .fieldoffset = offsetof(CPUARMState, cp15.vmpidr_el2) },
8145             REGINFO_SENTINEL
8146         };
8147         define_arm_cp_regs(cpu, vpidr_regs);
8148         define_arm_cp_regs(cpu, el2_cp_reginfo);
8149         if (arm_feature(env, ARM_FEATURE_V8)) {
8150             define_arm_cp_regs(cpu, el2_v8_cp_reginfo);
8151         }
8152         if (cpu_isar_feature(aa64_sel2, cpu)) {
8153             define_arm_cp_regs(cpu, el2_sec_cp_reginfo);
8154         }
8155         /* RVBAR_EL2 is only implemented if EL2 is the highest EL */
8156         if (!arm_feature(env, ARM_FEATURE_EL3)) {
8157             ARMCPRegInfo rvbar = {
8158                 .name = "RVBAR_EL2", .state = ARM_CP_STATE_AA64,
8159                 .opc0 = 3, .opc1 = 4, .crn = 12, .crm = 0, .opc2 = 1,
8160                 .type = ARM_CP_CONST, .access = PL2_R, .resetvalue = cpu->rvbar
8161             };
8162             define_one_arm_cp_reg(cpu, &rvbar);
8163         }
8164     } else {
8165         /* If EL2 is missing but higher ELs are enabled, we need to
8166          * register the no_el2 reginfos.
8167          */
8168         if (arm_feature(env, ARM_FEATURE_EL3)) {
8169             /* When EL3 exists but not EL2, VPIDR and VMPIDR take the value
8170              * of MIDR_EL1 and MPIDR_EL1.
8171              */
8172             ARMCPRegInfo vpidr_regs[] = {
8173                 { .name = "VPIDR_EL2", .state = ARM_CP_STATE_BOTH,
8174                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 0,
8175                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
8176                   .type = ARM_CP_CONST, .resetvalue = cpu->midr,
8177                   .fieldoffset = offsetof(CPUARMState, cp15.vpidr_el2) },
8178                 { .name = "VMPIDR_EL2", .state = ARM_CP_STATE_BOTH,
8179                   .opc0 = 3, .opc1 = 4, .crn = 0, .crm = 0, .opc2 = 5,
8180                   .access = PL2_RW, .accessfn = access_el3_aa32ns,
8181                   .type = ARM_CP_NO_RAW,
8182                   .writefn = arm_cp_write_ignore, .readfn = mpidr_read },
8183                 REGINFO_SENTINEL
8184             };
8185             define_arm_cp_regs(cpu, vpidr_regs);
8186             define_arm_cp_regs(cpu, el3_no_el2_cp_reginfo);
8187             if (arm_feature(env, ARM_FEATURE_V8)) {
8188                 define_arm_cp_regs(cpu, el3_no_el2_v8_cp_reginfo);
8189             }
8190         }
8191     }
8192     if (arm_feature(env, ARM_FEATURE_EL3)) {
8193         define_arm_cp_regs(cpu, el3_cp_reginfo);
8194         ARMCPRegInfo el3_regs[] = {
8195             { .name = "RVBAR_EL3", .state = ARM_CP_STATE_AA64,
8196               .opc0 = 3, .opc1 = 6, .crn = 12, .crm = 0, .opc2 = 1,
8197               .type = ARM_CP_CONST, .access = PL3_R, .resetvalue = cpu->rvbar },
8198             { .name = "SCTLR_EL3", .state = ARM_CP_STATE_AA64,
8199               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 0,
8200               .access = PL3_RW,
8201               .raw_writefn = raw_write, .writefn = sctlr_write,
8202               .fieldoffset = offsetof(CPUARMState, cp15.sctlr_el[3]),
8203               .resetvalue = cpu->reset_sctlr },
8204             REGINFO_SENTINEL
8205         };
8206 
8207         define_arm_cp_regs(cpu, el3_regs);
8208     }
8209     /* The behaviour of NSACR is sufficiently various that we don't
8210      * try to describe it in a single reginfo:
8211      *  if EL3 is 64 bit, then trap to EL3 from S EL1,
8212      *     reads as constant 0xc00 from NS EL1 and NS EL2
8213      *  if EL3 is 32 bit, then RW at EL3, RO at NS EL1 and NS EL2
8214      *  if v7 without EL3, register doesn't exist
8215      *  if v8 without EL3, reads as constant 0xc00 from NS EL1 and NS EL2
8216      */
8217     if (arm_feature(env, ARM_FEATURE_EL3)) {
8218         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8219             ARMCPRegInfo nsacr = {
8220                 .name = "NSACR", .type = ARM_CP_CONST,
8221                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8222                 .access = PL1_RW, .accessfn = nsacr_access,
8223                 .resetvalue = 0xc00
8224             };
8225             define_one_arm_cp_reg(cpu, &nsacr);
8226         } else {
8227             ARMCPRegInfo nsacr = {
8228                 .name = "NSACR",
8229                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8230                 .access = PL3_RW | PL1_R,
8231                 .resetvalue = 0,
8232                 .fieldoffset = offsetof(CPUARMState, cp15.nsacr)
8233             };
8234             define_one_arm_cp_reg(cpu, &nsacr);
8235         }
8236     } else {
8237         if (arm_feature(env, ARM_FEATURE_V8)) {
8238             ARMCPRegInfo nsacr = {
8239                 .name = "NSACR", .type = ARM_CP_CONST,
8240                 .cp = 15, .opc1 = 0, .crn = 1, .crm = 1, .opc2 = 2,
8241                 .access = PL1_R,
8242                 .resetvalue = 0xc00
8243             };
8244             define_one_arm_cp_reg(cpu, &nsacr);
8245         }
8246     }
8247 
8248     if (arm_feature(env, ARM_FEATURE_PMSA)) {
8249         if (arm_feature(env, ARM_FEATURE_V6)) {
8250             /* PMSAv6 not implemented */
8251             assert(arm_feature(env, ARM_FEATURE_V7));
8252             define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8253             define_arm_cp_regs(cpu, pmsav7_cp_reginfo);
8254         } else {
8255             define_arm_cp_regs(cpu, pmsav5_cp_reginfo);
8256         }
8257     } else {
8258         define_arm_cp_regs(cpu, vmsa_pmsa_cp_reginfo);
8259         define_arm_cp_regs(cpu, vmsa_cp_reginfo);
8260         /* TTCBR2 is introduced with ARMv8.2-AA32HPD.  */
8261         if (cpu_isar_feature(aa32_hpd, cpu)) {
8262             define_one_arm_cp_reg(cpu, &ttbcr2_reginfo);
8263         }
8264     }
8265     if (arm_feature(env, ARM_FEATURE_THUMB2EE)) {
8266         define_arm_cp_regs(cpu, t2ee_cp_reginfo);
8267     }
8268     if (arm_feature(env, ARM_FEATURE_GENERIC_TIMER)) {
8269         define_arm_cp_regs(cpu, generic_timer_cp_reginfo);
8270     }
8271     if (arm_feature(env, ARM_FEATURE_VAPA)) {
8272         define_arm_cp_regs(cpu, vapa_cp_reginfo);
8273     }
8274     if (arm_feature(env, ARM_FEATURE_CACHE_TEST_CLEAN)) {
8275         define_arm_cp_regs(cpu, cache_test_clean_cp_reginfo);
8276     }
8277     if (arm_feature(env, ARM_FEATURE_CACHE_DIRTY_REG)) {
8278         define_arm_cp_regs(cpu, cache_dirty_status_cp_reginfo);
8279     }
8280     if (arm_feature(env, ARM_FEATURE_CACHE_BLOCK_OPS)) {
8281         define_arm_cp_regs(cpu, cache_block_ops_cp_reginfo);
8282     }
8283     if (arm_feature(env, ARM_FEATURE_OMAPCP)) {
8284         define_arm_cp_regs(cpu, omap_cp_reginfo);
8285     }
8286     if (arm_feature(env, ARM_FEATURE_STRONGARM)) {
8287         define_arm_cp_regs(cpu, strongarm_cp_reginfo);
8288     }
8289     if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8290         define_arm_cp_regs(cpu, xscale_cp_reginfo);
8291     }
8292     if (arm_feature(env, ARM_FEATURE_DUMMY_C15_REGS)) {
8293         define_arm_cp_regs(cpu, dummy_c15_cp_reginfo);
8294     }
8295     if (arm_feature(env, ARM_FEATURE_LPAE)) {
8296         define_arm_cp_regs(cpu, lpae_cp_reginfo);
8297     }
8298     if (cpu_isar_feature(aa32_jazelle, cpu)) {
8299         define_arm_cp_regs(cpu, jazelle_regs);
8300     }
8301     /* Slightly awkwardly, the OMAP and StrongARM cores need all of
8302      * cp15 crn=0 to be writes-ignored, whereas for other cores they should
8303      * be read-only (ie write causes UNDEF exception).
8304      */
8305     {
8306         ARMCPRegInfo id_pre_v8_midr_cp_reginfo[] = {
8307             /* Pre-v8 MIDR space.
8308              * Note that the MIDR isn't a simple constant register because
8309              * of the TI925 behaviour where writes to another register can
8310              * cause the MIDR value to change.
8311              *
8312              * Unimplemented registers in the c15 0 0 0 space default to
8313              * MIDR. Define MIDR first as this entire space, then CTR, TCMTR
8314              * and friends override accordingly.
8315              */
8316             { .name = "MIDR",
8317               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = CP_ANY,
8318               .access = PL1_R, .resetvalue = cpu->midr,
8319               .writefn = arm_cp_write_ignore, .raw_writefn = raw_write,
8320               .readfn = midr_read,
8321               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8322               .type = ARM_CP_OVERRIDE },
8323             /* crn = 0 op1 = 0 crm = 3..7 : currently unassigned; we RAZ. */
8324             { .name = "DUMMY",
8325               .cp = 15, .crn = 0, .crm = 3, .opc1 = 0, .opc2 = CP_ANY,
8326               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8327             { .name = "DUMMY",
8328               .cp = 15, .crn = 0, .crm = 4, .opc1 = 0, .opc2 = CP_ANY,
8329               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8330             { .name = "DUMMY",
8331               .cp = 15, .crn = 0, .crm = 5, .opc1 = 0, .opc2 = CP_ANY,
8332               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8333             { .name = "DUMMY",
8334               .cp = 15, .crn = 0, .crm = 6, .opc1 = 0, .opc2 = CP_ANY,
8335               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8336             { .name = "DUMMY",
8337               .cp = 15, .crn = 0, .crm = 7, .opc1 = 0, .opc2 = CP_ANY,
8338               .access = PL1_R, .type = ARM_CP_CONST, .resetvalue = 0 },
8339             REGINFO_SENTINEL
8340         };
8341         ARMCPRegInfo id_v8_midr_cp_reginfo[] = {
8342             { .name = "MIDR_EL1", .state = ARM_CP_STATE_BOTH,
8343               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 0,
8344               .access = PL1_R, .type = ARM_CP_NO_RAW, .resetvalue = cpu->midr,
8345               .fieldoffset = offsetof(CPUARMState, cp15.c0_cpuid),
8346               .readfn = midr_read },
8347             /* crn = 0 op1 = 0 crm = 0 op2 = 4,7 : AArch32 aliases of MIDR */
8348             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8349               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8350               .access = PL1_R, .resetvalue = cpu->midr },
8351             { .name = "MIDR", .type = ARM_CP_ALIAS | ARM_CP_CONST,
8352               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 7,
8353               .access = PL1_R, .resetvalue = cpu->midr },
8354             { .name = "REVIDR_EL1", .state = ARM_CP_STATE_BOTH,
8355               .opc0 = 3, .opc1 = 0, .crn = 0, .crm = 0, .opc2 = 6,
8356               .access = PL1_R,
8357               .accessfn = access_aa64_tid1,
8358               .type = ARM_CP_CONST, .resetvalue = cpu->revidr },
8359             REGINFO_SENTINEL
8360         };
8361         ARMCPRegInfo id_cp_reginfo[] = {
8362             /* These are common to v8 and pre-v8 */
8363             { .name = "CTR",
8364               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 1,
8365               .access = PL1_R, .accessfn = ctr_el0_access,
8366               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8367             { .name = "CTR_EL0", .state = ARM_CP_STATE_AA64,
8368               .opc0 = 3, .opc1 = 3, .opc2 = 1, .crn = 0, .crm = 0,
8369               .access = PL0_R, .accessfn = ctr_el0_access,
8370               .type = ARM_CP_CONST, .resetvalue = cpu->ctr },
8371             /* TCMTR and TLBTR exist in v8 but have no 64-bit versions */
8372             { .name = "TCMTR",
8373               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 2,
8374               .access = PL1_R,
8375               .accessfn = access_aa32_tid1,
8376               .type = ARM_CP_CONST, .resetvalue = 0 },
8377             REGINFO_SENTINEL
8378         };
8379         /* TLBTR is specific to VMSA */
8380         ARMCPRegInfo id_tlbtr_reginfo = {
8381               .name = "TLBTR",
8382               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 3,
8383               .access = PL1_R,
8384               .accessfn = access_aa32_tid1,
8385               .type = ARM_CP_CONST, .resetvalue = 0,
8386         };
8387         /* MPUIR is specific to PMSA V6+ */
8388         ARMCPRegInfo id_mpuir_reginfo = {
8389               .name = "MPUIR",
8390               .cp = 15, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 4,
8391               .access = PL1_R, .type = ARM_CP_CONST,
8392               .resetvalue = cpu->pmsav7_dregion << 8
8393         };
8394         ARMCPRegInfo crn0_wi_reginfo = {
8395             .name = "CRN0_WI", .cp = 15, .crn = 0, .crm = CP_ANY,
8396             .opc1 = CP_ANY, .opc2 = CP_ANY, .access = PL1_W,
8397             .type = ARM_CP_NOP | ARM_CP_OVERRIDE
8398         };
8399 #ifdef CONFIG_USER_ONLY
8400         ARMCPRegUserSpaceInfo id_v8_user_midr_cp_reginfo[] = {
8401             { .name = "MIDR_EL1",
8402               .exported_bits = 0x00000000ffffffff },
8403             { .name = "REVIDR_EL1"                },
8404             REGUSERINFO_SENTINEL
8405         };
8406         modify_arm_cp_regs(id_v8_midr_cp_reginfo, id_v8_user_midr_cp_reginfo);
8407 #endif
8408         if (arm_feature(env, ARM_FEATURE_OMAPCP) ||
8409             arm_feature(env, ARM_FEATURE_STRONGARM)) {
8410             ARMCPRegInfo *r;
8411             /* Register the blanket "writes ignored" value first to cover the
8412              * whole space. Then update the specific ID registers to allow write
8413              * access, so that they ignore writes rather than causing them to
8414              * UNDEF.
8415              */
8416             define_one_arm_cp_reg(cpu, &crn0_wi_reginfo);
8417             for (r = id_pre_v8_midr_cp_reginfo;
8418                  r->type != ARM_CP_SENTINEL; r++) {
8419                 r->access = PL1_RW;
8420             }
8421             for (r = id_cp_reginfo; r->type != ARM_CP_SENTINEL; r++) {
8422                 r->access = PL1_RW;
8423             }
8424             id_mpuir_reginfo.access = PL1_RW;
8425             id_tlbtr_reginfo.access = PL1_RW;
8426         }
8427         if (arm_feature(env, ARM_FEATURE_V8)) {
8428             define_arm_cp_regs(cpu, id_v8_midr_cp_reginfo);
8429         } else {
8430             define_arm_cp_regs(cpu, id_pre_v8_midr_cp_reginfo);
8431         }
8432         define_arm_cp_regs(cpu, id_cp_reginfo);
8433         if (!arm_feature(env, ARM_FEATURE_PMSA)) {
8434             define_one_arm_cp_reg(cpu, &id_tlbtr_reginfo);
8435         } else if (arm_feature(env, ARM_FEATURE_V7)) {
8436             define_one_arm_cp_reg(cpu, &id_mpuir_reginfo);
8437         }
8438     }
8439 
8440     if (arm_feature(env, ARM_FEATURE_MPIDR)) {
8441         ARMCPRegInfo mpidr_cp_reginfo[] = {
8442             { .name = "MPIDR_EL1", .state = ARM_CP_STATE_BOTH,
8443               .opc0 = 3, .crn = 0, .crm = 0, .opc1 = 0, .opc2 = 5,
8444               .access = PL1_R, .readfn = mpidr_read, .type = ARM_CP_NO_RAW },
8445             REGINFO_SENTINEL
8446         };
8447 #ifdef CONFIG_USER_ONLY
8448         ARMCPRegUserSpaceInfo mpidr_user_cp_reginfo[] = {
8449             { .name = "MPIDR_EL1",
8450               .fixed_bits = 0x0000000080000000 },
8451             REGUSERINFO_SENTINEL
8452         };
8453         modify_arm_cp_regs(mpidr_cp_reginfo, mpidr_user_cp_reginfo);
8454 #endif
8455         define_arm_cp_regs(cpu, mpidr_cp_reginfo);
8456     }
8457 
8458     if (arm_feature(env, ARM_FEATURE_AUXCR)) {
8459         ARMCPRegInfo auxcr_reginfo[] = {
8460             { .name = "ACTLR_EL1", .state = ARM_CP_STATE_BOTH,
8461               .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 1,
8462               .access = PL1_RW, .accessfn = access_tacr,
8463               .type = ARM_CP_CONST, .resetvalue = cpu->reset_auxcr },
8464             { .name = "ACTLR_EL2", .state = ARM_CP_STATE_BOTH,
8465               .opc0 = 3, .opc1 = 4, .crn = 1, .crm = 0, .opc2 = 1,
8466               .access = PL2_RW, .type = ARM_CP_CONST,
8467               .resetvalue = 0 },
8468             { .name = "ACTLR_EL3", .state = ARM_CP_STATE_AA64,
8469               .opc0 = 3, .opc1 = 6, .crn = 1, .crm = 0, .opc2 = 1,
8470               .access = PL3_RW, .type = ARM_CP_CONST,
8471               .resetvalue = 0 },
8472             REGINFO_SENTINEL
8473         };
8474         define_arm_cp_regs(cpu, auxcr_reginfo);
8475         if (cpu_isar_feature(aa32_ac2, cpu)) {
8476             define_arm_cp_regs(cpu, actlr2_hactlr2_reginfo);
8477         }
8478     }
8479 
8480     if (arm_feature(env, ARM_FEATURE_CBAR)) {
8481         /*
8482          * CBAR is IMPDEF, but common on Arm Cortex-A implementations.
8483          * There are two flavours:
8484          *  (1) older 32-bit only cores have a simple 32-bit CBAR
8485          *  (2) 64-bit cores have a 64-bit CBAR visible to AArch64, plus a
8486          *      32-bit register visible to AArch32 at a different encoding
8487          *      to the "flavour 1" register and with the bits rearranged to
8488          *      be able to squash a 64-bit address into the 32-bit view.
8489          * We distinguish the two via the ARM_FEATURE_AARCH64 flag, but
8490          * in future if we support AArch32-only configs of some of the
8491          * AArch64 cores we might need to add a specific feature flag
8492          * to indicate cores with "flavour 2" CBAR.
8493          */
8494         if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8495             /* 32 bit view is [31:18] 0...0 [43:32]. */
8496             uint32_t cbar32 = (extract64(cpu->reset_cbar, 18, 14) << 18)
8497                 | extract64(cpu->reset_cbar, 32, 12);
8498             ARMCPRegInfo cbar_reginfo[] = {
8499                 { .name = "CBAR",
8500                   .type = ARM_CP_CONST,
8501                   .cp = 15, .crn = 15, .crm = 3, .opc1 = 1, .opc2 = 0,
8502                   .access = PL1_R, .resetvalue = cbar32 },
8503                 { .name = "CBAR_EL1", .state = ARM_CP_STATE_AA64,
8504                   .type = ARM_CP_CONST,
8505                   .opc0 = 3, .opc1 = 1, .crn = 15, .crm = 3, .opc2 = 0,
8506                   .access = PL1_R, .resetvalue = cpu->reset_cbar },
8507                 REGINFO_SENTINEL
8508             };
8509             /* We don't implement a r/w 64 bit CBAR currently */
8510             assert(arm_feature(env, ARM_FEATURE_CBAR_RO));
8511             define_arm_cp_regs(cpu, cbar_reginfo);
8512         } else {
8513             ARMCPRegInfo cbar = {
8514                 .name = "CBAR",
8515                 .cp = 15, .crn = 15, .crm = 0, .opc1 = 4, .opc2 = 0,
8516                 .access = PL1_R|PL3_W, .resetvalue = cpu->reset_cbar,
8517                 .fieldoffset = offsetof(CPUARMState,
8518                                         cp15.c15_config_base_address)
8519             };
8520             if (arm_feature(env, ARM_FEATURE_CBAR_RO)) {
8521                 cbar.access = PL1_R;
8522                 cbar.fieldoffset = 0;
8523                 cbar.type = ARM_CP_CONST;
8524             }
8525             define_one_arm_cp_reg(cpu, &cbar);
8526         }
8527     }
8528 
8529     if (arm_feature(env, ARM_FEATURE_VBAR)) {
8530         ARMCPRegInfo vbar_cp_reginfo[] = {
8531             { .name = "VBAR", .state = ARM_CP_STATE_BOTH,
8532               .opc0 = 3, .crn = 12, .crm = 0, .opc1 = 0, .opc2 = 0,
8533               .access = PL1_RW, .writefn = vbar_write,
8534               .bank_fieldoffsets = { offsetof(CPUARMState, cp15.vbar_s),
8535                                      offsetof(CPUARMState, cp15.vbar_ns) },
8536               .resetvalue = 0 },
8537             REGINFO_SENTINEL
8538         };
8539         define_arm_cp_regs(cpu, vbar_cp_reginfo);
8540     }
8541 
8542     /* Generic registers whose values depend on the implementation */
8543     {
8544         ARMCPRegInfo sctlr = {
8545             .name = "SCTLR", .state = ARM_CP_STATE_BOTH,
8546             .opc0 = 3, .opc1 = 0, .crn = 1, .crm = 0, .opc2 = 0,
8547             .access = PL1_RW, .accessfn = access_tvm_trvm,
8548             .bank_fieldoffsets = { offsetof(CPUARMState, cp15.sctlr_s),
8549                                    offsetof(CPUARMState, cp15.sctlr_ns) },
8550             .writefn = sctlr_write, .resetvalue = cpu->reset_sctlr,
8551             .raw_writefn = raw_write,
8552         };
8553         if (arm_feature(env, ARM_FEATURE_XSCALE)) {
8554             /* Normally we would always end the TB on an SCTLR write, but Linux
8555              * arch/arm/mach-pxa/sleep.S expects two instructions following
8556              * an MMU enable to execute from cache.  Imitate this behaviour.
8557              */
8558             sctlr.type |= ARM_CP_SUPPRESS_TB_END;
8559         }
8560         define_one_arm_cp_reg(cpu, &sctlr);
8561     }
8562 
8563     if (cpu_isar_feature(aa64_lor, cpu)) {
8564         define_arm_cp_regs(cpu, lor_reginfo);
8565     }
8566     if (cpu_isar_feature(aa64_pan, cpu)) {
8567         define_one_arm_cp_reg(cpu, &pan_reginfo);
8568     }
8569 #ifndef CONFIG_USER_ONLY
8570     if (cpu_isar_feature(aa64_ats1e1, cpu)) {
8571         define_arm_cp_regs(cpu, ats1e1_reginfo);
8572     }
8573     if (cpu_isar_feature(aa32_ats1e1, cpu)) {
8574         define_arm_cp_regs(cpu, ats1cp_reginfo);
8575     }
8576 #endif
8577     if (cpu_isar_feature(aa64_uao, cpu)) {
8578         define_one_arm_cp_reg(cpu, &uao_reginfo);
8579     }
8580 
8581     if (cpu_isar_feature(aa64_dit, cpu)) {
8582         define_one_arm_cp_reg(cpu, &dit_reginfo);
8583     }
8584     if (cpu_isar_feature(aa64_ssbs, cpu)) {
8585         define_one_arm_cp_reg(cpu, &ssbs_reginfo);
8586     }
8587 
8588     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8589         define_arm_cp_regs(cpu, vhe_reginfo);
8590     }
8591 
8592     if (cpu_isar_feature(aa64_sve, cpu)) {
8593         define_one_arm_cp_reg(cpu, &zcr_el1_reginfo);
8594         if (arm_feature(env, ARM_FEATURE_EL2)) {
8595             define_one_arm_cp_reg(cpu, &zcr_el2_reginfo);
8596         } else {
8597             define_one_arm_cp_reg(cpu, &zcr_no_el2_reginfo);
8598         }
8599         if (arm_feature(env, ARM_FEATURE_EL3)) {
8600             define_one_arm_cp_reg(cpu, &zcr_el3_reginfo);
8601         }
8602     }
8603 
8604 #ifdef TARGET_AARCH64
8605     if (cpu_isar_feature(aa64_pauth, cpu)) {
8606         define_arm_cp_regs(cpu, pauth_reginfo);
8607     }
8608     if (cpu_isar_feature(aa64_rndr, cpu)) {
8609         define_arm_cp_regs(cpu, rndr_reginfo);
8610     }
8611     if (cpu_isar_feature(aa64_tlbirange, cpu)) {
8612         define_arm_cp_regs(cpu, tlbirange_reginfo);
8613     }
8614     if (cpu_isar_feature(aa64_tlbios, cpu)) {
8615         define_arm_cp_regs(cpu, tlbios_reginfo);
8616     }
8617 #ifndef CONFIG_USER_ONLY
8618     /* Data Cache clean instructions up to PoP */
8619     if (cpu_isar_feature(aa64_dcpop, cpu)) {
8620         define_one_arm_cp_reg(cpu, dcpop_reg);
8621 
8622         if (cpu_isar_feature(aa64_dcpodp, cpu)) {
8623             define_one_arm_cp_reg(cpu, dcpodp_reg);
8624         }
8625     }
8626 #endif /*CONFIG_USER_ONLY*/
8627 
8628     /*
8629      * If full MTE is enabled, add all of the system registers.
8630      * If only "instructions available at EL0" are enabled,
8631      * then define only a RAZ/WI version of PSTATE.TCO.
8632      */
8633     if (cpu_isar_feature(aa64_mte, cpu)) {
8634         define_arm_cp_regs(cpu, mte_reginfo);
8635         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8636     } else if (cpu_isar_feature(aa64_mte_insn_reg, cpu)) {
8637         define_arm_cp_regs(cpu, mte_tco_ro_reginfo);
8638         define_arm_cp_regs(cpu, mte_el0_cacheop_reginfo);
8639     }
8640 #endif
8641 
8642     if (cpu_isar_feature(any_predinv, cpu)) {
8643         define_arm_cp_regs(cpu, predinv_reginfo);
8644     }
8645 
8646     if (cpu_isar_feature(any_ccidx, cpu)) {
8647         define_arm_cp_regs(cpu, ccsidr2_reginfo);
8648     }
8649 
8650 #ifndef CONFIG_USER_ONLY
8651     /*
8652      * Register redirections and aliases must be done last,
8653      * after the registers from the other extensions have been defined.
8654      */
8655     if (arm_feature(env, ARM_FEATURE_EL2) && cpu_isar_feature(aa64_vh, cpu)) {
8656         define_arm_vh_e2h_redirects_aliases(cpu);
8657     }
8658 #endif
8659 }
8660 
8661 void arm_cpu_register_gdb_regs_for_features(ARMCPU *cpu)
8662 {
8663     CPUState *cs = CPU(cpu);
8664     CPUARMState *env = &cpu->env;
8665 
8666     if (arm_feature(env, ARM_FEATURE_AARCH64)) {
8667         /*
8668          * The lower part of each SVE register aliases to the FPU
8669          * registers so we don't need to include both.
8670          */
8671 #ifdef TARGET_AARCH64
8672         if (isar_feature_aa64_sve(&cpu->isar)) {
8673             gdb_register_coprocessor(cs, arm_gdb_get_svereg, arm_gdb_set_svereg,
8674                                      arm_gen_dynamic_svereg_xml(cs, cs->gdb_num_regs),
8675                                      "sve-registers.xml", 0);
8676         } else
8677 #endif
8678         {
8679             gdb_register_coprocessor(cs, aarch64_fpu_gdb_get_reg,
8680                                      aarch64_fpu_gdb_set_reg,
8681                                      34, "aarch64-fpu.xml", 0);
8682         }
8683     } else if (arm_feature(env, ARM_FEATURE_NEON)) {
8684         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8685                                  51, "arm-neon.xml", 0);
8686     } else if (cpu_isar_feature(aa32_simd_r32, cpu)) {
8687         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8688                                  35, "arm-vfp3.xml", 0);
8689     } else if (cpu_isar_feature(aa32_vfp_simd, cpu)) {
8690         gdb_register_coprocessor(cs, vfp_gdb_get_reg, vfp_gdb_set_reg,
8691                                  19, "arm-vfp.xml", 0);
8692     }
8693     gdb_register_coprocessor(cs, arm_gdb_get_sysreg, arm_gdb_set_sysreg,
8694                              arm_gen_dynamic_sysreg_xml(cs, cs->gdb_num_regs),
8695                              "system-registers.xml", 0);
8696 
8697 }
8698 
8699 /* Sort alphabetically by type name, except for "any". */
8700 static gint arm_cpu_list_compare(gconstpointer a, gconstpointer b)
8701 {
8702     ObjectClass *class_a = (ObjectClass *)a;
8703     ObjectClass *class_b = (ObjectClass *)b;
8704     const char *name_a, *name_b;
8705 
8706     name_a = object_class_get_name(class_a);
8707     name_b = object_class_get_name(class_b);
8708     if (strcmp(name_a, "any-" TYPE_ARM_CPU) == 0) {
8709         return 1;
8710     } else if (strcmp(name_b, "any-" TYPE_ARM_CPU) == 0) {
8711         return -1;
8712     } else {
8713         return strcmp(name_a, name_b);
8714     }
8715 }
8716 
8717 static void arm_cpu_list_entry(gpointer data, gpointer user_data)
8718 {
8719     ObjectClass *oc = data;
8720     const char *typename;
8721     char *name;
8722 
8723     typename = object_class_get_name(oc);
8724     name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_ARM_CPU));
8725     qemu_printf("  %s\n", name);
8726     g_free(name);
8727 }
8728 
8729 void arm_cpu_list(void)
8730 {
8731     GSList *list;
8732 
8733     list = object_class_get_list(TYPE_ARM_CPU, false);
8734     list = g_slist_sort(list, arm_cpu_list_compare);
8735     qemu_printf("Available CPUs:\n");
8736     g_slist_foreach(list, arm_cpu_list_entry, NULL);
8737     g_slist_free(list);
8738 }
8739 
8740 static void arm_cpu_add_definition(gpointer data, gpointer user_data)
8741 {
8742     ObjectClass *oc = data;
8743     CpuDefinitionInfoList **cpu_list = user_data;
8744     CpuDefinitionInfo *info;
8745     const char *typename;
8746 
8747     typename = object_class_get_name(oc);
8748     info = g_malloc0(sizeof(*info));
8749     info->name = g_strndup(typename,
8750                            strlen(typename) - strlen("-" TYPE_ARM_CPU));
8751     info->q_typename = g_strdup(typename);
8752 
8753     QAPI_LIST_PREPEND(*cpu_list, info);
8754 }
8755 
8756 CpuDefinitionInfoList *qmp_query_cpu_definitions(Error **errp)
8757 {
8758     CpuDefinitionInfoList *cpu_list = NULL;
8759     GSList *list;
8760 
8761     list = object_class_get_list(TYPE_ARM_CPU, false);
8762     g_slist_foreach(list, arm_cpu_add_definition, &cpu_list);
8763     g_slist_free(list);
8764 
8765     return cpu_list;
8766 }
8767 
8768 static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,
8769                                    void *opaque, int state, int secstate,
8770                                    int crm, int opc1, int opc2,
8771                                    const char *name)
8772 {
8773     /* Private utility function for define_one_arm_cp_reg_with_opaque():
8774      * add a single reginfo struct to the hash table.
8775      */
8776     uint32_t *key = g_new(uint32_t, 1);
8777     ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));
8778     int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;
8779     int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;
8780 
8781     r2->name = g_strdup(name);
8782     /* Reset the secure state to the specific incoming state.  This is
8783      * necessary as the register may have been defined with both states.
8784      */
8785     r2->secure = secstate;
8786 
8787     if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8788         /* Register is banked (using both entries in array).
8789          * Overwriting fieldoffset as the array is only used to define
8790          * banked registers but later only fieldoffset is used.
8791          */
8792         r2->fieldoffset = r->bank_fieldoffsets[ns];
8793     }
8794 
8795     if (state == ARM_CP_STATE_AA32) {
8796         if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {
8797             /* If the register is banked then we don't need to migrate or
8798              * reset the 32-bit instance in certain cases:
8799              *
8800              * 1) If the register has both 32-bit and 64-bit instances then we
8801              *    can count on the 64-bit instance taking care of the
8802              *    non-secure bank.
8803              * 2) If ARMv8 is enabled then we can count on a 64-bit version
8804              *    taking care of the secure bank.  This requires that separate
8805              *    32 and 64-bit definitions are provided.
8806              */
8807             if ((r->state == ARM_CP_STATE_BOTH && ns) ||
8808                 (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {
8809                 r2->type |= ARM_CP_ALIAS;
8810             }
8811         } else if ((secstate != r->secure) && !ns) {
8812             /* The register is not banked so we only want to allow migration of
8813              * the non-secure instance.
8814              */
8815             r2->type |= ARM_CP_ALIAS;
8816         }
8817 
8818         if (r->state == ARM_CP_STATE_BOTH) {
8819             /* We assume it is a cp15 register if the .cp field is left unset.
8820              */
8821             if (r2->cp == 0) {
8822                 r2->cp = 15;
8823             }
8824 
8825 #ifdef HOST_WORDS_BIGENDIAN
8826             if (r2->fieldoffset) {
8827                 r2->fieldoffset += sizeof(uint32_t);
8828             }
8829 #endif
8830         }
8831     }
8832     if (state == ARM_CP_STATE_AA64) {
8833         /* To allow abbreviation of ARMCPRegInfo
8834          * definitions, we treat cp == 0 as equivalent to
8835          * the value for "standard guest-visible sysreg".
8836          * STATE_BOTH definitions are also always "standard
8837          * sysreg" in their AArch64 view (the .cp value may
8838          * be non-zero for the benefit of the AArch32 view).
8839          */
8840         if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {
8841             r2->cp = CP_REG_ARM64_SYSREG_CP;
8842         }
8843         *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,
8844                                   r2->opc0, opc1, opc2);
8845     } else {
8846         *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);
8847     }
8848     if (opaque) {
8849         r2->opaque = opaque;
8850     }
8851     /* reginfo passed to helpers is correct for the actual access,
8852      * and is never ARM_CP_STATE_BOTH:
8853      */
8854     r2->state = state;
8855     /* Make sure reginfo passed to helpers for wildcarded regs
8856      * has the correct crm/opc1/opc2 for this reg, not CP_ANY:
8857      */
8858     r2->crm = crm;
8859     r2->opc1 = opc1;
8860     r2->opc2 = opc2;
8861     /* By convention, for wildcarded registers only the first
8862      * entry is used for migration; the others are marked as
8863      * ALIAS so we don't try to transfer the register
8864      * multiple times. Special registers (ie NOP/WFI) are
8865      * never migratable and not even raw-accessible.
8866      */
8867     if ((r->type & ARM_CP_SPECIAL)) {
8868         r2->type |= ARM_CP_NO_RAW;
8869     }
8870     if (((r->crm == CP_ANY) && crm != 0) ||
8871         ((r->opc1 == CP_ANY) && opc1 != 0) ||
8872         ((r->opc2 == CP_ANY) && opc2 != 0)) {
8873         r2->type |= ARM_CP_ALIAS | ARM_CP_NO_GDB;
8874     }
8875 
8876     /* Check that raw accesses are either forbidden or handled. Note that
8877      * we can't assert this earlier because the setup of fieldoffset for
8878      * banked registers has to be done first.
8879      */
8880     if (!(r2->type & ARM_CP_NO_RAW)) {
8881         assert(!raw_accessors_invalid(r2));
8882     }
8883 
8884     /* Overriding of an existing definition must be explicitly
8885      * requested.
8886      */
8887     if (!(r->type & ARM_CP_OVERRIDE)) {
8888         ARMCPRegInfo *oldreg;
8889         oldreg = g_hash_table_lookup(cpu->cp_regs, key);
8890         if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {
8891             fprintf(stderr, "Register redefined: cp=%d %d bit "
8892                     "crn=%d crm=%d opc1=%d opc2=%d, "
8893                     "was %s, now %s\n", r2->cp, 32 + 32 * is64,
8894                     r2->crn, r2->crm, r2->opc1, r2->opc2,
8895                     oldreg->name, r2->name);
8896             g_assert_not_reached();
8897         }
8898     }
8899     g_hash_table_insert(cpu->cp_regs, key, r2);
8900 }
8901 
8902 
8903 void define_one_arm_cp_reg_with_opaque(ARMCPU *cpu,
8904                                        const ARMCPRegInfo *r, void *opaque)
8905 {
8906     /* Define implementations of coprocessor registers.
8907      * We store these in a hashtable because typically
8908      * there are less than 150 registers in a space which
8909      * is 16*16*16*8*8 = 262144 in size.
8910      * Wildcarding is supported for the crm, opc1 and opc2 fields.
8911      * If a register is defined twice then the second definition is
8912      * used, so this can be used to define some generic registers and
8913      * then override them with implementation specific variations.
8914      * At least one of the original and the second definition should
8915      * include ARM_CP_OVERRIDE in its type bits -- this is just a guard
8916      * against accidental use.
8917      *
8918      * The state field defines whether the register is to be
8919      * visible in the AArch32 or AArch64 execution state. If the
8920      * state is set to ARM_CP_STATE_BOTH then we synthesise a
8921      * reginfo structure for the AArch32 view, which sees the lower
8922      * 32 bits of the 64 bit register.
8923      *
8924      * Only registers visible in AArch64 may set r->opc0; opc0 cannot
8925      * be wildcarded. AArch64 registers are always considered to be 64
8926      * bits; the ARM_CP_64BIT* flag applies only to the AArch32 view of
8927      * the register, if any.
8928      */
8929     int crm, opc1, opc2, state;
8930     int crmmin = (r->crm == CP_ANY) ? 0 : r->crm;
8931     int crmmax = (r->crm == CP_ANY) ? 15 : r->crm;
8932     int opc1min = (r->opc1 == CP_ANY) ? 0 : r->opc1;
8933     int opc1max = (r->opc1 == CP_ANY) ? 7 : r->opc1;
8934     int opc2min = (r->opc2 == CP_ANY) ? 0 : r->opc2;
8935     int opc2max = (r->opc2 == CP_ANY) ? 7 : r->opc2;
8936     /* 64 bit registers have only CRm and Opc1 fields */
8937     assert(!((r->type & ARM_CP_64BIT) && (r->opc2 || r->crn)));
8938     /* op0 only exists in the AArch64 encodings */
8939     assert((r->state != ARM_CP_STATE_AA32) || (r->opc0 == 0));
8940     /* AArch64 regs are all 64 bit so ARM_CP_64BIT is meaningless */
8941     assert((r->state != ARM_CP_STATE_AA64) || !(r->type & ARM_CP_64BIT));
8942     /*
8943      * This API is only for Arm's system coprocessors (14 and 15) or
8944      * (M-profile or v7A-and-earlier only) for implementation defined
8945      * coprocessors in the range 0..7.  Our decode assumes this, since
8946      * 8..13 can be used for other insns including VFP and Neon. See
8947      * valid_cp() in translate.c.  Assert here that we haven't tried
8948      * to use an invalid coprocessor number.
8949      */
8950     switch (r->state) {
8951     case ARM_CP_STATE_BOTH:
8952         /* 0 has a special meaning, but otherwise the same rules as AA32. */
8953         if (r->cp == 0) {
8954             break;
8955         }
8956         /* fall through */
8957     case ARM_CP_STATE_AA32:
8958         if (arm_feature(&cpu->env, ARM_FEATURE_V8) &&
8959             !arm_feature(&cpu->env, ARM_FEATURE_M)) {
8960             assert(r->cp >= 14 && r->cp <= 15);
8961         } else {
8962             assert(r->cp < 8 || (r->cp >= 14 && r->cp <= 15));
8963         }
8964         break;
8965     case ARM_CP_STATE_AA64:
8966         assert(r->cp == 0 || r->cp == CP_REG_ARM64_SYSREG_CP);
8967         break;
8968     default:
8969         g_assert_not_reached();
8970     }
8971     /* The AArch64 pseudocode CheckSystemAccess() specifies that op1
8972      * encodes a minimum access level for the register. We roll this
8973      * runtime check into our general permission check code, so check
8974      * here that the reginfo's specified permissions are strict enough
8975      * to encompass the generic architectural permission check.
8976      */
8977     if (r->state != ARM_CP_STATE_AA32) {
8978         int mask = 0;
8979         switch (r->opc1) {
8980         case 0:
8981             /* min_EL EL1, but some accessible to EL0 via kernel ABI */
8982             mask = PL0U_R | PL1_RW;
8983             break;
8984         case 1: case 2:
8985             /* min_EL EL1 */
8986             mask = PL1_RW;
8987             break;
8988         case 3:
8989             /* min_EL EL0 */
8990             mask = PL0_RW;
8991             break;
8992         case 4:
8993         case 5:
8994             /* min_EL EL2 */
8995             mask = PL2_RW;
8996             break;
8997         case 6:
8998             /* min_EL EL3 */
8999             mask = PL3_RW;
9000             break;
9001         case 7:
9002             /* min_EL EL1, secure mode only (we don't check the latter) */
9003             mask = PL1_RW;
9004             break;
9005         default:
9006             /* broken reginfo with out-of-range opc1 */
9007             assert(false);
9008             break;
9009         }
9010         /* assert our permissions are not too lax (stricter is fine) */
9011         assert((r->access & ~mask) == 0);
9012     }
9013 
9014     /* Check that the register definition has enough info to handle
9015      * reads and writes if they are permitted.
9016      */
9017     if (!(r->type & (ARM_CP_SPECIAL|ARM_CP_CONST))) {
9018         if (r->access & PL3_R) {
9019             assert((r->fieldoffset ||
9020                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
9021                    r->readfn);
9022         }
9023         if (r->access & PL3_W) {
9024             assert((r->fieldoffset ||
9025                    (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1])) ||
9026                    r->writefn);
9027         }
9028     }
9029     /* Bad type field probably means missing sentinel at end of reg list */
9030     assert(cptype_valid(r->type));
9031     for (crm = crmmin; crm <= crmmax; crm++) {
9032         for (opc1 = opc1min; opc1 <= opc1max; opc1++) {
9033             for (opc2 = opc2min; opc2 <= opc2max; opc2++) {
9034                 for (state = ARM_CP_STATE_AA32;
9035                      state <= ARM_CP_STATE_AA64; state++) {
9036                     if (r->state != state && r->state != ARM_CP_STATE_BOTH) {
9037                         continue;
9038                     }
9039                     if (state == ARM_CP_STATE_AA32) {
9040                         /* Under AArch32 CP registers can be common
9041                          * (same for secure and non-secure world) or banked.
9042                          */
9043                         char *name;
9044 
9045                         switch (r->secure) {
9046                         case ARM_CP_SECSTATE_S:
9047                         case ARM_CP_SECSTATE_NS:
9048                             add_cpreg_to_hashtable(cpu, r, opaque, state,
9049                                                    r->secure, crm, opc1, opc2,
9050                                                    r->name);
9051                             break;
9052                         default:
9053                             name = g_strdup_printf("%s_S", r->name);
9054                             add_cpreg_to_hashtable(cpu, r, opaque, state,
9055                                                    ARM_CP_SECSTATE_S,
9056                                                    crm, opc1, opc2, name);
9057                             g_free(name);
9058                             add_cpreg_to_hashtable(cpu, r, opaque, state,
9059                                                    ARM_CP_SECSTATE_NS,
9060                                                    crm, opc1, opc2, r->name);
9061                             break;
9062                         }
9063                     } else {
9064                         /* AArch64 registers get mapped to non-secure instance
9065                          * of AArch32 */
9066                         add_cpreg_to_hashtable(cpu, r, opaque, state,
9067                                                ARM_CP_SECSTATE_NS,
9068                                                crm, opc1, opc2, r->name);
9069                     }
9070                 }
9071             }
9072         }
9073     }
9074 }
9075 
9076 void define_arm_cp_regs_with_opaque(ARMCPU *cpu,
9077                                     const ARMCPRegInfo *regs, void *opaque)
9078 {
9079     /* Define a whole list of registers */
9080     const ARMCPRegInfo *r;
9081     for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
9082         define_one_arm_cp_reg_with_opaque(cpu, r, opaque);
9083     }
9084 }
9085 
9086 /*
9087  * Modify ARMCPRegInfo for access from userspace.
9088  *
9089  * This is a data driven modification directed by
9090  * ARMCPRegUserSpaceInfo. All registers become ARM_CP_CONST as
9091  * user-space cannot alter any values and dynamic values pertaining to
9092  * execution state are hidden from user space view anyway.
9093  */
9094 void modify_arm_cp_regs(ARMCPRegInfo *regs, const ARMCPRegUserSpaceInfo *mods)
9095 {
9096     const ARMCPRegUserSpaceInfo *m;
9097     ARMCPRegInfo *r;
9098 
9099     for (m = mods; m->name; m++) {
9100         GPatternSpec *pat = NULL;
9101         if (m->is_glob) {
9102             pat = g_pattern_spec_new(m->name);
9103         }
9104         for (r = regs; r->type != ARM_CP_SENTINEL; r++) {
9105             if (pat && g_pattern_match_string(pat, r->name)) {
9106                 r->type = ARM_CP_CONST;
9107                 r->access = PL0U_R;
9108                 r->resetvalue = 0;
9109                 /* continue */
9110             } else if (strcmp(r->name, m->name) == 0) {
9111                 r->type = ARM_CP_CONST;
9112                 r->access = PL0U_R;
9113                 r->resetvalue &= m->exported_bits;
9114                 r->resetvalue |= m->fixed_bits;
9115                 break;
9116             }
9117         }
9118         if (pat) {
9119             g_pattern_spec_free(pat);
9120         }
9121     }
9122 }
9123 
9124 const ARMCPRegInfo *get_arm_cp_reginfo(GHashTable *cpregs, uint32_t encoded_cp)
9125 {
9126     return g_hash_table_lookup(cpregs, &encoded_cp);
9127 }
9128 
9129 void arm_cp_write_ignore(CPUARMState *env, const ARMCPRegInfo *ri,
9130                          uint64_t value)
9131 {
9132     /* Helper coprocessor write function for write-ignore registers */
9133 }
9134 
9135 uint64_t arm_cp_read_zero(CPUARMState *env, const ARMCPRegInfo *ri)
9136 {
9137     /* Helper coprocessor write function for read-as-zero registers */
9138     return 0;
9139 }
9140 
9141 void arm_cp_reset_ignore(CPUARMState *env, const ARMCPRegInfo *opaque)
9142 {
9143     /* Helper coprocessor reset function for do-nothing-on-reset registers */
9144 }
9145 
9146 static int bad_mode_switch(CPUARMState *env, int mode, CPSRWriteType write_type)
9147 {
9148     /* Return true if it is not valid for us to switch to
9149      * this CPU mode (ie all the UNPREDICTABLE cases in
9150      * the ARM ARM CPSRWriteByInstr pseudocode).
9151      */
9152 
9153     /* Changes to or from Hyp via MSR and CPS are illegal. */
9154     if (write_type == CPSRWriteByInstr &&
9155         ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_HYP ||
9156          mode == ARM_CPU_MODE_HYP)) {
9157         return 1;
9158     }
9159 
9160     switch (mode) {
9161     case ARM_CPU_MODE_USR:
9162         return 0;
9163     case ARM_CPU_MODE_SYS:
9164     case ARM_CPU_MODE_SVC:
9165     case ARM_CPU_MODE_ABT:
9166     case ARM_CPU_MODE_UND:
9167     case ARM_CPU_MODE_IRQ:
9168     case ARM_CPU_MODE_FIQ:
9169         /* Note that we don't implement the IMPDEF NSACR.RFR which in v7
9170          * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)
9171          */
9172         /* If HCR.TGE is set then changes from Monitor to NS PL1 via MSR
9173          * and CPS are treated as illegal mode changes.
9174          */
9175         if (write_type == CPSRWriteByInstr &&
9176             (env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON &&
9177             (arm_hcr_el2_eff(env) & HCR_TGE)) {
9178             return 1;
9179         }
9180         return 0;
9181     case ARM_CPU_MODE_HYP:
9182         return !arm_is_el2_enabled(env) || arm_current_el(env) < 2;
9183     case ARM_CPU_MODE_MON:
9184         return arm_current_el(env) < 3;
9185     default:
9186         return 1;
9187     }
9188 }
9189 
9190 uint32_t cpsr_read(CPUARMState *env)
9191 {
9192     int ZF;
9193     ZF = (env->ZF == 0);
9194     return env->uncached_cpsr | (env->NF & 0x80000000) | (ZF << 30) |
9195         (env->CF << 29) | ((env->VF & 0x80000000) >> 3) | (env->QF << 27)
9196         | (env->thumb << 5) | ((env->condexec_bits & 3) << 25)
9197         | ((env->condexec_bits & 0xfc) << 8)
9198         | (env->GE << 16) | (env->daif & CPSR_AIF);
9199 }
9200 
9201 void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,
9202                 CPSRWriteType write_type)
9203 {
9204     uint32_t changed_daif;
9205     bool rebuild_hflags = (write_type != CPSRWriteRaw) &&
9206         (mask & (CPSR_M | CPSR_E | CPSR_IL));
9207 
9208     if (mask & CPSR_NZCV) {
9209         env->ZF = (~val) & CPSR_Z;
9210         env->NF = val;
9211         env->CF = (val >> 29) & 1;
9212         env->VF = (val << 3) & 0x80000000;
9213     }
9214     if (mask & CPSR_Q)
9215         env->QF = ((val & CPSR_Q) != 0);
9216     if (mask & CPSR_T)
9217         env->thumb = ((val & CPSR_T) != 0);
9218     if (mask & CPSR_IT_0_1) {
9219         env->condexec_bits &= ~3;
9220         env->condexec_bits |= (val >> 25) & 3;
9221     }
9222     if (mask & CPSR_IT_2_7) {
9223         env->condexec_bits &= 3;
9224         env->condexec_bits |= (val >> 8) & 0xfc;
9225     }
9226     if (mask & CPSR_GE) {
9227         env->GE = (val >> 16) & 0xf;
9228     }
9229 
9230     /* In a V7 implementation that includes the security extensions but does
9231      * not include Virtualization Extensions the SCR.FW and SCR.AW bits control
9232      * whether non-secure software is allowed to change the CPSR_F and CPSR_A
9233      * bits respectively.
9234      *
9235      * In a V8 implementation, it is permitted for privileged software to
9236      * change the CPSR A/F bits regardless of the SCR.AW/FW bits.
9237      */
9238     if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&
9239         arm_feature(env, ARM_FEATURE_EL3) &&
9240         !arm_feature(env, ARM_FEATURE_EL2) &&
9241         !arm_is_secure(env)) {
9242 
9243         changed_daif = (env->daif ^ val) & mask;
9244 
9245         if (changed_daif & CPSR_A) {
9246             /* Check to see if we are allowed to change the masking of async
9247              * abort exceptions from a non-secure state.
9248              */
9249             if (!(env->cp15.scr_el3 & SCR_AW)) {
9250                 qemu_log_mask(LOG_GUEST_ERROR,
9251                               "Ignoring attempt to switch CPSR_A flag from "
9252                               "non-secure world with SCR.AW bit clear\n");
9253                 mask &= ~CPSR_A;
9254             }
9255         }
9256 
9257         if (changed_daif & CPSR_F) {
9258             /* Check to see if we are allowed to change the masking of FIQ
9259              * exceptions from a non-secure state.
9260              */
9261             if (!(env->cp15.scr_el3 & SCR_FW)) {
9262                 qemu_log_mask(LOG_GUEST_ERROR,
9263                               "Ignoring attempt to switch CPSR_F flag from "
9264                               "non-secure world with SCR.FW bit clear\n");
9265                 mask &= ~CPSR_F;
9266             }
9267 
9268             /* Check whether non-maskable FIQ (NMFI) support is enabled.
9269              * If this bit is set software is not allowed to mask
9270              * FIQs, but is allowed to set CPSR_F to 0.
9271              */
9272             if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&
9273                 (val & CPSR_F)) {
9274                 qemu_log_mask(LOG_GUEST_ERROR,
9275                               "Ignoring attempt to enable CPSR_F flag "
9276                               "(non-maskable FIQ [NMFI] support enabled)\n");
9277                 mask &= ~CPSR_F;
9278             }
9279         }
9280     }
9281 
9282     env->daif &= ~(CPSR_AIF & mask);
9283     env->daif |= val & CPSR_AIF & mask;
9284 
9285     if (write_type != CPSRWriteRaw &&
9286         ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {
9287         if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_USR) {
9288             /* Note that we can only get here in USR mode if this is a
9289              * gdb stub write; for this case we follow the architectural
9290              * behaviour for guest writes in USR mode of ignoring an attempt
9291              * to switch mode. (Those are caught by translate.c for writes
9292              * triggered by guest instructions.)
9293              */
9294             mask &= ~CPSR_M;
9295         } else if (bad_mode_switch(env, val & CPSR_M, write_type)) {
9296             /* Attempt to switch to an invalid mode: this is UNPREDICTABLE in
9297              * v7, and has defined behaviour in v8:
9298              *  + leave CPSR.M untouched
9299              *  + allow changes to the other CPSR fields
9300              *  + set PSTATE.IL
9301              * For user changes via the GDB stub, we don't set PSTATE.IL,
9302              * as this would be unnecessarily harsh for a user error.
9303              */
9304             mask &= ~CPSR_M;
9305             if (write_type != CPSRWriteByGDBStub &&
9306                 arm_feature(env, ARM_FEATURE_V8)) {
9307                 mask |= CPSR_IL;
9308                 val |= CPSR_IL;
9309             }
9310             qemu_log_mask(LOG_GUEST_ERROR,
9311                           "Illegal AArch32 mode switch attempt from %s to %s\n",
9312                           aarch32_mode_name(env->uncached_cpsr),
9313                           aarch32_mode_name(val));
9314         } else {
9315             qemu_log_mask(CPU_LOG_INT, "%s %s to %s PC 0x%" PRIx32 "\n",
9316                           write_type == CPSRWriteExceptionReturn ?
9317                           "Exception return from AArch32" :
9318                           "AArch32 mode switch from",
9319                           aarch32_mode_name(env->uncached_cpsr),
9320                           aarch32_mode_name(val), env->regs[15]);
9321             switch_mode(env, val & CPSR_M);
9322         }
9323     }
9324     mask &= ~CACHED_CPSR_BITS;
9325     env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);
9326     if (rebuild_hflags) {
9327         arm_rebuild_hflags(env);
9328     }
9329 }
9330 
9331 /* Sign/zero extend */
9332 uint32_t HELPER(sxtb16)(uint32_t x)
9333 {
9334     uint32_t res;
9335     res = (uint16_t)(int8_t)x;
9336     res |= (uint32_t)(int8_t)(x >> 16) << 16;
9337     return res;
9338 }
9339 
9340 static void handle_possible_div0_trap(CPUARMState *env, uintptr_t ra)
9341 {
9342     /*
9343      * Take a division-by-zero exception if necessary; otherwise return
9344      * to get the usual non-trapping division behaviour (result of 0)
9345      */
9346     if (arm_feature(env, ARM_FEATURE_M)
9347         && (env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_DIV_0_TRP_MASK)) {
9348         raise_exception_ra(env, EXCP_DIVBYZERO, 0, 1, ra);
9349     }
9350 }
9351 
9352 uint32_t HELPER(uxtb16)(uint32_t x)
9353 {
9354     uint32_t res;
9355     res = (uint16_t)(uint8_t)x;
9356     res |= (uint32_t)(uint8_t)(x >> 16) << 16;
9357     return res;
9358 }
9359 
9360 int32_t HELPER(sdiv)(CPUARMState *env, int32_t num, int32_t den)
9361 {
9362     if (den == 0) {
9363         handle_possible_div0_trap(env, GETPC());
9364         return 0;
9365     }
9366     if (num == INT_MIN && den == -1) {
9367         return INT_MIN;
9368     }
9369     return num / den;
9370 }
9371 
9372 uint32_t HELPER(udiv)(CPUARMState *env, uint32_t num, uint32_t den)
9373 {
9374     if (den == 0) {
9375         handle_possible_div0_trap(env, GETPC());
9376         return 0;
9377     }
9378     return num / den;
9379 }
9380 
9381 uint32_t HELPER(rbit)(uint32_t x)
9382 {
9383     return revbit32(x);
9384 }
9385 
9386 #ifdef CONFIG_USER_ONLY
9387 
9388 static void switch_mode(CPUARMState *env, int mode)
9389 {
9390     ARMCPU *cpu = env_archcpu(env);
9391 
9392     if (mode != ARM_CPU_MODE_USR) {
9393         cpu_abort(CPU(cpu), "Tried to switch out of user mode\n");
9394     }
9395 }
9396 
9397 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9398                                  uint32_t cur_el, bool secure)
9399 {
9400     return 1;
9401 }
9402 
9403 void aarch64_sync_64_to_32(CPUARMState *env)
9404 {
9405     g_assert_not_reached();
9406 }
9407 
9408 #else
9409 
9410 static void switch_mode(CPUARMState *env, int mode)
9411 {
9412     int old_mode;
9413     int i;
9414 
9415     old_mode = env->uncached_cpsr & CPSR_M;
9416     if (mode == old_mode)
9417         return;
9418 
9419     if (old_mode == ARM_CPU_MODE_FIQ) {
9420         memcpy (env->fiq_regs, env->regs + 8, 5 * sizeof(uint32_t));
9421         memcpy (env->regs + 8, env->usr_regs, 5 * sizeof(uint32_t));
9422     } else if (mode == ARM_CPU_MODE_FIQ) {
9423         memcpy (env->usr_regs, env->regs + 8, 5 * sizeof(uint32_t));
9424         memcpy (env->regs + 8, env->fiq_regs, 5 * sizeof(uint32_t));
9425     }
9426 
9427     i = bank_number(old_mode);
9428     env->banked_r13[i] = env->regs[13];
9429     env->banked_spsr[i] = env->spsr;
9430 
9431     i = bank_number(mode);
9432     env->regs[13] = env->banked_r13[i];
9433     env->spsr = env->banked_spsr[i];
9434 
9435     env->banked_r14[r14_bank_number(old_mode)] = env->regs[14];
9436     env->regs[14] = env->banked_r14[r14_bank_number(mode)];
9437 }
9438 
9439 /* Physical Interrupt Target EL Lookup Table
9440  *
9441  * [ From ARM ARM section G1.13.4 (Table G1-15) ]
9442  *
9443  * The below multi-dimensional table is used for looking up the target
9444  * exception level given numerous condition criteria.  Specifically, the
9445  * target EL is based on SCR and HCR routing controls as well as the
9446  * currently executing EL and secure state.
9447  *
9448  *    Dimensions:
9449  *    target_el_table[2][2][2][2][2][4]
9450  *                    |  |  |  |  |  +--- Current EL
9451  *                    |  |  |  |  +------ Non-secure(0)/Secure(1)
9452  *                    |  |  |  +--------- HCR mask override
9453  *                    |  |  +------------ SCR exec state control
9454  *                    |  +--------------- SCR mask override
9455  *                    +------------------ 32-bit(0)/64-bit(1) EL3
9456  *
9457  *    The table values are as such:
9458  *    0-3 = EL0-EL3
9459  *     -1 = Cannot occur
9460  *
9461  * The ARM ARM target EL table includes entries indicating that an "exception
9462  * is not taken".  The two cases where this is applicable are:
9463  *    1) An exception is taken from EL3 but the SCR does not have the exception
9464  *    routed to EL3.
9465  *    2) An exception is taken from EL2 but the HCR does not have the exception
9466  *    routed to EL2.
9467  * In these two cases, the below table contain a target of EL1.  This value is
9468  * returned as it is expected that the consumer of the table data will check
9469  * for "target EL >= current EL" to ensure the exception is not taken.
9470  *
9471  *            SCR     HCR
9472  *         64  EA     AMO                 From
9473  *        BIT IRQ     IMO      Non-secure         Secure
9474  *        EL3 FIQ  RW FMO   EL0 EL1 EL2 EL3   EL0 EL1 EL2 EL3
9475  */
9476 static const int8_t target_el_table[2][2][2][2][2][4] = {
9477     {{{{/* 0   0   0   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9478        {/* 0   0   0   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},
9479       {{/* 0   0   1   0 */{ 1,  1,  2, -1 },{ 3, -1, -1,  3 },},
9480        {/* 0   0   1   1 */{ 2,  2,  2, -1 },{ 3, -1, -1,  3 },},},},
9481      {{{/* 0   1   0   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9482        {/* 0   1   0   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},
9483       {{/* 0   1   1   0 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},
9484        {/* 0   1   1   1 */{ 3,  3,  3, -1 },{ 3, -1, -1,  3 },},},},},
9485     {{{{/* 1   0   0   0 */{ 1,  1,  2, -1 },{ 1,  1, -1,  1 },},
9486        {/* 1   0   0   1 */{ 2,  2,  2, -1 },{ 2,  2, -1,  1 },},},
9487       {{/* 1   0   1   0 */{ 1,  1,  1, -1 },{ 1,  1,  1,  1 },},
9488        {/* 1   0   1   1 */{ 2,  2,  2, -1 },{ 2,  2,  2,  1 },},},},
9489      {{{/* 1   1   0   0 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},
9490        {/* 1   1   0   1 */{ 3,  3,  3, -1 },{ 3,  3, -1,  3 },},},
9491       {{/* 1   1   1   0 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},
9492        {/* 1   1   1   1 */{ 3,  3,  3, -1 },{ 3,  3,  3,  3 },},},},},
9493 };
9494 
9495 /*
9496  * Determine the target EL for physical exceptions
9497  */
9498 uint32_t arm_phys_excp_target_el(CPUState *cs, uint32_t excp_idx,
9499                                  uint32_t cur_el, bool secure)
9500 {
9501     CPUARMState *env = cs->env_ptr;
9502     bool rw;
9503     bool scr;
9504     bool hcr;
9505     int target_el;
9506     /* Is the highest EL AArch64? */
9507     bool is64 = arm_feature(env, ARM_FEATURE_AARCH64);
9508     uint64_t hcr_el2;
9509 
9510     if (arm_feature(env, ARM_FEATURE_EL3)) {
9511         rw = ((env->cp15.scr_el3 & SCR_RW) == SCR_RW);
9512     } else {
9513         /* Either EL2 is the highest EL (and so the EL2 register width
9514          * is given by is64); or there is no EL2 or EL3, in which case
9515          * the value of 'rw' does not affect the table lookup anyway.
9516          */
9517         rw = is64;
9518     }
9519 
9520     hcr_el2 = arm_hcr_el2_eff(env);
9521     switch (excp_idx) {
9522     case EXCP_IRQ:
9523         scr = ((env->cp15.scr_el3 & SCR_IRQ) == SCR_IRQ);
9524         hcr = hcr_el2 & HCR_IMO;
9525         break;
9526     case EXCP_FIQ:
9527         scr = ((env->cp15.scr_el3 & SCR_FIQ) == SCR_FIQ);
9528         hcr = hcr_el2 & HCR_FMO;
9529         break;
9530     default:
9531         scr = ((env->cp15.scr_el3 & SCR_EA) == SCR_EA);
9532         hcr = hcr_el2 & HCR_AMO;
9533         break;
9534     };
9535 
9536     /*
9537      * For these purposes, TGE and AMO/IMO/FMO both force the
9538      * interrupt to EL2.  Fold TGE into the bit extracted above.
9539      */
9540     hcr |= (hcr_el2 & HCR_TGE) != 0;
9541 
9542     /* Perform a table-lookup for the target EL given the current state */
9543     target_el = target_el_table[is64][scr][rw][hcr][secure][cur_el];
9544 
9545     assert(target_el > 0);
9546 
9547     return target_el;
9548 }
9549 
9550 void arm_log_exception(int idx)
9551 {
9552     if (qemu_loglevel_mask(CPU_LOG_INT)) {
9553         const char *exc = NULL;
9554         static const char * const excnames[] = {
9555             [EXCP_UDEF] = "Undefined Instruction",
9556             [EXCP_SWI] = "SVC",
9557             [EXCP_PREFETCH_ABORT] = "Prefetch Abort",
9558             [EXCP_DATA_ABORT] = "Data Abort",
9559             [EXCP_IRQ] = "IRQ",
9560             [EXCP_FIQ] = "FIQ",
9561             [EXCP_BKPT] = "Breakpoint",
9562             [EXCP_EXCEPTION_EXIT] = "QEMU v7M exception exit",
9563             [EXCP_KERNEL_TRAP] = "QEMU intercept of kernel commpage",
9564             [EXCP_HVC] = "Hypervisor Call",
9565             [EXCP_HYP_TRAP] = "Hypervisor Trap",
9566             [EXCP_SMC] = "Secure Monitor Call",
9567             [EXCP_VIRQ] = "Virtual IRQ",
9568             [EXCP_VFIQ] = "Virtual FIQ",
9569             [EXCP_SEMIHOST] = "Semihosting call",
9570             [EXCP_NOCP] = "v7M NOCP UsageFault",
9571             [EXCP_INVSTATE] = "v7M INVSTATE UsageFault",
9572             [EXCP_STKOF] = "v8M STKOF UsageFault",
9573             [EXCP_LAZYFP] = "v7M exception during lazy FP stacking",
9574             [EXCP_LSERR] = "v8M LSERR UsageFault",
9575             [EXCP_UNALIGNED] = "v7M UNALIGNED UsageFault",
9576             [EXCP_DIVBYZERO] = "v7M DIVBYZERO UsageFault",
9577         };
9578 
9579         if (idx >= 0 && idx < ARRAY_SIZE(excnames)) {
9580             exc = excnames[idx];
9581         }
9582         if (!exc) {
9583             exc = "unknown";
9584         }
9585         qemu_log_mask(CPU_LOG_INT, "Taking exception %d [%s]\n", idx, exc);
9586     }
9587 }
9588 
9589 /*
9590  * Function used to synchronize QEMU's AArch64 register set with AArch32
9591  * register set.  This is necessary when switching between AArch32 and AArch64
9592  * execution state.
9593  */
9594 void aarch64_sync_32_to_64(CPUARMState *env)
9595 {
9596     int i;
9597     uint32_t mode = env->uncached_cpsr & CPSR_M;
9598 
9599     /* We can blanket copy R[0:7] to X[0:7] */
9600     for (i = 0; i < 8; i++) {
9601         env->xregs[i] = env->regs[i];
9602     }
9603 
9604     /*
9605      * Unless we are in FIQ mode, x8-x12 come from the user registers r8-r12.
9606      * Otherwise, they come from the banked user regs.
9607      */
9608     if (mode == ARM_CPU_MODE_FIQ) {
9609         for (i = 8; i < 13; i++) {
9610             env->xregs[i] = env->usr_regs[i - 8];
9611         }
9612     } else {
9613         for (i = 8; i < 13; i++) {
9614             env->xregs[i] = env->regs[i];
9615         }
9616     }
9617 
9618     /*
9619      * Registers x13-x23 are the various mode SP and FP registers. Registers
9620      * r13 and r14 are only copied if we are in that mode, otherwise we copy
9621      * from the mode banked register.
9622      */
9623     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9624         env->xregs[13] = env->regs[13];
9625         env->xregs[14] = env->regs[14];
9626     } else {
9627         env->xregs[13] = env->banked_r13[bank_number(ARM_CPU_MODE_USR)];
9628         /* HYP is an exception in that it is copied from r14 */
9629         if (mode == ARM_CPU_MODE_HYP) {
9630             env->xregs[14] = env->regs[14];
9631         } else {
9632             env->xregs[14] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)];
9633         }
9634     }
9635 
9636     if (mode == ARM_CPU_MODE_HYP) {
9637         env->xregs[15] = env->regs[13];
9638     } else {
9639         env->xregs[15] = env->banked_r13[bank_number(ARM_CPU_MODE_HYP)];
9640     }
9641 
9642     if (mode == ARM_CPU_MODE_IRQ) {
9643         env->xregs[16] = env->regs[14];
9644         env->xregs[17] = env->regs[13];
9645     } else {
9646         env->xregs[16] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)];
9647         env->xregs[17] = env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)];
9648     }
9649 
9650     if (mode == ARM_CPU_MODE_SVC) {
9651         env->xregs[18] = env->regs[14];
9652         env->xregs[19] = env->regs[13];
9653     } else {
9654         env->xregs[18] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)];
9655         env->xregs[19] = env->banked_r13[bank_number(ARM_CPU_MODE_SVC)];
9656     }
9657 
9658     if (mode == ARM_CPU_MODE_ABT) {
9659         env->xregs[20] = env->regs[14];
9660         env->xregs[21] = env->regs[13];
9661     } else {
9662         env->xregs[20] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)];
9663         env->xregs[21] = env->banked_r13[bank_number(ARM_CPU_MODE_ABT)];
9664     }
9665 
9666     if (mode == ARM_CPU_MODE_UND) {
9667         env->xregs[22] = env->regs[14];
9668         env->xregs[23] = env->regs[13];
9669     } else {
9670         env->xregs[22] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)];
9671         env->xregs[23] = env->banked_r13[bank_number(ARM_CPU_MODE_UND)];
9672     }
9673 
9674     /*
9675      * Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9676      * mode, then we can copy from r8-r14.  Otherwise, we copy from the
9677      * FIQ bank for r8-r14.
9678      */
9679     if (mode == ARM_CPU_MODE_FIQ) {
9680         for (i = 24; i < 31; i++) {
9681             env->xregs[i] = env->regs[i - 16];   /* X[24:30] <- R[8:14] */
9682         }
9683     } else {
9684         for (i = 24; i < 29; i++) {
9685             env->xregs[i] = env->fiq_regs[i - 24];
9686         }
9687         env->xregs[29] = env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)];
9688         env->xregs[30] = env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)];
9689     }
9690 
9691     env->pc = env->regs[15];
9692 }
9693 
9694 /*
9695  * Function used to synchronize QEMU's AArch32 register set with AArch64
9696  * register set.  This is necessary when switching between AArch32 and AArch64
9697  * execution state.
9698  */
9699 void aarch64_sync_64_to_32(CPUARMState *env)
9700 {
9701     int i;
9702     uint32_t mode = env->uncached_cpsr & CPSR_M;
9703 
9704     /* We can blanket copy X[0:7] to R[0:7] */
9705     for (i = 0; i < 8; i++) {
9706         env->regs[i] = env->xregs[i];
9707     }
9708 
9709     /*
9710      * Unless we are in FIQ mode, r8-r12 come from the user registers x8-x12.
9711      * Otherwise, we copy x8-x12 into the banked user regs.
9712      */
9713     if (mode == ARM_CPU_MODE_FIQ) {
9714         for (i = 8; i < 13; i++) {
9715             env->usr_regs[i - 8] = env->xregs[i];
9716         }
9717     } else {
9718         for (i = 8; i < 13; i++) {
9719             env->regs[i] = env->xregs[i];
9720         }
9721     }
9722 
9723     /*
9724      * Registers r13 & r14 depend on the current mode.
9725      * If we are in a given mode, we copy the corresponding x registers to r13
9726      * and r14.  Otherwise, we copy the x register to the banked r13 and r14
9727      * for the mode.
9728      */
9729     if (mode == ARM_CPU_MODE_USR || mode == ARM_CPU_MODE_SYS) {
9730         env->regs[13] = env->xregs[13];
9731         env->regs[14] = env->xregs[14];
9732     } else {
9733         env->banked_r13[bank_number(ARM_CPU_MODE_USR)] = env->xregs[13];
9734 
9735         /*
9736          * HYP is an exception in that it does not have its own banked r14 but
9737          * shares the USR r14
9738          */
9739         if (mode == ARM_CPU_MODE_HYP) {
9740             env->regs[14] = env->xregs[14];
9741         } else {
9742             env->banked_r14[r14_bank_number(ARM_CPU_MODE_USR)] = env->xregs[14];
9743         }
9744     }
9745 
9746     if (mode == ARM_CPU_MODE_HYP) {
9747         env->regs[13] = env->xregs[15];
9748     } else {
9749         env->banked_r13[bank_number(ARM_CPU_MODE_HYP)] = env->xregs[15];
9750     }
9751 
9752     if (mode == ARM_CPU_MODE_IRQ) {
9753         env->regs[14] = env->xregs[16];
9754         env->regs[13] = env->xregs[17];
9755     } else {
9756         env->banked_r14[r14_bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[16];
9757         env->banked_r13[bank_number(ARM_CPU_MODE_IRQ)] = env->xregs[17];
9758     }
9759 
9760     if (mode == ARM_CPU_MODE_SVC) {
9761         env->regs[14] = env->xregs[18];
9762         env->regs[13] = env->xregs[19];
9763     } else {
9764         env->banked_r14[r14_bank_number(ARM_CPU_MODE_SVC)] = env->xregs[18];
9765         env->banked_r13[bank_number(ARM_CPU_MODE_SVC)] = env->xregs[19];
9766     }
9767 
9768     if (mode == ARM_CPU_MODE_ABT) {
9769         env->regs[14] = env->xregs[20];
9770         env->regs[13] = env->xregs[21];
9771     } else {
9772         env->banked_r14[r14_bank_number(ARM_CPU_MODE_ABT)] = env->xregs[20];
9773         env->banked_r13[bank_number(ARM_CPU_MODE_ABT)] = env->xregs[21];
9774     }
9775 
9776     if (mode == ARM_CPU_MODE_UND) {
9777         env->regs[14] = env->xregs[22];
9778         env->regs[13] = env->xregs[23];
9779     } else {
9780         env->banked_r14[r14_bank_number(ARM_CPU_MODE_UND)] = env->xregs[22];
9781         env->banked_r13[bank_number(ARM_CPU_MODE_UND)] = env->xregs[23];
9782     }
9783 
9784     /* Registers x24-x30 are mapped to r8-r14 in FIQ mode.  If we are in FIQ
9785      * mode, then we can copy to r8-r14.  Otherwise, we copy to the
9786      * FIQ bank for r8-r14.
9787      */
9788     if (mode == ARM_CPU_MODE_FIQ) {
9789         for (i = 24; i < 31; i++) {
9790             env->regs[i - 16] = env->xregs[i];   /* X[24:30] -> R[8:14] */
9791         }
9792     } else {
9793         for (i = 24; i < 29; i++) {
9794             env->fiq_regs[i - 24] = env->xregs[i];
9795         }
9796         env->banked_r13[bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[29];
9797         env->banked_r14[r14_bank_number(ARM_CPU_MODE_FIQ)] = env->xregs[30];
9798     }
9799 
9800     env->regs[15] = env->pc;
9801 }
9802 
9803 static void take_aarch32_exception(CPUARMState *env, int new_mode,
9804                                    uint32_t mask, uint32_t offset,
9805                                    uint32_t newpc)
9806 {
9807     int new_el;
9808 
9809     /* Change the CPU state so as to actually take the exception. */
9810     switch_mode(env, new_mode);
9811 
9812     /*
9813      * For exceptions taken to AArch32 we must clear the SS bit in both
9814      * PSTATE and in the old-state value we save to SPSR_<mode>, so zero it now.
9815      */
9816     env->pstate &= ~PSTATE_SS;
9817     env->spsr = cpsr_read(env);
9818     /* Clear IT bits.  */
9819     env->condexec_bits = 0;
9820     /* Switch to the new mode, and to the correct instruction set.  */
9821     env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;
9822 
9823     /* This must be after mode switching. */
9824     new_el = arm_current_el(env);
9825 
9826     /* Set new mode endianness */
9827     env->uncached_cpsr &= ~CPSR_E;
9828     if (env->cp15.sctlr_el[new_el] & SCTLR_EE) {
9829         env->uncached_cpsr |= CPSR_E;
9830     }
9831     /* J and IL must always be cleared for exception entry */
9832     env->uncached_cpsr &= ~(CPSR_IL | CPSR_J);
9833     env->daif |= mask;
9834 
9835     if (cpu_isar_feature(aa32_ssbs, env_archcpu(env))) {
9836         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_32) {
9837             env->uncached_cpsr |= CPSR_SSBS;
9838         } else {
9839             env->uncached_cpsr &= ~CPSR_SSBS;
9840         }
9841     }
9842 
9843     if (new_mode == ARM_CPU_MODE_HYP) {
9844         env->thumb = (env->cp15.sctlr_el[2] & SCTLR_TE) != 0;
9845         env->elr_el[2] = env->regs[15];
9846     } else {
9847         /* CPSR.PAN is normally preserved preserved unless...  */
9848         if (cpu_isar_feature(aa32_pan, env_archcpu(env))) {
9849             switch (new_el) {
9850             case 3:
9851                 if (!arm_is_secure_below_el3(env)) {
9852                     /* ... the target is EL3, from non-secure state.  */
9853                     env->uncached_cpsr &= ~CPSR_PAN;
9854                     break;
9855                 }
9856                 /* ... the target is EL3, from secure state ... */
9857                 /* fall through */
9858             case 1:
9859                 /* ... the target is EL1 and SCTLR.SPAN is 0.  */
9860                 if (!(env->cp15.sctlr_el[new_el] & SCTLR_SPAN)) {
9861                     env->uncached_cpsr |= CPSR_PAN;
9862                 }
9863                 break;
9864             }
9865         }
9866         /*
9867          * this is a lie, as there was no c1_sys on V4T/V5, but who cares
9868          * and we should just guard the thumb mode on V4
9869          */
9870         if (arm_feature(env, ARM_FEATURE_V4T)) {
9871             env->thumb =
9872                 (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_TE) != 0;
9873         }
9874         env->regs[14] = env->regs[15] + offset;
9875     }
9876     env->regs[15] = newpc;
9877     arm_rebuild_hflags(env);
9878 }
9879 
9880 static void arm_cpu_do_interrupt_aarch32_hyp(CPUState *cs)
9881 {
9882     /*
9883      * Handle exception entry to Hyp mode; this is sufficiently
9884      * different to entry to other AArch32 modes that we handle it
9885      * separately here.
9886      *
9887      * The vector table entry used is always the 0x14 Hyp mode entry point,
9888      * unless this is an UNDEF/HVC/abort taken from Hyp to Hyp.
9889      * The offset applied to the preferred return address is always zero
9890      * (see DDI0487C.a section G1.12.3).
9891      * PSTATE A/I/F masks are set based only on the SCR.EA/IRQ/FIQ values.
9892      */
9893     uint32_t addr, mask;
9894     ARMCPU *cpu = ARM_CPU(cs);
9895     CPUARMState *env = &cpu->env;
9896 
9897     switch (cs->exception_index) {
9898     case EXCP_UDEF:
9899         addr = 0x04;
9900         break;
9901     case EXCP_SWI:
9902         addr = 0x14;
9903         break;
9904     case EXCP_BKPT:
9905         /* Fall through to prefetch abort.  */
9906     case EXCP_PREFETCH_ABORT:
9907         env->cp15.ifar_s = env->exception.vaddress;
9908         qemu_log_mask(CPU_LOG_INT, "...with HIFAR 0x%x\n",
9909                       (uint32_t)env->exception.vaddress);
9910         addr = 0x0c;
9911         break;
9912     case EXCP_DATA_ABORT:
9913         env->cp15.dfar_s = env->exception.vaddress;
9914         qemu_log_mask(CPU_LOG_INT, "...with HDFAR 0x%x\n",
9915                       (uint32_t)env->exception.vaddress);
9916         addr = 0x10;
9917         break;
9918     case EXCP_IRQ:
9919         addr = 0x18;
9920         break;
9921     case EXCP_FIQ:
9922         addr = 0x1c;
9923         break;
9924     case EXCP_HVC:
9925         addr = 0x08;
9926         break;
9927     case EXCP_HYP_TRAP:
9928         addr = 0x14;
9929         break;
9930     default:
9931         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
9932     }
9933 
9934     if (cs->exception_index != EXCP_IRQ && cs->exception_index != EXCP_FIQ) {
9935         if (!arm_feature(env, ARM_FEATURE_V8)) {
9936             /*
9937              * QEMU syndrome values are v8-style. v7 has the IL bit
9938              * UNK/SBZP for "field not valid" cases, where v8 uses RES1.
9939              * If this is a v7 CPU, squash the IL bit in those cases.
9940              */
9941             if (cs->exception_index == EXCP_PREFETCH_ABORT ||
9942                 (cs->exception_index == EXCP_DATA_ABORT &&
9943                  !(env->exception.syndrome & ARM_EL_ISV)) ||
9944                 syn_get_ec(env->exception.syndrome) == EC_UNCATEGORIZED) {
9945                 env->exception.syndrome &= ~ARM_EL_IL;
9946             }
9947         }
9948         env->cp15.esr_el[2] = env->exception.syndrome;
9949     }
9950 
9951     if (arm_current_el(env) != 2 && addr < 0x14) {
9952         addr = 0x14;
9953     }
9954 
9955     mask = 0;
9956     if (!(env->cp15.scr_el3 & SCR_EA)) {
9957         mask |= CPSR_A;
9958     }
9959     if (!(env->cp15.scr_el3 & SCR_IRQ)) {
9960         mask |= CPSR_I;
9961     }
9962     if (!(env->cp15.scr_el3 & SCR_FIQ)) {
9963         mask |= CPSR_F;
9964     }
9965 
9966     addr += env->cp15.hvbar;
9967 
9968     take_aarch32_exception(env, ARM_CPU_MODE_HYP, mask, 0, addr);
9969 }
9970 
9971 static void arm_cpu_do_interrupt_aarch32(CPUState *cs)
9972 {
9973     ARMCPU *cpu = ARM_CPU(cs);
9974     CPUARMState *env = &cpu->env;
9975     uint32_t addr;
9976     uint32_t mask;
9977     int new_mode;
9978     uint32_t offset;
9979     uint32_t moe;
9980 
9981     /* If this is a debug exception we must update the DBGDSCR.MOE bits */
9982     switch (syn_get_ec(env->exception.syndrome)) {
9983     case EC_BREAKPOINT:
9984     case EC_BREAKPOINT_SAME_EL:
9985         moe = 1;
9986         break;
9987     case EC_WATCHPOINT:
9988     case EC_WATCHPOINT_SAME_EL:
9989         moe = 10;
9990         break;
9991     case EC_AA32_BKPT:
9992         moe = 3;
9993         break;
9994     case EC_VECTORCATCH:
9995         moe = 5;
9996         break;
9997     default:
9998         moe = 0;
9999         break;
10000     }
10001 
10002     if (moe) {
10003         env->cp15.mdscr_el1 = deposit64(env->cp15.mdscr_el1, 2, 4, moe);
10004     }
10005 
10006     if (env->exception.target_el == 2) {
10007         arm_cpu_do_interrupt_aarch32_hyp(cs);
10008         return;
10009     }
10010 
10011     switch (cs->exception_index) {
10012     case EXCP_UDEF:
10013         new_mode = ARM_CPU_MODE_UND;
10014         addr = 0x04;
10015         mask = CPSR_I;
10016         if (env->thumb)
10017             offset = 2;
10018         else
10019             offset = 4;
10020         break;
10021     case EXCP_SWI:
10022         new_mode = ARM_CPU_MODE_SVC;
10023         addr = 0x08;
10024         mask = CPSR_I;
10025         /* The PC already points to the next instruction.  */
10026         offset = 0;
10027         break;
10028     case EXCP_BKPT:
10029         /* Fall through to prefetch abort.  */
10030     case EXCP_PREFETCH_ABORT:
10031         A32_BANKED_CURRENT_REG_SET(env, ifsr, env->exception.fsr);
10032         A32_BANKED_CURRENT_REG_SET(env, ifar, env->exception.vaddress);
10033         qemu_log_mask(CPU_LOG_INT, "...with IFSR 0x%x IFAR 0x%x\n",
10034                       env->exception.fsr, (uint32_t)env->exception.vaddress);
10035         new_mode = ARM_CPU_MODE_ABT;
10036         addr = 0x0c;
10037         mask = CPSR_A | CPSR_I;
10038         offset = 4;
10039         break;
10040     case EXCP_DATA_ABORT:
10041         A32_BANKED_CURRENT_REG_SET(env, dfsr, env->exception.fsr);
10042         A32_BANKED_CURRENT_REG_SET(env, dfar, env->exception.vaddress);
10043         qemu_log_mask(CPU_LOG_INT, "...with DFSR 0x%x DFAR 0x%x\n",
10044                       env->exception.fsr,
10045                       (uint32_t)env->exception.vaddress);
10046         new_mode = ARM_CPU_MODE_ABT;
10047         addr = 0x10;
10048         mask = CPSR_A | CPSR_I;
10049         offset = 8;
10050         break;
10051     case EXCP_IRQ:
10052         new_mode = ARM_CPU_MODE_IRQ;
10053         addr = 0x18;
10054         /* Disable IRQ and imprecise data aborts.  */
10055         mask = CPSR_A | CPSR_I;
10056         offset = 4;
10057         if (env->cp15.scr_el3 & SCR_IRQ) {
10058             /* IRQ routed to monitor mode */
10059             new_mode = ARM_CPU_MODE_MON;
10060             mask |= CPSR_F;
10061         }
10062         break;
10063     case EXCP_FIQ:
10064         new_mode = ARM_CPU_MODE_FIQ;
10065         addr = 0x1c;
10066         /* Disable FIQ, IRQ and imprecise data aborts.  */
10067         mask = CPSR_A | CPSR_I | CPSR_F;
10068         if (env->cp15.scr_el3 & SCR_FIQ) {
10069             /* FIQ routed to monitor mode */
10070             new_mode = ARM_CPU_MODE_MON;
10071         }
10072         offset = 4;
10073         break;
10074     case EXCP_VIRQ:
10075         new_mode = ARM_CPU_MODE_IRQ;
10076         addr = 0x18;
10077         /* Disable IRQ and imprecise data aborts.  */
10078         mask = CPSR_A | CPSR_I;
10079         offset = 4;
10080         break;
10081     case EXCP_VFIQ:
10082         new_mode = ARM_CPU_MODE_FIQ;
10083         addr = 0x1c;
10084         /* Disable FIQ, IRQ and imprecise data aborts.  */
10085         mask = CPSR_A | CPSR_I | CPSR_F;
10086         offset = 4;
10087         break;
10088     case EXCP_SMC:
10089         new_mode = ARM_CPU_MODE_MON;
10090         addr = 0x08;
10091         mask = CPSR_A | CPSR_I | CPSR_F;
10092         offset = 0;
10093         break;
10094     default:
10095         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10096         return; /* Never happens.  Keep compiler happy.  */
10097     }
10098 
10099     if (new_mode == ARM_CPU_MODE_MON) {
10100         addr += env->cp15.mvbar;
10101     } else if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {
10102         /* High vectors. When enabled, base address cannot be remapped. */
10103         addr += 0xffff0000;
10104     } else {
10105         /* ARM v7 architectures provide a vector base address register to remap
10106          * the interrupt vector table.
10107          * This register is only followed in non-monitor mode, and is banked.
10108          * Note: only bits 31:5 are valid.
10109          */
10110         addr += A32_BANKED_CURRENT_REG_GET(env, vbar);
10111     }
10112 
10113     if ((env->uncached_cpsr & CPSR_M) == ARM_CPU_MODE_MON) {
10114         env->cp15.scr_el3 &= ~SCR_NS;
10115     }
10116 
10117     take_aarch32_exception(env, new_mode, mask, offset, addr);
10118 }
10119 
10120 static int aarch64_regnum(CPUARMState *env, int aarch32_reg)
10121 {
10122     /*
10123      * Return the register number of the AArch64 view of the AArch32
10124      * register @aarch32_reg. The CPUARMState CPSR is assumed to still
10125      * be that of the AArch32 mode the exception came from.
10126      */
10127     int mode = env->uncached_cpsr & CPSR_M;
10128 
10129     switch (aarch32_reg) {
10130     case 0 ... 7:
10131         return aarch32_reg;
10132     case 8 ... 12:
10133         return mode == ARM_CPU_MODE_FIQ ? aarch32_reg + 16 : aarch32_reg;
10134     case 13:
10135         switch (mode) {
10136         case ARM_CPU_MODE_USR:
10137         case ARM_CPU_MODE_SYS:
10138             return 13;
10139         case ARM_CPU_MODE_HYP:
10140             return 15;
10141         case ARM_CPU_MODE_IRQ:
10142             return 17;
10143         case ARM_CPU_MODE_SVC:
10144             return 19;
10145         case ARM_CPU_MODE_ABT:
10146             return 21;
10147         case ARM_CPU_MODE_UND:
10148             return 23;
10149         case ARM_CPU_MODE_FIQ:
10150             return 29;
10151         default:
10152             g_assert_not_reached();
10153         }
10154     case 14:
10155         switch (mode) {
10156         case ARM_CPU_MODE_USR:
10157         case ARM_CPU_MODE_SYS:
10158         case ARM_CPU_MODE_HYP:
10159             return 14;
10160         case ARM_CPU_MODE_IRQ:
10161             return 16;
10162         case ARM_CPU_MODE_SVC:
10163             return 18;
10164         case ARM_CPU_MODE_ABT:
10165             return 20;
10166         case ARM_CPU_MODE_UND:
10167             return 22;
10168         case ARM_CPU_MODE_FIQ:
10169             return 30;
10170         default:
10171             g_assert_not_reached();
10172         }
10173     case 15:
10174         return 31;
10175     default:
10176         g_assert_not_reached();
10177     }
10178 }
10179 
10180 static uint32_t cpsr_read_for_spsr_elx(CPUARMState *env)
10181 {
10182     uint32_t ret = cpsr_read(env);
10183 
10184     /* Move DIT to the correct location for SPSR_ELx */
10185     if (ret & CPSR_DIT) {
10186         ret &= ~CPSR_DIT;
10187         ret |= PSTATE_DIT;
10188     }
10189     /* Merge PSTATE.SS into SPSR_ELx */
10190     ret |= env->pstate & PSTATE_SS;
10191 
10192     return ret;
10193 }
10194 
10195 /* Handle exception entry to a target EL which is using AArch64 */
10196 static void arm_cpu_do_interrupt_aarch64(CPUState *cs)
10197 {
10198     ARMCPU *cpu = ARM_CPU(cs);
10199     CPUARMState *env = &cpu->env;
10200     unsigned int new_el = env->exception.target_el;
10201     target_ulong addr = env->cp15.vbar_el[new_el];
10202     unsigned int new_mode = aarch64_pstate_mode(new_el, true);
10203     unsigned int old_mode;
10204     unsigned int cur_el = arm_current_el(env);
10205     int rt;
10206 
10207     /*
10208      * Note that new_el can never be 0.  If cur_el is 0, then
10209      * el0_a64 is is_a64(), else el0_a64 is ignored.
10210      */
10211     aarch64_sve_change_el(env, cur_el, new_el, is_a64(env));
10212 
10213     if (cur_el < new_el) {
10214         /* Entry vector offset depends on whether the implemented EL
10215          * immediately lower than the target level is using AArch32 or AArch64
10216          */
10217         bool is_aa64;
10218         uint64_t hcr;
10219 
10220         switch (new_el) {
10221         case 3:
10222             is_aa64 = (env->cp15.scr_el3 & SCR_RW) != 0;
10223             break;
10224         case 2:
10225             hcr = arm_hcr_el2_eff(env);
10226             if ((hcr & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
10227                 is_aa64 = (hcr & HCR_RW) != 0;
10228                 break;
10229             }
10230             /* fall through */
10231         case 1:
10232             is_aa64 = is_a64(env);
10233             break;
10234         default:
10235             g_assert_not_reached();
10236         }
10237 
10238         if (is_aa64) {
10239             addr += 0x400;
10240         } else {
10241             addr += 0x600;
10242         }
10243     } else if (pstate_read(env) & PSTATE_SP) {
10244         addr += 0x200;
10245     }
10246 
10247     switch (cs->exception_index) {
10248     case EXCP_PREFETCH_ABORT:
10249     case EXCP_DATA_ABORT:
10250         env->cp15.far_el[new_el] = env->exception.vaddress;
10251         qemu_log_mask(CPU_LOG_INT, "...with FAR 0x%" PRIx64 "\n",
10252                       env->cp15.far_el[new_el]);
10253         /* fall through */
10254     case EXCP_BKPT:
10255     case EXCP_UDEF:
10256     case EXCP_SWI:
10257     case EXCP_HVC:
10258     case EXCP_HYP_TRAP:
10259     case EXCP_SMC:
10260         switch (syn_get_ec(env->exception.syndrome)) {
10261         case EC_ADVSIMDFPACCESSTRAP:
10262             /*
10263              * QEMU internal FP/SIMD syndromes from AArch32 include the
10264              * TA and coproc fields which are only exposed if the exception
10265              * is taken to AArch32 Hyp mode. Mask them out to get a valid
10266              * AArch64 format syndrome.
10267              */
10268             env->exception.syndrome &= ~MAKE_64BIT_MASK(0, 20);
10269             break;
10270         case EC_CP14RTTRAP:
10271         case EC_CP15RTTRAP:
10272         case EC_CP14DTTRAP:
10273             /*
10274              * For a trap on AArch32 MRC/MCR/LDC/STC the Rt field is currently
10275              * the raw register field from the insn; when taking this to
10276              * AArch64 we must convert it to the AArch64 view of the register
10277              * number. Notice that we read a 4-bit AArch32 register number and
10278              * write back a 5-bit AArch64 one.
10279              */
10280             rt = extract32(env->exception.syndrome, 5, 4);
10281             rt = aarch64_regnum(env, rt);
10282             env->exception.syndrome = deposit32(env->exception.syndrome,
10283                                                 5, 5, rt);
10284             break;
10285         case EC_CP15RRTTRAP:
10286         case EC_CP14RRTTRAP:
10287             /* Similarly for MRRC/MCRR traps for Rt and Rt2 fields */
10288             rt = extract32(env->exception.syndrome, 5, 4);
10289             rt = aarch64_regnum(env, rt);
10290             env->exception.syndrome = deposit32(env->exception.syndrome,
10291                                                 5, 5, rt);
10292             rt = extract32(env->exception.syndrome, 10, 4);
10293             rt = aarch64_regnum(env, rt);
10294             env->exception.syndrome = deposit32(env->exception.syndrome,
10295                                                 10, 5, rt);
10296             break;
10297         }
10298         env->cp15.esr_el[new_el] = env->exception.syndrome;
10299         break;
10300     case EXCP_IRQ:
10301     case EXCP_VIRQ:
10302         addr += 0x80;
10303         break;
10304     case EXCP_FIQ:
10305     case EXCP_VFIQ:
10306         addr += 0x100;
10307         break;
10308     default:
10309         cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);
10310     }
10311 
10312     if (is_a64(env)) {
10313         old_mode = pstate_read(env);
10314         aarch64_save_sp(env, arm_current_el(env));
10315         env->elr_el[new_el] = env->pc;
10316     } else {
10317         old_mode = cpsr_read_for_spsr_elx(env);
10318         env->elr_el[new_el] = env->regs[15];
10319 
10320         aarch64_sync_32_to_64(env);
10321 
10322         env->condexec_bits = 0;
10323     }
10324     env->banked_spsr[aarch64_banked_spsr_index(new_el)] = old_mode;
10325 
10326     qemu_log_mask(CPU_LOG_INT, "...with ELR 0x%" PRIx64 "\n",
10327                   env->elr_el[new_el]);
10328 
10329     if (cpu_isar_feature(aa64_pan, cpu)) {
10330         /* The value of PSTATE.PAN is normally preserved, except when ... */
10331         new_mode |= old_mode & PSTATE_PAN;
10332         switch (new_el) {
10333         case 2:
10334             /* ... the target is EL2 with HCR_EL2.{E2H,TGE} == '11' ...  */
10335             if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE))
10336                 != (HCR_E2H | HCR_TGE)) {
10337                 break;
10338             }
10339             /* fall through */
10340         case 1:
10341             /* ... the target is EL1 ... */
10342             /* ... and SCTLR_ELx.SPAN == 0, then set to 1.  */
10343             if ((env->cp15.sctlr_el[new_el] & SCTLR_SPAN) == 0) {
10344                 new_mode |= PSTATE_PAN;
10345             }
10346             break;
10347         }
10348     }
10349     if (cpu_isar_feature(aa64_mte, cpu)) {
10350         new_mode |= PSTATE_TCO;
10351     }
10352 
10353     if (cpu_isar_feature(aa64_ssbs, cpu)) {
10354         if (env->cp15.sctlr_el[new_el] & SCTLR_DSSBS_64) {
10355             new_mode |= PSTATE_SSBS;
10356         } else {
10357             new_mode &= ~PSTATE_SSBS;
10358         }
10359     }
10360 
10361     pstate_write(env, PSTATE_DAIF | new_mode);
10362     env->aarch64 = 1;
10363     aarch64_restore_sp(env, new_el);
10364     helper_rebuild_hflags_a64(env, new_el);
10365 
10366     env->pc = addr;
10367 
10368     qemu_log_mask(CPU_LOG_INT, "...to EL%d PC 0x%" PRIx64 " PSTATE 0x%x\n",
10369                   new_el, env->pc, pstate_read(env));
10370 }
10371 
10372 /*
10373  * Do semihosting call and set the appropriate return value. All the
10374  * permission and validity checks have been done at translate time.
10375  *
10376  * We only see semihosting exceptions in TCG only as they are not
10377  * trapped to the hypervisor in KVM.
10378  */
10379 #ifdef CONFIG_TCG
10380 static void handle_semihosting(CPUState *cs)
10381 {
10382     ARMCPU *cpu = ARM_CPU(cs);
10383     CPUARMState *env = &cpu->env;
10384 
10385     if (is_a64(env)) {
10386         qemu_log_mask(CPU_LOG_INT,
10387                       "...handling as semihosting call 0x%" PRIx64 "\n",
10388                       env->xregs[0]);
10389         env->xregs[0] = do_common_semihosting(cs);
10390         env->pc += 4;
10391     } else {
10392         qemu_log_mask(CPU_LOG_INT,
10393                       "...handling as semihosting call 0x%x\n",
10394                       env->regs[0]);
10395         env->regs[0] = do_common_semihosting(cs);
10396         env->regs[15] += env->thumb ? 2 : 4;
10397     }
10398 }
10399 #endif
10400 
10401 /* Handle a CPU exception for A and R profile CPUs.
10402  * Do any appropriate logging, handle PSCI calls, and then hand off
10403  * to the AArch64-entry or AArch32-entry function depending on the
10404  * target exception level's register width.
10405  *
10406  * Note: this is used for both TCG (as the do_interrupt tcg op),
10407  *       and KVM to re-inject guest debug exceptions, and to
10408  *       inject a Synchronous-External-Abort.
10409  */
10410 void arm_cpu_do_interrupt(CPUState *cs)
10411 {
10412     ARMCPU *cpu = ARM_CPU(cs);
10413     CPUARMState *env = &cpu->env;
10414     unsigned int new_el = env->exception.target_el;
10415 
10416     assert(!arm_feature(env, ARM_FEATURE_M));
10417 
10418     arm_log_exception(cs->exception_index);
10419     qemu_log_mask(CPU_LOG_INT, "...from EL%d to EL%d\n", arm_current_el(env),
10420                   new_el);
10421     if (qemu_loglevel_mask(CPU_LOG_INT)
10422         && !excp_is_internal(cs->exception_index)) {
10423         qemu_log_mask(CPU_LOG_INT, "...with ESR 0x%x/0x%" PRIx32 "\n",
10424                       syn_get_ec(env->exception.syndrome),
10425                       env->exception.syndrome);
10426     }
10427 
10428     if (arm_is_psci_call(cpu, cs->exception_index)) {
10429         arm_handle_psci_call(cpu);
10430         qemu_log_mask(CPU_LOG_INT, "...handled as PSCI call\n");
10431         return;
10432     }
10433 
10434     /*
10435      * Semihosting semantics depend on the register width of the code
10436      * that caused the exception, not the target exception level, so
10437      * must be handled here.
10438      */
10439 #ifdef CONFIG_TCG
10440     if (cs->exception_index == EXCP_SEMIHOST) {
10441         handle_semihosting(cs);
10442         return;
10443     }
10444 #endif
10445 
10446     /* Hooks may change global state so BQL should be held, also the
10447      * BQL needs to be held for any modification of
10448      * cs->interrupt_request.
10449      */
10450     g_assert(qemu_mutex_iothread_locked());
10451 
10452     arm_call_pre_el_change_hook(cpu);
10453 
10454     assert(!excp_is_internal(cs->exception_index));
10455     if (arm_el_is_aa64(env, new_el)) {
10456         arm_cpu_do_interrupt_aarch64(cs);
10457     } else {
10458         arm_cpu_do_interrupt_aarch32(cs);
10459     }
10460 
10461     arm_call_el_change_hook(cpu);
10462 
10463     if (!kvm_enabled()) {
10464         cs->interrupt_request |= CPU_INTERRUPT_EXITTB;
10465     }
10466 }
10467 #endif /* !CONFIG_USER_ONLY */
10468 
10469 uint64_t arm_sctlr(CPUARMState *env, int el)
10470 {
10471     /* Only EL0 needs to be adjusted for EL1&0 or EL2&0. */
10472     if (el == 0) {
10473         ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, 0);
10474         el = (mmu_idx == ARMMMUIdx_E20_0 || mmu_idx == ARMMMUIdx_SE20_0)
10475              ? 2 : 1;
10476     }
10477     return env->cp15.sctlr_el[el];
10478 }
10479 
10480 /* Return the SCTLR value which controls this address translation regime */
10481 static inline uint64_t regime_sctlr(CPUARMState *env, ARMMMUIdx mmu_idx)
10482 {
10483     return env->cp15.sctlr_el[regime_el(env, mmu_idx)];
10484 }
10485 
10486 #ifndef CONFIG_USER_ONLY
10487 
10488 /* Return true if the specified stage of address translation is disabled */
10489 static inline bool regime_translation_disabled(CPUARMState *env,
10490                                                ARMMMUIdx mmu_idx)
10491 {
10492     uint64_t hcr_el2;
10493 
10494     if (arm_feature(env, ARM_FEATURE_M)) {
10495         switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &
10496                 (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
10497         case R_V7M_MPU_CTRL_ENABLE_MASK:
10498             /* Enabled, but not for HardFault and NMI */
10499             return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
10500         case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
10501             /* Enabled for all cases */
10502             return false;
10503         case 0:
10504         default:
10505             /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
10506              * we warned about that in armv7m_nvic.c when the guest set it.
10507              */
10508             return true;
10509         }
10510     }
10511 
10512     hcr_el2 = arm_hcr_el2_eff(env);
10513 
10514     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
10515         /* HCR.DC means HCR.VM behaves as 1 */
10516         return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
10517     }
10518 
10519     if (hcr_el2 & HCR_TGE) {
10520         /* TGE means that NS EL0/1 act as if SCTLR_EL1.M is zero */
10521         if (!regime_is_secure(env, mmu_idx) && regime_el(env, mmu_idx) == 1) {
10522             return true;
10523         }
10524     }
10525 
10526     if ((hcr_el2 & HCR_DC) && arm_mmu_idx_is_stage1_of_2(mmu_idx)) {
10527         /* HCR.DC means SCTLR_EL1.M behaves as 0 */
10528         return true;
10529     }
10530 
10531     return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
10532 }
10533 
10534 static inline bool regime_translation_big_endian(CPUARMState *env,
10535                                                  ARMMMUIdx mmu_idx)
10536 {
10537     return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
10538 }
10539 
10540 /* Return the TTBR associated with this translation regime */
10541 static inline uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx,
10542                                    int ttbrn)
10543 {
10544     if (mmu_idx == ARMMMUIdx_Stage2) {
10545         return env->cp15.vttbr_el2;
10546     }
10547     if (mmu_idx == ARMMMUIdx_Stage2_S) {
10548         return env->cp15.vsttbr_el2;
10549     }
10550     if (ttbrn == 0) {
10551         return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
10552     } else {
10553         return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
10554     }
10555 }
10556 
10557 #endif /* !CONFIG_USER_ONLY */
10558 
10559 /* Convert a possible stage1+2 MMU index into the appropriate
10560  * stage 1 MMU index
10561  */
10562 static inline ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
10563 {
10564     switch (mmu_idx) {
10565     case ARMMMUIdx_SE10_0:
10566         return ARMMMUIdx_Stage1_SE0;
10567     case ARMMMUIdx_SE10_1:
10568         return ARMMMUIdx_Stage1_SE1;
10569     case ARMMMUIdx_SE10_1_PAN:
10570         return ARMMMUIdx_Stage1_SE1_PAN;
10571     case ARMMMUIdx_E10_0:
10572         return ARMMMUIdx_Stage1_E0;
10573     case ARMMMUIdx_E10_1:
10574         return ARMMMUIdx_Stage1_E1;
10575     case ARMMMUIdx_E10_1_PAN:
10576         return ARMMMUIdx_Stage1_E1_PAN;
10577     default:
10578         return mmu_idx;
10579     }
10580 }
10581 
10582 /* Return true if the translation regime is using LPAE format page tables */
10583 static inline bool regime_using_lpae_format(CPUARMState *env,
10584                                             ARMMMUIdx mmu_idx)
10585 {
10586     int el = regime_el(env, mmu_idx);
10587     if (el == 2 || arm_el_is_aa64(env, el)) {
10588         return true;
10589     }
10590     if (arm_feature(env, ARM_FEATURE_LPAE)
10591         && (regime_tcr(env, mmu_idx)->raw_tcr & TTBCR_EAE)) {
10592         return true;
10593     }
10594     return false;
10595 }
10596 
10597 /* Returns true if the stage 1 translation regime is using LPAE format page
10598  * tables. Used when raising alignment exceptions, whose FSR changes depending
10599  * on whether the long or short descriptor format is in use. */
10600 bool arm_s1_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)
10601 {
10602     mmu_idx = stage_1_mmu_idx(mmu_idx);
10603 
10604     return regime_using_lpae_format(env, mmu_idx);
10605 }
10606 
10607 #ifndef CONFIG_USER_ONLY
10608 static inline bool regime_is_user(CPUARMState *env, ARMMMUIdx mmu_idx)
10609 {
10610     switch (mmu_idx) {
10611     case ARMMMUIdx_SE10_0:
10612     case ARMMMUIdx_E20_0:
10613     case ARMMMUIdx_SE20_0:
10614     case ARMMMUIdx_Stage1_E0:
10615     case ARMMMUIdx_Stage1_SE0:
10616     case ARMMMUIdx_MUser:
10617     case ARMMMUIdx_MSUser:
10618     case ARMMMUIdx_MUserNegPri:
10619     case ARMMMUIdx_MSUserNegPri:
10620         return true;
10621     default:
10622         return false;
10623     case ARMMMUIdx_E10_0:
10624     case ARMMMUIdx_E10_1:
10625     case ARMMMUIdx_E10_1_PAN:
10626         g_assert_not_reached();
10627     }
10628 }
10629 
10630 /* Translate section/page access permissions to page
10631  * R/W protection flags
10632  *
10633  * @env:         CPUARMState
10634  * @mmu_idx:     MMU index indicating required translation regime
10635  * @ap:          The 3-bit access permissions (AP[2:0])
10636  * @domain_prot: The 2-bit domain access permissions
10637  */
10638 static inline int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
10639                                 int ap, int domain_prot)
10640 {
10641     bool is_user = regime_is_user(env, mmu_idx);
10642 
10643     if (domain_prot == 3) {
10644         return PAGE_READ | PAGE_WRITE;
10645     }
10646 
10647     switch (ap) {
10648     case 0:
10649         if (arm_feature(env, ARM_FEATURE_V7)) {
10650             return 0;
10651         }
10652         switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
10653         case SCTLR_S:
10654             return is_user ? 0 : PAGE_READ;
10655         case SCTLR_R:
10656             return PAGE_READ;
10657         default:
10658             return 0;
10659         }
10660     case 1:
10661         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10662     case 2:
10663         if (is_user) {
10664             return PAGE_READ;
10665         } else {
10666             return PAGE_READ | PAGE_WRITE;
10667         }
10668     case 3:
10669         return PAGE_READ | PAGE_WRITE;
10670     case 4: /* Reserved.  */
10671         return 0;
10672     case 5:
10673         return is_user ? 0 : PAGE_READ;
10674     case 6:
10675         return PAGE_READ;
10676     case 7:
10677         if (!arm_feature(env, ARM_FEATURE_V6K)) {
10678             return 0;
10679         }
10680         return PAGE_READ;
10681     default:
10682         g_assert_not_reached();
10683     }
10684 }
10685 
10686 /* Translate section/page access permissions to page
10687  * R/W protection flags.
10688  *
10689  * @ap:      The 2-bit simple AP (AP[2:1])
10690  * @is_user: TRUE if accessing from PL0
10691  */
10692 static inline int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
10693 {
10694     switch (ap) {
10695     case 0:
10696         return is_user ? 0 : PAGE_READ | PAGE_WRITE;
10697     case 1:
10698         return PAGE_READ | PAGE_WRITE;
10699     case 2:
10700         return is_user ? 0 : PAGE_READ;
10701     case 3:
10702         return PAGE_READ;
10703     default:
10704         g_assert_not_reached();
10705     }
10706 }
10707 
10708 static inline int
10709 simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
10710 {
10711     return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
10712 }
10713 
10714 /* Translate S2 section/page access permissions to protection flags
10715  *
10716  * @env:     CPUARMState
10717  * @s2ap:    The 2-bit stage2 access permissions (S2AP)
10718  * @xn:      XN (execute-never) bits
10719  * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
10720  */
10721 static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
10722 {
10723     int prot = 0;
10724 
10725     if (s2ap & 1) {
10726         prot |= PAGE_READ;
10727     }
10728     if (s2ap & 2) {
10729         prot |= PAGE_WRITE;
10730     }
10731 
10732     if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
10733         switch (xn) {
10734         case 0:
10735             prot |= PAGE_EXEC;
10736             break;
10737         case 1:
10738             if (s1_is_el0) {
10739                 prot |= PAGE_EXEC;
10740             }
10741             break;
10742         case 2:
10743             break;
10744         case 3:
10745             if (!s1_is_el0) {
10746                 prot |= PAGE_EXEC;
10747             }
10748             break;
10749         default:
10750             g_assert_not_reached();
10751         }
10752     } else {
10753         if (!extract32(xn, 1, 1)) {
10754             if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
10755                 prot |= PAGE_EXEC;
10756             }
10757         }
10758     }
10759     return prot;
10760 }
10761 
10762 /* Translate section/page access permissions to protection flags
10763  *
10764  * @env:     CPUARMState
10765  * @mmu_idx: MMU index indicating required translation regime
10766  * @is_aa64: TRUE if AArch64
10767  * @ap:      The 2-bit simple AP (AP[2:1])
10768  * @ns:      NS (non-secure) bit
10769  * @xn:      XN (execute-never) bit
10770  * @pxn:     PXN (privileged execute-never) bit
10771  */
10772 static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
10773                       int ap, int ns, int xn, int pxn)
10774 {
10775     bool is_user = regime_is_user(env, mmu_idx);
10776     int prot_rw, user_rw;
10777     bool have_wxn;
10778     int wxn = 0;
10779 
10780     assert(mmu_idx != ARMMMUIdx_Stage2);
10781     assert(mmu_idx != ARMMMUIdx_Stage2_S);
10782 
10783     user_rw = simple_ap_to_rw_prot_is_user(ap, true);
10784     if (is_user) {
10785         prot_rw = user_rw;
10786     } else {
10787         if (user_rw && regime_is_pan(env, mmu_idx)) {
10788             /* PAN forbids data accesses but doesn't affect insn fetch */
10789             prot_rw = 0;
10790         } else {
10791             prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
10792         }
10793     }
10794 
10795     if (ns && arm_is_secure(env) && (env->cp15.scr_el3 & SCR_SIF)) {
10796         return prot_rw;
10797     }
10798 
10799     /* TODO have_wxn should be replaced with
10800      *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
10801      * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
10802      * compatible processors have EL2, which is required for [U]WXN.
10803      */
10804     have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
10805 
10806     if (have_wxn) {
10807         wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
10808     }
10809 
10810     if (is_aa64) {
10811         if (regime_has_2_ranges(mmu_idx) && !is_user) {
10812             xn = pxn || (user_rw & PAGE_WRITE);
10813         }
10814     } else if (arm_feature(env, ARM_FEATURE_V7)) {
10815         switch (regime_el(env, mmu_idx)) {
10816         case 1:
10817         case 3:
10818             if (is_user) {
10819                 xn = xn || !(user_rw & PAGE_READ);
10820             } else {
10821                 int uwxn = 0;
10822                 if (have_wxn) {
10823                     uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
10824                 }
10825                 xn = xn || !(prot_rw & PAGE_READ) || pxn ||
10826                      (uwxn && (user_rw & PAGE_WRITE));
10827             }
10828             break;
10829         case 2:
10830             break;
10831         }
10832     } else {
10833         xn = wxn = 0;
10834     }
10835 
10836     if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
10837         return prot_rw;
10838     }
10839     return prot_rw | PAGE_EXEC;
10840 }
10841 
10842 static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
10843                                      uint32_t *table, uint32_t address)
10844 {
10845     /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
10846     TCR *tcr = regime_tcr(env, mmu_idx);
10847 
10848     if (address & tcr->mask) {
10849         if (tcr->raw_tcr & TTBCR_PD1) {
10850             /* Translation table walk disabled for TTBR1 */
10851             return false;
10852         }
10853         *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
10854     } else {
10855         if (tcr->raw_tcr & TTBCR_PD0) {
10856             /* Translation table walk disabled for TTBR0 */
10857             return false;
10858         }
10859         *table = regime_ttbr(env, mmu_idx, 0) & tcr->base_mask;
10860     }
10861     *table |= (address >> 18) & 0x3ffc;
10862     return true;
10863 }
10864 
10865 /* Translate a S1 pagetable walk through S2 if needed.  */
10866 static hwaddr S1_ptw_translate(CPUARMState *env, ARMMMUIdx mmu_idx,
10867                                hwaddr addr, bool *is_secure,
10868                                ARMMMUFaultInfo *fi)
10869 {
10870     if (arm_mmu_idx_is_stage1_of_2(mmu_idx) &&
10871         !regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
10872         target_ulong s2size;
10873         hwaddr s2pa;
10874         int s2prot;
10875         int ret;
10876         ARMMMUIdx s2_mmu_idx = *is_secure ? ARMMMUIdx_Stage2_S
10877                                           : ARMMMUIdx_Stage2;
10878         ARMCacheAttrs cacheattrs = {};
10879         MemTxAttrs txattrs = {};
10880 
10881         ret = get_phys_addr_lpae(env, addr, MMU_DATA_LOAD, s2_mmu_idx, false,
10882                                  &s2pa, &txattrs, &s2prot, &s2size, fi,
10883                                  &cacheattrs);
10884         if (ret) {
10885             assert(fi->type != ARMFault_None);
10886             fi->s2addr = addr;
10887             fi->stage2 = true;
10888             fi->s1ptw = true;
10889             fi->s1ns = !*is_secure;
10890             return ~0;
10891         }
10892         if ((arm_hcr_el2_eff(env) & HCR_PTW) &&
10893             (cacheattrs.attrs & 0xf0) == 0) {
10894             /*
10895              * PTW set and S1 walk touched S2 Device memory:
10896              * generate Permission fault.
10897              */
10898             fi->type = ARMFault_Permission;
10899             fi->s2addr = addr;
10900             fi->stage2 = true;
10901             fi->s1ptw = true;
10902             fi->s1ns = !*is_secure;
10903             return ~0;
10904         }
10905 
10906         if (arm_is_secure_below_el3(env)) {
10907             /* Check if page table walk is to secure or non-secure PA space. */
10908             if (*is_secure) {
10909                 *is_secure = !(env->cp15.vstcr_el2.raw_tcr & VSTCR_SW);
10910             } else {
10911                 *is_secure = !(env->cp15.vtcr_el2.raw_tcr & VTCR_NSW);
10912             }
10913         } else {
10914             assert(!*is_secure);
10915         }
10916 
10917         addr = s2pa;
10918     }
10919     return addr;
10920 }
10921 
10922 /* All loads done in the course of a page table walk go through here. */
10923 static uint32_t arm_ldl_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10924                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10925 {
10926     ARMCPU *cpu = ARM_CPU(cs);
10927     CPUARMState *env = &cpu->env;
10928     MemTxAttrs attrs = {};
10929     MemTxResult result = MEMTX_OK;
10930     AddressSpace *as;
10931     uint32_t data;
10932 
10933     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10934     attrs.secure = is_secure;
10935     as = arm_addressspace(cs, attrs);
10936     if (fi->s1ptw) {
10937         return 0;
10938     }
10939     if (regime_translation_big_endian(env, mmu_idx)) {
10940         data = address_space_ldl_be(as, addr, attrs, &result);
10941     } else {
10942         data = address_space_ldl_le(as, addr, attrs, &result);
10943     }
10944     if (result == MEMTX_OK) {
10945         return data;
10946     }
10947     fi->type = ARMFault_SyncExternalOnWalk;
10948     fi->ea = arm_extabort_type(result);
10949     return 0;
10950 }
10951 
10952 static uint64_t arm_ldq_ptw(CPUState *cs, hwaddr addr, bool is_secure,
10953                             ARMMMUIdx mmu_idx, ARMMMUFaultInfo *fi)
10954 {
10955     ARMCPU *cpu = ARM_CPU(cs);
10956     CPUARMState *env = &cpu->env;
10957     MemTxAttrs attrs = {};
10958     MemTxResult result = MEMTX_OK;
10959     AddressSpace *as;
10960     uint64_t data;
10961 
10962     addr = S1_ptw_translate(env, mmu_idx, addr, &is_secure, fi);
10963     attrs.secure = is_secure;
10964     as = arm_addressspace(cs, attrs);
10965     if (fi->s1ptw) {
10966         return 0;
10967     }
10968     if (regime_translation_big_endian(env, mmu_idx)) {
10969         data = address_space_ldq_be(as, addr, attrs, &result);
10970     } else {
10971         data = address_space_ldq_le(as, addr, attrs, &result);
10972     }
10973     if (result == MEMTX_OK) {
10974         return data;
10975     }
10976     fi->type = ARMFault_SyncExternalOnWalk;
10977     fi->ea = arm_extabort_type(result);
10978     return 0;
10979 }
10980 
10981 static bool get_phys_addr_v5(CPUARMState *env, uint32_t address,
10982                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
10983                              hwaddr *phys_ptr, int *prot,
10984                              target_ulong *page_size,
10985                              ARMMMUFaultInfo *fi)
10986 {
10987     CPUState *cs = env_cpu(env);
10988     int level = 1;
10989     uint32_t table;
10990     uint32_t desc;
10991     int type;
10992     int ap;
10993     int domain = 0;
10994     int domain_prot;
10995     hwaddr phys_addr;
10996     uint32_t dacr;
10997 
10998     /* Pagetable walk.  */
10999     /* Lookup l1 descriptor.  */
11000     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
11001         /* Section translation fault if page walk is disabled by PD0 or PD1 */
11002         fi->type = ARMFault_Translation;
11003         goto do_fault;
11004     }
11005     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11006                        mmu_idx, fi);
11007     if (fi->type != ARMFault_None) {
11008         goto do_fault;
11009     }
11010     type = (desc & 3);
11011     domain = (desc >> 5) & 0x0f;
11012     if (regime_el(env, mmu_idx) == 1) {
11013         dacr = env->cp15.dacr_ns;
11014     } else {
11015         dacr = env->cp15.dacr_s;
11016     }
11017     domain_prot = (dacr >> (domain * 2)) & 3;
11018     if (type == 0) {
11019         /* Section translation fault.  */
11020         fi->type = ARMFault_Translation;
11021         goto do_fault;
11022     }
11023     if (type != 2) {
11024         level = 2;
11025     }
11026     if (domain_prot == 0 || domain_prot == 2) {
11027         fi->type = ARMFault_Domain;
11028         goto do_fault;
11029     }
11030     if (type == 2) {
11031         /* 1Mb section.  */
11032         phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
11033         ap = (desc >> 10) & 3;
11034         *page_size = 1024 * 1024;
11035     } else {
11036         /* Lookup l2 entry.  */
11037         if (type == 1) {
11038             /* Coarse pagetable.  */
11039             table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
11040         } else {
11041             /* Fine pagetable.  */
11042             table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
11043         }
11044         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11045                            mmu_idx, fi);
11046         if (fi->type != ARMFault_None) {
11047             goto do_fault;
11048         }
11049         switch (desc & 3) {
11050         case 0: /* Page translation fault.  */
11051             fi->type = ARMFault_Translation;
11052             goto do_fault;
11053         case 1: /* 64k page.  */
11054             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11055             ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
11056             *page_size = 0x10000;
11057             break;
11058         case 2: /* 4k page.  */
11059             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11060             ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
11061             *page_size = 0x1000;
11062             break;
11063         case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
11064             if (type == 1) {
11065                 /* ARMv6/XScale extended small page format */
11066                 if (arm_feature(env, ARM_FEATURE_XSCALE)
11067                     || arm_feature(env, ARM_FEATURE_V6)) {
11068                     phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11069                     *page_size = 0x1000;
11070                 } else {
11071                     /* UNPREDICTABLE in ARMv5; we choose to take a
11072                      * page translation fault.
11073                      */
11074                     fi->type = ARMFault_Translation;
11075                     goto do_fault;
11076                 }
11077             } else {
11078                 phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
11079                 *page_size = 0x400;
11080             }
11081             ap = (desc >> 4) & 3;
11082             break;
11083         default:
11084             /* Never happens, but compiler isn't smart enough to tell.  */
11085             abort();
11086         }
11087     }
11088     *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11089     *prot |= *prot ? PAGE_EXEC : 0;
11090     if (!(*prot & (1 << access_type))) {
11091         /* Access permission fault.  */
11092         fi->type = ARMFault_Permission;
11093         goto do_fault;
11094     }
11095     *phys_ptr = phys_addr;
11096     return false;
11097 do_fault:
11098     fi->domain = domain;
11099     fi->level = level;
11100     return true;
11101 }
11102 
11103 static bool get_phys_addr_v6(CPUARMState *env, uint32_t address,
11104                              MMUAccessType access_type, ARMMMUIdx mmu_idx,
11105                              hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
11106                              target_ulong *page_size, ARMMMUFaultInfo *fi)
11107 {
11108     CPUState *cs = env_cpu(env);
11109     ARMCPU *cpu = env_archcpu(env);
11110     int level = 1;
11111     uint32_t table;
11112     uint32_t desc;
11113     uint32_t xn;
11114     uint32_t pxn = 0;
11115     int type;
11116     int ap;
11117     int domain = 0;
11118     int domain_prot;
11119     hwaddr phys_addr;
11120     uint32_t dacr;
11121     bool ns;
11122 
11123     /* Pagetable walk.  */
11124     /* Lookup l1 descriptor.  */
11125     if (!get_level1_table_address(env, mmu_idx, &table, address)) {
11126         /* Section translation fault if page walk is disabled by PD0 or PD1 */
11127         fi->type = ARMFault_Translation;
11128         goto do_fault;
11129     }
11130     desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11131                        mmu_idx, fi);
11132     if (fi->type != ARMFault_None) {
11133         goto do_fault;
11134     }
11135     type = (desc & 3);
11136     if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
11137         /* Section translation fault, or attempt to use the encoding
11138          * which is Reserved on implementations without PXN.
11139          */
11140         fi->type = ARMFault_Translation;
11141         goto do_fault;
11142     }
11143     if ((type == 1) || !(desc & (1 << 18))) {
11144         /* Page or Section.  */
11145         domain = (desc >> 5) & 0x0f;
11146     }
11147     if (regime_el(env, mmu_idx) == 1) {
11148         dacr = env->cp15.dacr_ns;
11149     } else {
11150         dacr = env->cp15.dacr_s;
11151     }
11152     if (type == 1) {
11153         level = 2;
11154     }
11155     domain_prot = (dacr >> (domain * 2)) & 3;
11156     if (domain_prot == 0 || domain_prot == 2) {
11157         /* Section or Page domain fault */
11158         fi->type = ARMFault_Domain;
11159         goto do_fault;
11160     }
11161     if (type != 1) {
11162         if (desc & (1 << 18)) {
11163             /* Supersection.  */
11164             phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
11165             phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
11166             phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
11167             *page_size = 0x1000000;
11168         } else {
11169             /* Section.  */
11170             phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
11171             *page_size = 0x100000;
11172         }
11173         ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
11174         xn = desc & (1 << 4);
11175         pxn = desc & 1;
11176         ns = extract32(desc, 19, 1);
11177     } else {
11178         if (cpu_isar_feature(aa32_pxn, cpu)) {
11179             pxn = (desc >> 2) & 1;
11180         }
11181         ns = extract32(desc, 3, 1);
11182         /* Lookup l2 entry.  */
11183         table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
11184         desc = arm_ldl_ptw(cs, table, regime_is_secure(env, mmu_idx),
11185                            mmu_idx, fi);
11186         if (fi->type != ARMFault_None) {
11187             goto do_fault;
11188         }
11189         ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
11190         switch (desc & 3) {
11191         case 0: /* Page translation fault.  */
11192             fi->type = ARMFault_Translation;
11193             goto do_fault;
11194         case 1: /* 64k page.  */
11195             phys_addr = (desc & 0xffff0000) | (address & 0xffff);
11196             xn = desc & (1 << 15);
11197             *page_size = 0x10000;
11198             break;
11199         case 2: case 3: /* 4k page.  */
11200             phys_addr = (desc & 0xfffff000) | (address & 0xfff);
11201             xn = desc & 1;
11202             *page_size = 0x1000;
11203             break;
11204         default:
11205             /* Never happens, but compiler isn't smart enough to tell.  */
11206             abort();
11207         }
11208     }
11209     if (domain_prot == 3) {
11210         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11211     } else {
11212         if (pxn && !regime_is_user(env, mmu_idx)) {
11213             xn = 1;
11214         }
11215         if (xn && access_type == MMU_INST_FETCH) {
11216             fi->type = ARMFault_Permission;
11217             goto do_fault;
11218         }
11219 
11220         if (arm_feature(env, ARM_FEATURE_V6K) &&
11221                 (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
11222             /* The simplified model uses AP[0] as an access control bit.  */
11223             if ((ap & 1) == 0) {
11224                 /* Access flag fault.  */
11225                 fi->type = ARMFault_AccessFlag;
11226                 goto do_fault;
11227             }
11228             *prot = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
11229         } else {
11230             *prot = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
11231         }
11232         if (*prot && !xn) {
11233             *prot |= PAGE_EXEC;
11234         }
11235         if (!(*prot & (1 << access_type))) {
11236             /* Access permission fault.  */
11237             fi->type = ARMFault_Permission;
11238             goto do_fault;
11239         }
11240     }
11241     if (ns) {
11242         /* The NS bit will (as required by the architecture) have no effect if
11243          * the CPU doesn't support TZ or this is a non-secure translation
11244          * regime, because the attribute will already be non-secure.
11245          */
11246         attrs->secure = false;
11247     }
11248     *phys_ptr = phys_addr;
11249     return false;
11250 do_fault:
11251     fi->domain = domain;
11252     fi->level = level;
11253     return true;
11254 }
11255 
11256 /*
11257  * check_s2_mmu_setup
11258  * @cpu:        ARMCPU
11259  * @is_aa64:    True if the translation regime is in AArch64 state
11260  * @startlevel: Suggested starting level
11261  * @inputsize:  Bitsize of IPAs
11262  * @stride:     Page-table stride (See the ARM ARM)
11263  *
11264  * Returns true if the suggested S2 translation parameters are OK and
11265  * false otherwise.
11266  */
11267 static bool check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, int level,
11268                                int inputsize, int stride)
11269 {
11270     const int grainsize = stride + 3;
11271     int startsizecheck;
11272 
11273     /* Negative levels are never allowed.  */
11274     if (level < 0) {
11275         return false;
11276     }
11277 
11278     startsizecheck = inputsize - ((3 - level) * stride + grainsize);
11279     if (startsizecheck < 1 || startsizecheck > stride + 4) {
11280         return false;
11281     }
11282 
11283     if (is_aa64) {
11284         CPUARMState *env = &cpu->env;
11285         unsigned int pamax = arm_pamax(cpu);
11286 
11287         switch (stride) {
11288         case 13: /* 64KB Pages.  */
11289             if (level == 0 || (level == 1 && pamax <= 42)) {
11290                 return false;
11291             }
11292             break;
11293         case 11: /* 16KB Pages.  */
11294             if (level == 0 || (level == 1 && pamax <= 40)) {
11295                 return false;
11296             }
11297             break;
11298         case 9: /* 4KB Pages.  */
11299             if (level == 0 && pamax <= 42) {
11300                 return false;
11301             }
11302             break;
11303         default:
11304             g_assert_not_reached();
11305         }
11306 
11307         /* Inputsize checks.  */
11308         if (inputsize > pamax &&
11309             (arm_el_is_aa64(env, 1) || inputsize > 40)) {
11310             /* This is CONSTRAINED UNPREDICTABLE and we choose to fault.  */
11311             return false;
11312         }
11313     } else {
11314         /* AArch32 only supports 4KB pages. Assert on that.  */
11315         assert(stride == 9);
11316 
11317         if (level == 0) {
11318             return false;
11319         }
11320     }
11321     return true;
11322 }
11323 
11324 /* Translate from the 4-bit stage 2 representation of
11325  * memory attributes (without cache-allocation hints) to
11326  * the 8-bit representation of the stage 1 MAIR registers
11327  * (which includes allocation hints).
11328  *
11329  * ref: shared/translation/attrs/S2AttrDecode()
11330  *      .../S2ConvertAttrsHints()
11331  */
11332 static uint8_t convert_stage2_attrs(CPUARMState *env, uint8_t s2attrs)
11333 {
11334     uint8_t hiattr = extract32(s2attrs, 2, 2);
11335     uint8_t loattr = extract32(s2attrs, 0, 2);
11336     uint8_t hihint = 0, lohint = 0;
11337 
11338     if (hiattr != 0) { /* normal memory */
11339         if (arm_hcr_el2_eff(env) & HCR_CD) { /* cache disabled */
11340             hiattr = loattr = 1; /* non-cacheable */
11341         } else {
11342             if (hiattr != 1) { /* Write-through or write-back */
11343                 hihint = 3; /* RW allocate */
11344             }
11345             if (loattr != 1) { /* Write-through or write-back */
11346                 lohint = 3; /* RW allocate */
11347             }
11348         }
11349     }
11350 
11351     return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
11352 }
11353 #endif /* !CONFIG_USER_ONLY */
11354 
11355 static int aa64_va_parameter_tbi(uint64_t tcr, ARMMMUIdx mmu_idx)
11356 {
11357     if (regime_has_2_ranges(mmu_idx)) {
11358         return extract64(tcr, 37, 2);
11359     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11360         return 0; /* VTCR_EL2 */
11361     } else {
11362         /* Replicate the single TBI bit so we always have 2 bits.  */
11363         return extract32(tcr, 20, 1) * 3;
11364     }
11365 }
11366 
11367 static int aa64_va_parameter_tbid(uint64_t tcr, ARMMMUIdx mmu_idx)
11368 {
11369     if (regime_has_2_ranges(mmu_idx)) {
11370         return extract64(tcr, 51, 2);
11371     } else if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11372         return 0; /* VTCR_EL2 */
11373     } else {
11374         /* Replicate the single TBID bit so we always have 2 bits.  */
11375         return extract32(tcr, 29, 1) * 3;
11376     }
11377 }
11378 
11379 static int aa64_va_parameter_tcma(uint64_t tcr, ARMMMUIdx mmu_idx)
11380 {
11381     if (regime_has_2_ranges(mmu_idx)) {
11382         return extract64(tcr, 57, 2);
11383     } else {
11384         /* Replicate the single TCMA bit so we always have 2 bits.  */
11385         return extract32(tcr, 30, 1) * 3;
11386     }
11387 }
11388 
11389 ARMVAParameters aa64_va_parameters(CPUARMState *env, uint64_t va,
11390                                    ARMMMUIdx mmu_idx, bool data)
11391 {
11392     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11393     bool epd, hpd, using16k, using64k;
11394     int select, tsz, tbi, max_tsz;
11395 
11396     if (!regime_has_2_ranges(mmu_idx)) {
11397         select = 0;
11398         tsz = extract32(tcr, 0, 6);
11399         using64k = extract32(tcr, 14, 1);
11400         using16k = extract32(tcr, 15, 1);
11401         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11402             /* VTCR_EL2 */
11403             hpd = false;
11404         } else {
11405             hpd = extract32(tcr, 24, 1);
11406         }
11407         epd = false;
11408     } else {
11409         /*
11410          * Bit 55 is always between the two regions, and is canonical for
11411          * determining if address tagging is enabled.
11412          */
11413         select = extract64(va, 55, 1);
11414         if (!select) {
11415             tsz = extract32(tcr, 0, 6);
11416             epd = extract32(tcr, 7, 1);
11417             using64k = extract32(tcr, 14, 1);
11418             using16k = extract32(tcr, 15, 1);
11419             hpd = extract64(tcr, 41, 1);
11420         } else {
11421             int tg = extract32(tcr, 30, 2);
11422             using16k = tg == 1;
11423             using64k = tg == 3;
11424             tsz = extract32(tcr, 16, 6);
11425             epd = extract32(tcr, 23, 1);
11426             hpd = extract64(tcr, 42, 1);
11427         }
11428     }
11429 
11430     if (cpu_isar_feature(aa64_st, env_archcpu(env))) {
11431         max_tsz = 48 - using64k;
11432     } else {
11433         max_tsz = 39;
11434     }
11435 
11436     tsz = MIN(tsz, max_tsz);
11437     tsz = MAX(tsz, 16);  /* TODO: ARMv8.2-LVA  */
11438 
11439     /* Present TBI as a composite with TBID.  */
11440     tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
11441     if (!data) {
11442         tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
11443     }
11444     tbi = (tbi >> select) & 1;
11445 
11446     return (ARMVAParameters) {
11447         .tsz = tsz,
11448         .select = select,
11449         .tbi = tbi,
11450         .epd = epd,
11451         .hpd = hpd,
11452         .using16k = using16k,
11453         .using64k = using64k,
11454     };
11455 }
11456 
11457 #ifndef CONFIG_USER_ONLY
11458 static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
11459                                           ARMMMUIdx mmu_idx)
11460 {
11461     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
11462     uint32_t el = regime_el(env, mmu_idx);
11463     int select, tsz;
11464     bool epd, hpd;
11465 
11466     assert(mmu_idx != ARMMMUIdx_Stage2_S);
11467 
11468     if (mmu_idx == ARMMMUIdx_Stage2) {
11469         /* VTCR */
11470         bool sext = extract32(tcr, 4, 1);
11471         bool sign = extract32(tcr, 3, 1);
11472 
11473         /*
11474          * If the sign-extend bit is not the same as t0sz[3], the result
11475          * is unpredictable. Flag this as a guest error.
11476          */
11477         if (sign != sext) {
11478             qemu_log_mask(LOG_GUEST_ERROR,
11479                           "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
11480         }
11481         tsz = sextract32(tcr, 0, 4) + 8;
11482         select = 0;
11483         hpd = false;
11484         epd = false;
11485     } else if (el == 2) {
11486         /* HTCR */
11487         tsz = extract32(tcr, 0, 3);
11488         select = 0;
11489         hpd = extract64(tcr, 24, 1);
11490         epd = false;
11491     } else {
11492         int t0sz = extract32(tcr, 0, 3);
11493         int t1sz = extract32(tcr, 16, 3);
11494 
11495         if (t1sz == 0) {
11496             select = va > (0xffffffffu >> t0sz);
11497         } else {
11498             /* Note that we will detect errors later.  */
11499             select = va >= ~(0xffffffffu >> t1sz);
11500         }
11501         if (!select) {
11502             tsz = t0sz;
11503             epd = extract32(tcr, 7, 1);
11504             hpd = extract64(tcr, 41, 1);
11505         } else {
11506             tsz = t1sz;
11507             epd = extract32(tcr, 23, 1);
11508             hpd = extract64(tcr, 42, 1);
11509         }
11510         /* For aarch32, hpd0 is not enabled without t2e as well.  */
11511         hpd &= extract32(tcr, 6, 1);
11512     }
11513 
11514     return (ARMVAParameters) {
11515         .tsz = tsz,
11516         .select = select,
11517         .epd = epd,
11518         .hpd = hpd,
11519     };
11520 }
11521 
11522 /**
11523  * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
11524  *
11525  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
11526  * prot and page_size may not be filled in, and the populated fsr value provides
11527  * information on why the translation aborted, in the format of a long-format
11528  * DFSR/IFSR fault register, with the following caveats:
11529  *  * the WnR bit is never set (the caller must do this).
11530  *
11531  * @env: CPUARMState
11532  * @address: virtual address to get physical address for
11533  * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
11534  * @mmu_idx: MMU index indicating required translation regime
11535  * @s1_is_el0: if @mmu_idx is ARMMMUIdx_Stage2 (so this is a stage 2 page table
11536  *             walk), must be true if this is stage 2 of a stage 1+2 walk for an
11537  *             EL0 access). If @mmu_idx is anything else, @s1_is_el0 is ignored.
11538  * @phys_ptr: set to the physical address corresponding to the virtual address
11539  * @attrs: set to the memory transaction attributes to use
11540  * @prot: set to the permissions for the page containing phys_ptr
11541  * @page_size_ptr: set to the size of the page containing phys_ptr
11542  * @fi: set to fault info if the translation fails
11543  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
11544  */
11545 static bool get_phys_addr_lpae(CPUARMState *env, uint64_t address,
11546                                MMUAccessType access_type, ARMMMUIdx mmu_idx,
11547                                bool s1_is_el0,
11548                                hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,
11549                                target_ulong *page_size_ptr,
11550                                ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
11551 {
11552     ARMCPU *cpu = env_archcpu(env);
11553     CPUState *cs = CPU(cpu);
11554     /* Read an LPAE long-descriptor translation table. */
11555     ARMFaultType fault_type = ARMFault_Translation;
11556     uint32_t level;
11557     ARMVAParameters param;
11558     uint64_t ttbr;
11559     hwaddr descaddr, indexmask, indexmask_grainsize;
11560     uint32_t tableattrs;
11561     target_ulong page_size;
11562     uint32_t attrs;
11563     int32_t stride;
11564     int addrsize, inputsize;
11565     TCR *tcr = regime_tcr(env, mmu_idx);
11566     int ap, ns, xn, pxn;
11567     uint32_t el = regime_el(env, mmu_idx);
11568     uint64_t descaddrmask;
11569     bool aarch64 = arm_el_is_aa64(env, el);
11570     bool guarded = false;
11571 
11572     /* TODO: This code does not support shareability levels. */
11573     if (aarch64) {
11574         param = aa64_va_parameters(env, address, mmu_idx,
11575                                    access_type != MMU_INST_FETCH);
11576         level = 0;
11577         addrsize = 64 - 8 * param.tbi;
11578         inputsize = 64 - param.tsz;
11579     } else {
11580         param = aa32_va_parameters(env, address, mmu_idx);
11581         level = 1;
11582         addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
11583         inputsize = addrsize - param.tsz;
11584     }
11585 
11586     /*
11587      * We determined the region when collecting the parameters, but we
11588      * have not yet validated that the address is valid for the region.
11589      * Extract the top bits and verify that they all match select.
11590      *
11591      * For aa32, if inputsize == addrsize, then we have selected the
11592      * region by exclusion in aa32_va_parameters and there is no more
11593      * validation to do here.
11594      */
11595     if (inputsize < addrsize) {
11596         target_ulong top_bits = sextract64(address, inputsize,
11597                                            addrsize - inputsize);
11598         if (-top_bits != param.select) {
11599             /* The gap between the two regions is a Translation fault */
11600             fault_type = ARMFault_Translation;
11601             goto do_fault;
11602         }
11603     }
11604 
11605     if (param.using64k) {
11606         stride = 13;
11607     } else if (param.using16k) {
11608         stride = 11;
11609     } else {
11610         stride = 9;
11611     }
11612 
11613     /* Note that QEMU ignores shareability and cacheability attributes,
11614      * so we don't need to do anything with the SH, ORGN, IRGN fields
11615      * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
11616      * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
11617      * implement any ASID-like capability so we can ignore it (instead
11618      * we will always flush the TLB any time the ASID is changed).
11619      */
11620     ttbr = regime_ttbr(env, mmu_idx, param.select);
11621 
11622     /* Here we should have set up all the parameters for the translation:
11623      * inputsize, ttbr, epd, stride, tbi
11624      */
11625 
11626     if (param.epd) {
11627         /* Translation table walk disabled => Translation fault on TLB miss
11628          * Note: This is always 0 on 64-bit EL2 and EL3.
11629          */
11630         goto do_fault;
11631     }
11632 
11633     if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
11634         /* The starting level depends on the virtual address size (which can
11635          * be up to 48 bits) and the translation granule size. It indicates
11636          * the number of strides (stride bits at a time) needed to
11637          * consume the bits of the input address. In the pseudocode this is:
11638          *  level = 4 - RoundUp((inputsize - grainsize) / stride)
11639          * where their 'inputsize' is our 'inputsize', 'grainsize' is
11640          * our 'stride + 3' and 'stride' is our 'stride'.
11641          * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
11642          * = 4 - (inputsize - stride - 3 + stride - 1) / stride
11643          * = 4 - (inputsize - 4) / stride;
11644          */
11645         level = 4 - (inputsize - 4) / stride;
11646     } else {
11647         /* For stage 2 translations the starting level is specified by the
11648          * VTCR_EL2.SL0 field (whose interpretation depends on the page size)
11649          */
11650         uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);
11651         uint32_t startlevel;
11652         bool ok;
11653 
11654         if (!aarch64 || stride == 9) {
11655             /* AArch32 or 4KB pages */
11656             startlevel = 2 - sl0;
11657 
11658             if (cpu_isar_feature(aa64_st, cpu)) {
11659                 startlevel &= 3;
11660             }
11661         } else {
11662             /* 16KB or 64KB pages */
11663             startlevel = 3 - sl0;
11664         }
11665 
11666         /* Check that the starting level is valid. */
11667         ok = check_s2_mmu_setup(cpu, aarch64, startlevel,
11668                                 inputsize, stride);
11669         if (!ok) {
11670             fault_type = ARMFault_Translation;
11671             goto do_fault;
11672         }
11673         level = startlevel;
11674     }
11675 
11676     indexmask_grainsize = (1ULL << (stride + 3)) - 1;
11677     indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;
11678 
11679     /* Now we can extract the actual base address from the TTBR */
11680     descaddr = extract64(ttbr, 0, 48);
11681     /*
11682      * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
11683      * and also to mask out CnP (bit 0) which could validly be non-zero.
11684      */
11685     descaddr &= ~indexmask;
11686 
11687     /* The address field in the descriptor goes up to bit 39 for ARMv7
11688      * but up to bit 47 for ARMv8, but we use the descaddrmask
11689      * up to bit 39 for AArch32, because we don't need other bits in that case
11690      * to construct next descriptor address (anyway they should be all zeroes).
11691      */
11692     descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &
11693                    ~indexmask_grainsize;
11694 
11695     /* Secure accesses start with the page table in secure memory and
11696      * can be downgraded to non-secure at any step. Non-secure accesses
11697      * remain non-secure. We implement this by just ORing in the NSTable/NS
11698      * bits at each step.
11699      */
11700     tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);
11701     for (;;) {
11702         uint64_t descriptor;
11703         bool nstable;
11704 
11705         descaddr |= (address >> (stride * (4 - level))) & indexmask;
11706         descaddr &= ~7ULL;
11707         nstable = extract32(tableattrs, 4, 1);
11708         descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);
11709         if (fi->type != ARMFault_None) {
11710             goto do_fault;
11711         }
11712 
11713         if (!(descriptor & 1) ||
11714             (!(descriptor & 2) && (level == 3))) {
11715             /* Invalid, or the Reserved level 3 encoding */
11716             goto do_fault;
11717         }
11718         descaddr = descriptor & descaddrmask;
11719 
11720         if ((descriptor & 2) && (level < 3)) {
11721             /* Table entry. The top five bits are attributes which may
11722              * propagate down through lower levels of the table (and
11723              * which are all arranged so that 0 means "no effect", so
11724              * we can gather them up by ORing in the bits at each level).
11725              */
11726             tableattrs |= extract64(descriptor, 59, 5);
11727             level++;
11728             indexmask = indexmask_grainsize;
11729             continue;
11730         }
11731         /* Block entry at level 1 or 2, or page entry at level 3.
11732          * These are basically the same thing, although the number
11733          * of bits we pull in from the vaddr varies.
11734          */
11735         page_size = (1ULL << ((stride * (4 - level)) + 3));
11736         descaddr |= (address & (page_size - 1));
11737         /* Extract attributes from the descriptor */
11738         attrs = extract64(descriptor, 2, 10)
11739             | (extract64(descriptor, 52, 12) << 10);
11740 
11741         if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11742             /* Stage 2 table descriptors do not include any attribute fields */
11743             break;
11744         }
11745         /* Merge in attributes from table descriptors */
11746         attrs |= nstable << 3; /* NS */
11747         guarded = extract64(descriptor, 50, 1);  /* GP */
11748         if (param.hpd) {
11749             /* HPD disables all the table attributes except NSTable.  */
11750             break;
11751         }
11752         attrs |= extract32(tableattrs, 0, 2) << 11;     /* XN, PXN */
11753         /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
11754          * means "force PL1 access only", which means forcing AP[1] to 0.
11755          */
11756         attrs &= ~(extract32(tableattrs, 2, 1) << 4);   /* !APT[0] => AP[1] */
11757         attrs |= extract32(tableattrs, 3, 1) << 5;      /* APT[1] => AP[2] */
11758         break;
11759     }
11760     /* Here descaddr is the final physical address, and attributes
11761      * are all in attrs.
11762      */
11763     fault_type = ARMFault_AccessFlag;
11764     if ((attrs & (1 << 8)) == 0) {
11765         /* Access flag */
11766         goto do_fault;
11767     }
11768 
11769     ap = extract32(attrs, 4, 2);
11770 
11771     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11772         ns = mmu_idx == ARMMMUIdx_Stage2;
11773         xn = extract32(attrs, 11, 2);
11774         *prot = get_S2prot(env, ap, xn, s1_is_el0);
11775     } else {
11776         ns = extract32(attrs, 3, 1);
11777         xn = extract32(attrs, 12, 1);
11778         pxn = extract32(attrs, 11, 1);
11779         *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);
11780     }
11781 
11782     fault_type = ARMFault_Permission;
11783     if (!(*prot & (1 << access_type))) {
11784         goto do_fault;
11785     }
11786 
11787     if (ns) {
11788         /* The NS bit will (as required by the architecture) have no effect if
11789          * the CPU doesn't support TZ or this is a non-secure translation
11790          * regime, because the attribute will already be non-secure.
11791          */
11792         txattrs->secure = false;
11793     }
11794     /* When in aarch64 mode, and BTI is enabled, remember GP in the IOTLB.  */
11795     if (aarch64 && guarded && cpu_isar_feature(aa64_bti, cpu)) {
11796         arm_tlb_bti_gp(txattrs) = true;
11797     }
11798 
11799     if (mmu_idx == ARMMMUIdx_Stage2 || mmu_idx == ARMMMUIdx_Stage2_S) {
11800         cacheattrs->attrs = convert_stage2_attrs(env, extract32(attrs, 0, 4));
11801     } else {
11802         /* Index into MAIR registers for cache attributes */
11803         uint8_t attrindx = extract32(attrs, 0, 3);
11804         uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
11805         assert(attrindx <= 7);
11806         cacheattrs->attrs = extract64(mair, attrindx * 8, 8);
11807     }
11808     cacheattrs->shareability = extract32(attrs, 6, 2);
11809 
11810     *phys_ptr = descaddr;
11811     *page_size_ptr = page_size;
11812     return false;
11813 
11814 do_fault:
11815     fi->type = fault_type;
11816     fi->level = level;
11817     /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */
11818     fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_Stage2 ||
11819                                mmu_idx == ARMMMUIdx_Stage2_S);
11820     fi->s1ns = mmu_idx == ARMMMUIdx_Stage2;
11821     return true;
11822 }
11823 
11824 static inline void get_phys_addr_pmsav7_default(CPUARMState *env,
11825                                                 ARMMMUIdx mmu_idx,
11826                                                 int32_t address, int *prot)
11827 {
11828     if (!arm_feature(env, ARM_FEATURE_M)) {
11829         *prot = PAGE_READ | PAGE_WRITE;
11830         switch (address) {
11831         case 0xF0000000 ... 0xFFFFFFFF:
11832             if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
11833                 /* hivecs execing is ok */
11834                 *prot |= PAGE_EXEC;
11835             }
11836             break;
11837         case 0x00000000 ... 0x7FFFFFFF:
11838             *prot |= PAGE_EXEC;
11839             break;
11840         }
11841     } else {
11842         /* Default system address map for M profile cores.
11843          * The architecture specifies which regions are execute-never;
11844          * at the MPU level no other checks are defined.
11845          */
11846         switch (address) {
11847         case 0x00000000 ... 0x1fffffff: /* ROM */
11848         case 0x20000000 ... 0x3fffffff: /* SRAM */
11849         case 0x60000000 ... 0x7fffffff: /* RAM */
11850         case 0x80000000 ... 0x9fffffff: /* RAM */
11851             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
11852             break;
11853         case 0x40000000 ... 0x5fffffff: /* Peripheral */
11854         case 0xa0000000 ... 0xbfffffff: /* Device */
11855         case 0xc0000000 ... 0xdfffffff: /* Device */
11856         case 0xe0000000 ... 0xffffffff: /* System */
11857             *prot = PAGE_READ | PAGE_WRITE;
11858             break;
11859         default:
11860             g_assert_not_reached();
11861         }
11862     }
11863 }
11864 
11865 static bool pmsav7_use_background_region(ARMCPU *cpu,
11866                                          ARMMMUIdx mmu_idx, bool is_user)
11867 {
11868     /* Return true if we should use the default memory map as a
11869      * "background" region if there are no hits against any MPU regions.
11870      */
11871     CPUARMState *env = &cpu->env;
11872 
11873     if (is_user) {
11874         return false;
11875     }
11876 
11877     if (arm_feature(env, ARM_FEATURE_M)) {
11878         return env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)]
11879             & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
11880     } else {
11881         return regime_sctlr(env, mmu_idx) & SCTLR_BR;
11882     }
11883 }
11884 
11885 static inline bool m_is_ppb_region(CPUARMState *env, uint32_t address)
11886 {
11887     /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
11888     return arm_feature(env, ARM_FEATURE_M) &&
11889         extract32(address, 20, 12) == 0xe00;
11890 }
11891 
11892 static inline bool m_is_system_region(CPUARMState *env, uint32_t address)
11893 {
11894     /* True if address is in the M profile system region
11895      * 0xe0000000 - 0xffffffff
11896      */
11897     return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
11898 }
11899 
11900 static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,
11901                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
11902                                  hwaddr *phys_ptr, int *prot,
11903                                  target_ulong *page_size,
11904                                  ARMMMUFaultInfo *fi)
11905 {
11906     ARMCPU *cpu = env_archcpu(env);
11907     int n;
11908     bool is_user = regime_is_user(env, mmu_idx);
11909 
11910     *phys_ptr = address;
11911     *page_size = TARGET_PAGE_SIZE;
11912     *prot = 0;
11913 
11914     if (regime_translation_disabled(env, mmu_idx) ||
11915         m_is_ppb_region(env, address)) {
11916         /* MPU disabled or M profile PPB access: use default memory map.
11917          * The other case which uses the default memory map in the
11918          * v7M ARM ARM pseudocode is exception vector reads from the vector
11919          * table. In QEMU those accesses are done in arm_v7m_load_vector(),
11920          * which always does a direct read using address_space_ldl(), rather
11921          * than going via this function, so we don't need to check that here.
11922          */
11923         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
11924     } else { /* MPU enabled */
11925         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
11926             /* region search */
11927             uint32_t base = env->pmsav7.drbar[n];
11928             uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
11929             uint32_t rmask;
11930             bool srdis = false;
11931 
11932             if (!(env->pmsav7.drsr[n] & 0x1)) {
11933                 continue;
11934             }
11935 
11936             if (!rsize) {
11937                 qemu_log_mask(LOG_GUEST_ERROR,
11938                               "DRSR[%d]: Rsize field cannot be 0\n", n);
11939                 continue;
11940             }
11941             rsize++;
11942             rmask = (1ull << rsize) - 1;
11943 
11944             if (base & rmask) {
11945                 qemu_log_mask(LOG_GUEST_ERROR,
11946                               "DRBAR[%d]: 0x%" PRIx32 " misaligned "
11947                               "to DRSR region size, mask = 0x%" PRIx32 "\n",
11948                               n, base, rmask);
11949                 continue;
11950             }
11951 
11952             if (address < base || address > base + rmask) {
11953                 /*
11954                  * Address not in this region. We must check whether the
11955                  * region covers addresses in the same page as our address.
11956                  * In that case we must not report a size that covers the
11957                  * whole page for a subsequent hit against a different MPU
11958                  * region or the background region, because it would result in
11959                  * incorrect TLB hits for subsequent accesses to addresses that
11960                  * are in this MPU region.
11961                  */
11962                 if (ranges_overlap(base, rmask,
11963                                    address & TARGET_PAGE_MASK,
11964                                    TARGET_PAGE_SIZE)) {
11965                     *page_size = 1;
11966                 }
11967                 continue;
11968             }
11969 
11970             /* Region matched */
11971 
11972             if (rsize >= 8) { /* no subregions for regions < 256 bytes */
11973                 int i, snd;
11974                 uint32_t srdis_mask;
11975 
11976                 rsize -= 3; /* sub region size (power of 2) */
11977                 snd = ((address - base) >> rsize) & 0x7;
11978                 srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
11979 
11980                 srdis_mask = srdis ? 0x3 : 0x0;
11981                 for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
11982                     /* This will check in groups of 2, 4 and then 8, whether
11983                      * the subregion bits are consistent. rsize is incremented
11984                      * back up to give the region size, considering consistent
11985                      * adjacent subregions as one region. Stop testing if rsize
11986                      * is already big enough for an entire QEMU page.
11987                      */
11988                     int snd_rounded = snd & ~(i - 1);
11989                     uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
11990                                                      snd_rounded + 8, i);
11991                     if (srdis_mask ^ srdis_multi) {
11992                         break;
11993                     }
11994                     srdis_mask = (srdis_mask << i) | srdis_mask;
11995                     rsize++;
11996                 }
11997             }
11998             if (srdis) {
11999                 continue;
12000             }
12001             if (rsize < TARGET_PAGE_BITS) {
12002                 *page_size = 1 << rsize;
12003             }
12004             break;
12005         }
12006 
12007         if (n == -1) { /* no hits */
12008             if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12009                 /* background fault */
12010                 fi->type = ARMFault_Background;
12011                 return true;
12012             }
12013             get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12014         } else { /* a MPU hit! */
12015             uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
12016             uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
12017 
12018             if (m_is_system_region(env, address)) {
12019                 /* System space is always execute never */
12020                 xn = 1;
12021             }
12022 
12023             if (is_user) { /* User mode AP bit decoding */
12024                 switch (ap) {
12025                 case 0:
12026                 case 1:
12027                 case 5:
12028                     break; /* no access */
12029                 case 3:
12030                     *prot |= PAGE_WRITE;
12031                     /* fall through */
12032                 case 2:
12033                 case 6:
12034                     *prot |= PAGE_READ | PAGE_EXEC;
12035                     break;
12036                 case 7:
12037                     /* for v7M, same as 6; for R profile a reserved value */
12038                     if (arm_feature(env, ARM_FEATURE_M)) {
12039                         *prot |= PAGE_READ | PAGE_EXEC;
12040                         break;
12041                     }
12042                     /* fall through */
12043                 default:
12044                     qemu_log_mask(LOG_GUEST_ERROR,
12045                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12046                                   PRIx32 "\n", n, ap);
12047                 }
12048             } else { /* Priv. mode AP bits decoding */
12049                 switch (ap) {
12050                 case 0:
12051                     break; /* no access */
12052                 case 1:
12053                 case 2:
12054                 case 3:
12055                     *prot |= PAGE_WRITE;
12056                     /* fall through */
12057                 case 5:
12058                 case 6:
12059                     *prot |= PAGE_READ | PAGE_EXEC;
12060                     break;
12061                 case 7:
12062                     /* for v7M, same as 6; for R profile a reserved value */
12063                     if (arm_feature(env, ARM_FEATURE_M)) {
12064                         *prot |= PAGE_READ | PAGE_EXEC;
12065                         break;
12066                     }
12067                     /* fall through */
12068                 default:
12069                     qemu_log_mask(LOG_GUEST_ERROR,
12070                                   "DRACR[%d]: Bad value for AP bits: 0x%"
12071                                   PRIx32 "\n", n, ap);
12072                 }
12073             }
12074 
12075             /* execute never */
12076             if (xn) {
12077                 *prot &= ~PAGE_EXEC;
12078             }
12079         }
12080     }
12081 
12082     fi->type = ARMFault_Permission;
12083     fi->level = 1;
12084     return !(*prot & (1 << access_type));
12085 }
12086 
12087 static bool v8m_is_sau_exempt(CPUARMState *env,
12088                               uint32_t address, MMUAccessType access_type)
12089 {
12090     /* The architecture specifies that certain address ranges are
12091      * exempt from v8M SAU/IDAU checks.
12092      */
12093     return
12094         (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
12095         (address >= 0xe0000000 && address <= 0xe0002fff) ||
12096         (address >= 0xe000e000 && address <= 0xe000efff) ||
12097         (address >= 0xe002e000 && address <= 0xe002efff) ||
12098         (address >= 0xe0040000 && address <= 0xe0041fff) ||
12099         (address >= 0xe00ff000 && address <= 0xe00fffff);
12100 }
12101 
12102 void v8m_security_lookup(CPUARMState *env, uint32_t address,
12103                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,
12104                                 V8M_SAttributes *sattrs)
12105 {
12106     /* Look up the security attributes for this address. Compare the
12107      * pseudocode SecurityCheck() function.
12108      * We assume the caller has zero-initialized *sattrs.
12109      */
12110     ARMCPU *cpu = env_archcpu(env);
12111     int r;
12112     bool idau_exempt = false, idau_ns = true, idau_nsc = true;
12113     int idau_region = IREGION_NOTVALID;
12114     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12115     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12116 
12117     if (cpu->idau) {
12118         IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
12119         IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
12120 
12121         iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
12122                    &idau_nsc);
12123     }
12124 
12125     if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
12126         /* 0xf0000000..0xffffffff is always S for insn fetches */
12127         return;
12128     }
12129 
12130     if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
12131         sattrs->ns = !regime_is_secure(env, mmu_idx);
12132         return;
12133     }
12134 
12135     if (idau_region != IREGION_NOTVALID) {
12136         sattrs->irvalid = true;
12137         sattrs->iregion = idau_region;
12138     }
12139 
12140     switch (env->sau.ctrl & 3) {
12141     case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
12142         break;
12143     case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
12144         sattrs->ns = true;
12145         break;
12146     default: /* SAU.ENABLE == 1 */
12147         for (r = 0; r < cpu->sau_sregion; r++) {
12148             if (env->sau.rlar[r] & 1) {
12149                 uint32_t base = env->sau.rbar[r] & ~0x1f;
12150                 uint32_t limit = env->sau.rlar[r] | 0x1f;
12151 
12152                 if (base <= address && limit >= address) {
12153                     if (base > addr_page_base || limit < addr_page_limit) {
12154                         sattrs->subpage = true;
12155                     }
12156                     if (sattrs->srvalid) {
12157                         /* If we hit in more than one region then we must report
12158                          * as Secure, not NS-Callable, with no valid region
12159                          * number info.
12160                          */
12161                         sattrs->ns = false;
12162                         sattrs->nsc = false;
12163                         sattrs->sregion = 0;
12164                         sattrs->srvalid = false;
12165                         break;
12166                     } else {
12167                         if (env->sau.rlar[r] & 2) {
12168                             sattrs->nsc = true;
12169                         } else {
12170                             sattrs->ns = true;
12171                         }
12172                         sattrs->srvalid = true;
12173                         sattrs->sregion = r;
12174                     }
12175                 } else {
12176                     /*
12177                      * Address not in this region. We must check whether the
12178                      * region covers addresses in the same page as our address.
12179                      * In that case we must not report a size that covers the
12180                      * whole page for a subsequent hit against a different MPU
12181                      * region or the background region, because it would result
12182                      * in incorrect TLB hits for subsequent accesses to
12183                      * addresses that are in this MPU region.
12184                      */
12185                     if (limit >= base &&
12186                         ranges_overlap(base, limit - base + 1,
12187                                        addr_page_base,
12188                                        TARGET_PAGE_SIZE)) {
12189                         sattrs->subpage = true;
12190                     }
12191                 }
12192             }
12193         }
12194         break;
12195     }
12196 
12197     /*
12198      * The IDAU will override the SAU lookup results if it specifies
12199      * higher security than the SAU does.
12200      */
12201     if (!idau_ns) {
12202         if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
12203             sattrs->ns = false;
12204             sattrs->nsc = idau_nsc;
12205         }
12206     }
12207 }
12208 
12209 bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
12210                               MMUAccessType access_type, ARMMMUIdx mmu_idx,
12211                               hwaddr *phys_ptr, MemTxAttrs *txattrs,
12212                               int *prot, bool *is_subpage,
12213                               ARMMMUFaultInfo *fi, uint32_t *mregion)
12214 {
12215     /* Perform a PMSAv8 MPU lookup (without also doing the SAU check
12216      * that a full phys-to-virt translation does).
12217      * mregion is (if not NULL) set to the region number which matched,
12218      * or -1 if no region number is returned (MPU off, address did not
12219      * hit a region, address hit in multiple regions).
12220      * We set is_subpage to true if the region hit doesn't cover the
12221      * entire TARGET_PAGE the address is within.
12222      */
12223     ARMCPU *cpu = env_archcpu(env);
12224     bool is_user = regime_is_user(env, mmu_idx);
12225     uint32_t secure = regime_is_secure(env, mmu_idx);
12226     int n;
12227     int matchregion = -1;
12228     bool hit = false;
12229     uint32_t addr_page_base = address & TARGET_PAGE_MASK;
12230     uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
12231 
12232     *is_subpage = false;
12233     *phys_ptr = address;
12234     *prot = 0;
12235     if (mregion) {
12236         *mregion = -1;
12237     }
12238 
12239     /* Unlike the ARM ARM pseudocode, we don't need to check whether this
12240      * was an exception vector read from the vector table (which is always
12241      * done using the default system address map), because those accesses
12242      * are done in arm_v7m_load_vector(), which always does a direct
12243      * read using address_space_ldl(), rather than going via this function.
12244      */
12245     if (regime_translation_disabled(env, mmu_idx)) { /* MPU disabled */
12246         hit = true;
12247     } else if (m_is_ppb_region(env, address)) {
12248         hit = true;
12249     } else {
12250         if (pmsav7_use_background_region(cpu, mmu_idx, is_user)) {
12251             hit = true;
12252         }
12253 
12254         for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
12255             /* region search */
12256             /* Note that the base address is bits [31:5] from the register
12257              * with bits [4:0] all zeroes, but the limit address is bits
12258              * [31:5] from the register with bits [4:0] all ones.
12259              */
12260             uint32_t base = env->pmsav8.rbar[secure][n] & ~0x1f;
12261             uint32_t limit = env->pmsav8.rlar[secure][n] | 0x1f;
12262 
12263             if (!(env->pmsav8.rlar[secure][n] & 0x1)) {
12264                 /* Region disabled */
12265                 continue;
12266             }
12267 
12268             if (address < base || address > limit) {
12269                 /*
12270                  * Address not in this region. We must check whether the
12271                  * region covers addresses in the same page as our address.
12272                  * In that case we must not report a size that covers the
12273                  * whole page for a subsequent hit against a different MPU
12274                  * region or the background region, because it would result in
12275                  * incorrect TLB hits for subsequent accesses to addresses that
12276                  * are in this MPU region.
12277                  */
12278                 if (limit >= base &&
12279                     ranges_overlap(base, limit - base + 1,
12280                                    addr_page_base,
12281                                    TARGET_PAGE_SIZE)) {
12282                     *is_subpage = true;
12283                 }
12284                 continue;
12285             }
12286 
12287             if (base > addr_page_base || limit < addr_page_limit) {
12288                 *is_subpage = true;
12289             }
12290 
12291             if (matchregion != -1) {
12292                 /* Multiple regions match -- always a failure (unlike
12293                  * PMSAv7 where highest-numbered-region wins)
12294                  */
12295                 fi->type = ARMFault_Permission;
12296                 fi->level = 1;
12297                 return true;
12298             }
12299 
12300             matchregion = n;
12301             hit = true;
12302         }
12303     }
12304 
12305     if (!hit) {
12306         /* background fault */
12307         fi->type = ARMFault_Background;
12308         return true;
12309     }
12310 
12311     if (matchregion == -1) {
12312         /* hit using the background region */
12313         get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);
12314     } else {
12315         uint32_t ap = extract32(env->pmsav8.rbar[secure][matchregion], 1, 2);
12316         uint32_t xn = extract32(env->pmsav8.rbar[secure][matchregion], 0, 1);
12317         bool pxn = false;
12318 
12319         if (arm_feature(env, ARM_FEATURE_V8_1M)) {
12320             pxn = extract32(env->pmsav8.rlar[secure][matchregion], 4, 1);
12321         }
12322 
12323         if (m_is_system_region(env, address)) {
12324             /* System space is always execute never */
12325             xn = 1;
12326         }
12327 
12328         *prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
12329         if (*prot && !xn && !(pxn && !is_user)) {
12330             *prot |= PAGE_EXEC;
12331         }
12332         /* We don't need to look the attribute up in the MAIR0/MAIR1
12333          * registers because that only tells us about cacheability.
12334          */
12335         if (mregion) {
12336             *mregion = matchregion;
12337         }
12338     }
12339 
12340     fi->type = ARMFault_Permission;
12341     fi->level = 1;
12342     return !(*prot & (1 << access_type));
12343 }
12344 
12345 
12346 static bool get_phys_addr_pmsav8(CPUARMState *env, uint32_t address,
12347                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12348                                  hwaddr *phys_ptr, MemTxAttrs *txattrs,
12349                                  int *prot, target_ulong *page_size,
12350                                  ARMMMUFaultInfo *fi)
12351 {
12352     uint32_t secure = regime_is_secure(env, mmu_idx);
12353     V8M_SAttributes sattrs = {};
12354     bool ret;
12355     bool mpu_is_subpage;
12356 
12357     if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
12358         v8m_security_lookup(env, address, access_type, mmu_idx, &sattrs);
12359         if (access_type == MMU_INST_FETCH) {
12360             /* Instruction fetches always use the MMU bank and the
12361              * transaction attribute determined by the fetch address,
12362              * regardless of CPU state. This is painful for QEMU
12363              * to handle, because it would mean we need to encode
12364              * into the mmu_idx not just the (user, negpri) information
12365              * for the current security state but also that for the
12366              * other security state, which would balloon the number
12367              * of mmu_idx values needed alarmingly.
12368              * Fortunately we can avoid this because it's not actually
12369              * possible to arbitrarily execute code from memory with
12370              * the wrong security attribute: it will always generate
12371              * an exception of some kind or another, apart from the
12372              * special case of an NS CPU executing an SG instruction
12373              * in S&NSC memory. So we always just fail the translation
12374              * here and sort things out in the exception handler
12375              * (including possibly emulating an SG instruction).
12376              */
12377             if (sattrs.ns != !secure) {
12378                 if (sattrs.nsc) {
12379                     fi->type = ARMFault_QEMU_NSCExec;
12380                 } else {
12381                     fi->type = ARMFault_QEMU_SFault;
12382                 }
12383                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12384                 *phys_ptr = address;
12385                 *prot = 0;
12386                 return true;
12387             }
12388         } else {
12389             /* For data accesses we always use the MMU bank indicated
12390              * by the current CPU state, but the security attributes
12391              * might downgrade a secure access to nonsecure.
12392              */
12393             if (sattrs.ns) {
12394                 txattrs->secure = false;
12395             } else if (!secure) {
12396                 /* NS access to S memory must fault.
12397                  * Architecturally we should first check whether the
12398                  * MPU information for this address indicates that we
12399                  * are doing an unaligned access to Device memory, which
12400                  * should generate a UsageFault instead. QEMU does not
12401                  * currently check for that kind of unaligned access though.
12402                  * If we added it we would need to do so as a special case
12403                  * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
12404                  */
12405                 fi->type = ARMFault_QEMU_SFault;
12406                 *page_size = sattrs.subpage ? 1 : TARGET_PAGE_SIZE;
12407                 *phys_ptr = address;
12408                 *prot = 0;
12409                 return true;
12410             }
12411         }
12412     }
12413 
12414     ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, phys_ptr,
12415                             txattrs, prot, &mpu_is_subpage, fi, NULL);
12416     *page_size = sattrs.subpage || mpu_is_subpage ? 1 : TARGET_PAGE_SIZE;
12417     return ret;
12418 }
12419 
12420 static bool get_phys_addr_pmsav5(CPUARMState *env, uint32_t address,
12421                                  MMUAccessType access_type, ARMMMUIdx mmu_idx,
12422                                  hwaddr *phys_ptr, int *prot,
12423                                  ARMMMUFaultInfo *fi)
12424 {
12425     int n;
12426     uint32_t mask;
12427     uint32_t base;
12428     bool is_user = regime_is_user(env, mmu_idx);
12429 
12430     if (regime_translation_disabled(env, mmu_idx)) {
12431         /* MPU disabled.  */
12432         *phys_ptr = address;
12433         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12434         return false;
12435     }
12436 
12437     *phys_ptr = address;
12438     for (n = 7; n >= 0; n--) {
12439         base = env->cp15.c6_region[n];
12440         if ((base & 1) == 0) {
12441             continue;
12442         }
12443         mask = 1 << ((base >> 1) & 0x1f);
12444         /* Keep this shift separate from the above to avoid an
12445            (undefined) << 32.  */
12446         mask = (mask << 1) - 1;
12447         if (((base ^ address) & ~mask) == 0) {
12448             break;
12449         }
12450     }
12451     if (n < 0) {
12452         fi->type = ARMFault_Background;
12453         return true;
12454     }
12455 
12456     if (access_type == MMU_INST_FETCH) {
12457         mask = env->cp15.pmsav5_insn_ap;
12458     } else {
12459         mask = env->cp15.pmsav5_data_ap;
12460     }
12461     mask = (mask >> (n * 4)) & 0xf;
12462     switch (mask) {
12463     case 0:
12464         fi->type = ARMFault_Permission;
12465         fi->level = 1;
12466         return true;
12467     case 1:
12468         if (is_user) {
12469             fi->type = ARMFault_Permission;
12470             fi->level = 1;
12471             return true;
12472         }
12473         *prot = PAGE_READ | PAGE_WRITE;
12474         break;
12475     case 2:
12476         *prot = PAGE_READ;
12477         if (!is_user) {
12478             *prot |= PAGE_WRITE;
12479         }
12480         break;
12481     case 3:
12482         *prot = PAGE_READ | PAGE_WRITE;
12483         break;
12484     case 5:
12485         if (is_user) {
12486             fi->type = ARMFault_Permission;
12487             fi->level = 1;
12488             return true;
12489         }
12490         *prot = PAGE_READ;
12491         break;
12492     case 6:
12493         *prot = PAGE_READ;
12494         break;
12495     default:
12496         /* Bad permission.  */
12497         fi->type = ARMFault_Permission;
12498         fi->level = 1;
12499         return true;
12500     }
12501     *prot |= PAGE_EXEC;
12502     return false;
12503 }
12504 
12505 /* Combine either inner or outer cacheability attributes for normal
12506  * memory, according to table D4-42 and pseudocode procedure
12507  * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
12508  *
12509  * NB: only stage 1 includes allocation hints (RW bits), leading to
12510  * some asymmetry.
12511  */
12512 static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
12513 {
12514     if (s1 == 4 || s2 == 4) {
12515         /* non-cacheable has precedence */
12516         return 4;
12517     } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
12518         /* stage 1 write-through takes precedence */
12519         return s1;
12520     } else if (extract32(s2, 2, 2) == 2) {
12521         /* stage 2 write-through takes precedence, but the allocation hint
12522          * is still taken from stage 1
12523          */
12524         return (2 << 2) | extract32(s1, 0, 2);
12525     } else { /* write-back */
12526         return s1;
12527     }
12528 }
12529 
12530 /* Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
12531  * and CombineS1S2Desc()
12532  *
12533  * @s1:      Attributes from stage 1 walk
12534  * @s2:      Attributes from stage 2 walk
12535  */
12536 static ARMCacheAttrs combine_cacheattrs(ARMCacheAttrs s1, ARMCacheAttrs s2)
12537 {
12538     uint8_t s1lo, s2lo, s1hi, s2hi;
12539     ARMCacheAttrs ret;
12540     bool tagged = false;
12541 
12542     if (s1.attrs == 0xf0) {
12543         tagged = true;
12544         s1.attrs = 0xff;
12545     }
12546 
12547     s1lo = extract32(s1.attrs, 0, 4);
12548     s2lo = extract32(s2.attrs, 0, 4);
12549     s1hi = extract32(s1.attrs, 4, 4);
12550     s2hi = extract32(s2.attrs, 4, 4);
12551 
12552     /* Combine shareability attributes (table D4-43) */
12553     if (s1.shareability == 2 || s2.shareability == 2) {
12554         /* if either are outer-shareable, the result is outer-shareable */
12555         ret.shareability = 2;
12556     } else if (s1.shareability == 3 || s2.shareability == 3) {
12557         /* if either are inner-shareable, the result is inner-shareable */
12558         ret.shareability = 3;
12559     } else {
12560         /* both non-shareable */
12561         ret.shareability = 0;
12562     }
12563 
12564     /* Combine memory type and cacheability attributes */
12565     if (s1hi == 0 || s2hi == 0) {
12566         /* Device has precedence over normal */
12567         if (s1lo == 0 || s2lo == 0) {
12568             /* nGnRnE has precedence over anything */
12569             ret.attrs = 0;
12570         } else if (s1lo == 4 || s2lo == 4) {
12571             /* non-Reordering has precedence over Reordering */
12572             ret.attrs = 4;  /* nGnRE */
12573         } else if (s1lo == 8 || s2lo == 8) {
12574             /* non-Gathering has precedence over Gathering */
12575             ret.attrs = 8;  /* nGRE */
12576         } else {
12577             ret.attrs = 0xc; /* GRE */
12578         }
12579 
12580         /* Any location for which the resultant memory type is any
12581          * type of Device memory is always treated as Outer Shareable.
12582          */
12583         ret.shareability = 2;
12584     } else { /* Normal memory */
12585         /* Outer/inner cacheability combine independently */
12586         ret.attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
12587                   | combine_cacheattr_nibble(s1lo, s2lo);
12588 
12589         if (ret.attrs == 0x44) {
12590             /* Any location for which the resultant memory type is Normal
12591              * Inner Non-cacheable, Outer Non-cacheable is always treated
12592              * as Outer Shareable.
12593              */
12594             ret.shareability = 2;
12595         }
12596     }
12597 
12598     /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
12599     if (tagged && ret.attrs == 0xff) {
12600         ret.attrs = 0xf0;
12601     }
12602 
12603     return ret;
12604 }
12605 
12606 
12607 /* get_phys_addr - get the physical address for this virtual address
12608  *
12609  * Find the physical address corresponding to the given virtual address,
12610  * by doing a translation table walk on MMU based systems or using the
12611  * MPU state on MPU based systems.
12612  *
12613  * Returns false if the translation was successful. Otherwise, phys_ptr, attrs,
12614  * prot and page_size may not be filled in, and the populated fsr value provides
12615  * information on why the translation aborted, in the format of a
12616  * DFSR/IFSR fault register, with the following caveats:
12617  *  * we honour the short vs long DFSR format differences.
12618  *  * the WnR bit is never set (the caller must do this).
12619  *  * for PSMAv5 based systems we don't bother to return a full FSR format
12620  *    value.
12621  *
12622  * @env: CPUARMState
12623  * @address: virtual address to get physical address for
12624  * @access_type: 0 for read, 1 for write, 2 for execute
12625  * @mmu_idx: MMU index indicating required translation regime
12626  * @phys_ptr: set to the physical address corresponding to the virtual address
12627  * @attrs: set to the memory transaction attributes to use
12628  * @prot: set to the permissions for the page containing phys_ptr
12629  * @page_size: set to the size of the page containing phys_ptr
12630  * @fi: set to fault info if the translation fails
12631  * @cacheattrs: (if non-NULL) set to the cacheability/shareability attributes
12632  */
12633 bool get_phys_addr(CPUARMState *env, target_ulong address,
12634                    MMUAccessType access_type, ARMMMUIdx mmu_idx,
12635                    hwaddr *phys_ptr, MemTxAttrs *attrs, int *prot,
12636                    target_ulong *page_size,
12637                    ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)
12638 {
12639     ARMMMUIdx s1_mmu_idx = stage_1_mmu_idx(mmu_idx);
12640 
12641     if (mmu_idx != s1_mmu_idx) {
12642         /* Call ourselves recursively to do the stage 1 and then stage 2
12643          * translations if mmu_idx is a two-stage regime.
12644          */
12645         if (arm_feature(env, ARM_FEATURE_EL2)) {
12646             hwaddr ipa;
12647             int s2_prot;
12648             int ret;
12649             ARMCacheAttrs cacheattrs2 = {};
12650             ARMMMUIdx s2_mmu_idx;
12651             bool is_el0;
12652 
12653             ret = get_phys_addr(env, address, access_type, s1_mmu_idx, &ipa,
12654                                 attrs, prot, page_size, fi, cacheattrs);
12655 
12656             /* If S1 fails or S2 is disabled, return early.  */
12657             if (ret || regime_translation_disabled(env, ARMMMUIdx_Stage2)) {
12658                 *phys_ptr = ipa;
12659                 return ret;
12660             }
12661 
12662             s2_mmu_idx = attrs->secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
12663             is_el0 = mmu_idx == ARMMMUIdx_E10_0 || mmu_idx == ARMMMUIdx_SE10_0;
12664 
12665             /* S1 is done. Now do S2 translation.  */
12666             ret = get_phys_addr_lpae(env, ipa, access_type, s2_mmu_idx, is_el0,
12667                                      phys_ptr, attrs, &s2_prot,
12668                                      page_size, fi, &cacheattrs2);
12669             fi->s2addr = ipa;
12670             /* Combine the S1 and S2 perms.  */
12671             *prot &= s2_prot;
12672 
12673             /* If S2 fails, return early.  */
12674             if (ret) {
12675                 return ret;
12676             }
12677 
12678             /* Combine the S1 and S2 cache attributes. */
12679             if (arm_hcr_el2_eff(env) & HCR_DC) {
12680                 /*
12681                  * HCR.DC forces the first stage attributes to
12682                  *  Normal Non-Shareable,
12683                  *  Inner Write-Back Read-Allocate Write-Allocate,
12684                  *  Outer Write-Back Read-Allocate Write-Allocate.
12685                  * Do not overwrite Tagged within attrs.
12686                  */
12687                 if (cacheattrs->attrs != 0xf0) {
12688                     cacheattrs->attrs = 0xff;
12689                 }
12690                 cacheattrs->shareability = 0;
12691             }
12692             *cacheattrs = combine_cacheattrs(*cacheattrs, cacheattrs2);
12693 
12694             /* Check if IPA translates to secure or non-secure PA space. */
12695             if (arm_is_secure_below_el3(env)) {
12696                 if (attrs->secure) {
12697                     attrs->secure =
12698                         !(env->cp15.vstcr_el2.raw_tcr & (VSTCR_SA | VSTCR_SW));
12699                 } else {
12700                     attrs->secure =
12701                         !((env->cp15.vtcr_el2.raw_tcr & (VTCR_NSA | VTCR_NSW))
12702                         || (env->cp15.vstcr_el2.raw_tcr & VSTCR_SA));
12703                 }
12704             }
12705             return 0;
12706         } else {
12707             /*
12708              * For non-EL2 CPUs a stage1+stage2 translation is just stage 1.
12709              */
12710             mmu_idx = stage_1_mmu_idx(mmu_idx);
12711         }
12712     }
12713 
12714     /* The page table entries may downgrade secure to non-secure, but
12715      * cannot upgrade an non-secure translation regime's attributes
12716      * to secure.
12717      */
12718     attrs->secure = regime_is_secure(env, mmu_idx);
12719     attrs->user = regime_is_user(env, mmu_idx);
12720 
12721     /* Fast Context Switch Extension. This doesn't exist at all in v8.
12722      * In v7 and earlier it affects all stage 1 translations.
12723      */
12724     if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
12725         && !arm_feature(env, ARM_FEATURE_V8)) {
12726         if (regime_el(env, mmu_idx) == 3) {
12727             address += env->cp15.fcseidr_s;
12728         } else {
12729             address += env->cp15.fcseidr_ns;
12730         }
12731     }
12732 
12733     if (arm_feature(env, ARM_FEATURE_PMSA)) {
12734         bool ret;
12735         *page_size = TARGET_PAGE_SIZE;
12736 
12737         if (arm_feature(env, ARM_FEATURE_V8)) {
12738             /* PMSAv8 */
12739             ret = get_phys_addr_pmsav8(env, address, access_type, mmu_idx,
12740                                        phys_ptr, attrs, prot, page_size, fi);
12741         } else if (arm_feature(env, ARM_FEATURE_V7)) {
12742             /* PMSAv7 */
12743             ret = get_phys_addr_pmsav7(env, address, access_type, mmu_idx,
12744                                        phys_ptr, prot, page_size, fi);
12745         } else {
12746             /* Pre-v7 MPU */
12747             ret = get_phys_addr_pmsav5(env, address, access_type, mmu_idx,
12748                                        phys_ptr, prot, fi);
12749         }
12750         qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
12751                       " mmu_idx %u -> %s (prot %c%c%c)\n",
12752                       access_type == MMU_DATA_LOAD ? "reading" :
12753                       (access_type == MMU_DATA_STORE ? "writing" : "execute"),
12754                       (uint32_t)address, mmu_idx,
12755                       ret ? "Miss" : "Hit",
12756                       *prot & PAGE_READ ? 'r' : '-',
12757                       *prot & PAGE_WRITE ? 'w' : '-',
12758                       *prot & PAGE_EXEC ? 'x' : '-');
12759 
12760         return ret;
12761     }
12762 
12763     /* Definitely a real MMU, not an MPU */
12764 
12765     if (regime_translation_disabled(env, mmu_idx)) {
12766         uint64_t hcr;
12767         uint8_t memattr;
12768 
12769         /*
12770          * MMU disabled.  S1 addresses within aa64 translation regimes are
12771          * still checked for bounds -- see AArch64.TranslateAddressS1Off.
12772          */
12773         if (mmu_idx != ARMMMUIdx_Stage2 && mmu_idx != ARMMMUIdx_Stage2_S) {
12774             int r_el = regime_el(env, mmu_idx);
12775             if (arm_el_is_aa64(env, r_el)) {
12776                 int pamax = arm_pamax(env_archcpu(env));
12777                 uint64_t tcr = env->cp15.tcr_el[r_el].raw_tcr;
12778                 int addrtop, tbi;
12779 
12780                 tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
12781                 if (access_type == MMU_INST_FETCH) {
12782                     tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
12783                 }
12784                 tbi = (tbi >> extract64(address, 55, 1)) & 1;
12785                 addrtop = (tbi ? 55 : 63);
12786 
12787                 if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
12788                     fi->type = ARMFault_AddressSize;
12789                     fi->level = 0;
12790                     fi->stage2 = false;
12791                     return 1;
12792                 }
12793 
12794                 /*
12795                  * When TBI is disabled, we've just validated that all of the
12796                  * bits above PAMax are zero, so logically we only need to
12797                  * clear the top byte for TBI.  But it's clearer to follow
12798                  * the pseudocode set of addrdesc.paddress.
12799                  */
12800                 address = extract64(address, 0, 52);
12801             }
12802         }
12803         *phys_ptr = address;
12804         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
12805         *page_size = TARGET_PAGE_SIZE;
12806 
12807         /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
12808         hcr = arm_hcr_el2_eff(env);
12809         cacheattrs->shareability = 0;
12810         if (hcr & HCR_DC) {
12811             if (hcr & HCR_DCT) {
12812                 memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
12813             } else {
12814                 memattr = 0xff;  /* Normal, WB, RWA */
12815             }
12816         } else if (access_type == MMU_INST_FETCH) {
12817             if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
12818                 memattr = 0xee;  /* Normal, WT, RA, NT */
12819             } else {
12820                 memattr = 0x44;  /* Normal, NC, No */
12821             }
12822             cacheattrs->shareability = 2; /* outer sharable */
12823         } else {
12824             memattr = 0x00;      /* Device, nGnRnE */
12825         }
12826         cacheattrs->attrs = memattr;
12827         return 0;
12828     }
12829 
12830     if (regime_using_lpae_format(env, mmu_idx)) {
12831         return get_phys_addr_lpae(env, address, access_type, mmu_idx, false,
12832                                   phys_ptr, attrs, prot, page_size,
12833                                   fi, cacheattrs);
12834     } else if (regime_sctlr(env, mmu_idx) & SCTLR_XP) {
12835         return get_phys_addr_v6(env, address, access_type, mmu_idx,
12836                                 phys_ptr, attrs, prot, page_size, fi);
12837     } else {
12838         return get_phys_addr_v5(env, address, access_type, mmu_idx,
12839                                     phys_ptr, prot, page_size, fi);
12840     }
12841 }
12842 
12843 hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
12844                                          MemTxAttrs *attrs)
12845 {
12846     ARMCPU *cpu = ARM_CPU(cs);
12847     CPUARMState *env = &cpu->env;
12848     hwaddr phys_addr;
12849     target_ulong page_size;
12850     int prot;
12851     bool ret;
12852     ARMMMUFaultInfo fi = {};
12853     ARMMMUIdx mmu_idx = arm_mmu_idx(env);
12854     ARMCacheAttrs cacheattrs = {};
12855 
12856     *attrs = (MemTxAttrs) {};
12857 
12858     ret = get_phys_addr(env, addr, MMU_DATA_LOAD, mmu_idx, &phys_addr,
12859                         attrs, &prot, &page_size, &fi, &cacheattrs);
12860 
12861     if (ret) {
12862         return -1;
12863     }
12864     return phys_addr;
12865 }
12866 
12867 #endif
12868 
12869 /* Note that signed overflow is undefined in C.  The following routines are
12870    careful to use unsigned types where modulo arithmetic is required.
12871    Failure to do so _will_ break on newer gcc.  */
12872 
12873 /* Signed saturating arithmetic.  */
12874 
12875 /* Perform 16-bit signed saturating addition.  */
12876 static inline uint16_t add16_sat(uint16_t a, uint16_t b)
12877 {
12878     uint16_t res;
12879 
12880     res = a + b;
12881     if (((res ^ a) & 0x8000) && !((a ^ b) & 0x8000)) {
12882         if (a & 0x8000)
12883             res = 0x8000;
12884         else
12885             res = 0x7fff;
12886     }
12887     return res;
12888 }
12889 
12890 /* Perform 8-bit signed saturating addition.  */
12891 static inline uint8_t add8_sat(uint8_t a, uint8_t b)
12892 {
12893     uint8_t res;
12894 
12895     res = a + b;
12896     if (((res ^ a) & 0x80) && !((a ^ b) & 0x80)) {
12897         if (a & 0x80)
12898             res = 0x80;
12899         else
12900             res = 0x7f;
12901     }
12902     return res;
12903 }
12904 
12905 /* Perform 16-bit signed saturating subtraction.  */
12906 static inline uint16_t sub16_sat(uint16_t a, uint16_t b)
12907 {
12908     uint16_t res;
12909 
12910     res = a - b;
12911     if (((res ^ a) & 0x8000) && ((a ^ b) & 0x8000)) {
12912         if (a & 0x8000)
12913             res = 0x8000;
12914         else
12915             res = 0x7fff;
12916     }
12917     return res;
12918 }
12919 
12920 /* Perform 8-bit signed saturating subtraction.  */
12921 static inline uint8_t sub8_sat(uint8_t a, uint8_t b)
12922 {
12923     uint8_t res;
12924 
12925     res = a - b;
12926     if (((res ^ a) & 0x80) && ((a ^ b) & 0x80)) {
12927         if (a & 0x80)
12928             res = 0x80;
12929         else
12930             res = 0x7f;
12931     }
12932     return res;
12933 }
12934 
12935 #define ADD16(a, b, n) RESULT(add16_sat(a, b), n, 16);
12936 #define SUB16(a, b, n) RESULT(sub16_sat(a, b), n, 16);
12937 #define ADD8(a, b, n)  RESULT(add8_sat(a, b), n, 8);
12938 #define SUB8(a, b, n)  RESULT(sub8_sat(a, b), n, 8);
12939 #define PFX q
12940 
12941 #include "op_addsub.h"
12942 
12943 /* Unsigned saturating arithmetic.  */
12944 static inline uint16_t add16_usat(uint16_t a, uint16_t b)
12945 {
12946     uint16_t res;
12947     res = a + b;
12948     if (res < a)
12949         res = 0xffff;
12950     return res;
12951 }
12952 
12953 static inline uint16_t sub16_usat(uint16_t a, uint16_t b)
12954 {
12955     if (a > b)
12956         return a - b;
12957     else
12958         return 0;
12959 }
12960 
12961 static inline uint8_t add8_usat(uint8_t a, uint8_t b)
12962 {
12963     uint8_t res;
12964     res = a + b;
12965     if (res < a)
12966         res = 0xff;
12967     return res;
12968 }
12969 
12970 static inline uint8_t sub8_usat(uint8_t a, uint8_t b)
12971 {
12972     if (a > b)
12973         return a - b;
12974     else
12975         return 0;
12976 }
12977 
12978 #define ADD16(a, b, n) RESULT(add16_usat(a, b), n, 16);
12979 #define SUB16(a, b, n) RESULT(sub16_usat(a, b), n, 16);
12980 #define ADD8(a, b, n)  RESULT(add8_usat(a, b), n, 8);
12981 #define SUB8(a, b, n)  RESULT(sub8_usat(a, b), n, 8);
12982 #define PFX uq
12983 
12984 #include "op_addsub.h"
12985 
12986 /* Signed modulo arithmetic.  */
12987 #define SARITH16(a, b, n, op) do { \
12988     int32_t sum; \
12989     sum = (int32_t)(int16_t)(a) op (int32_t)(int16_t)(b); \
12990     RESULT(sum, n, 16); \
12991     if (sum >= 0) \
12992         ge |= 3 << (n * 2); \
12993     } while(0)
12994 
12995 #define SARITH8(a, b, n, op) do { \
12996     int32_t sum; \
12997     sum = (int32_t)(int8_t)(a) op (int32_t)(int8_t)(b); \
12998     RESULT(sum, n, 8); \
12999     if (sum >= 0) \
13000         ge |= 1 << n; \
13001     } while(0)
13002 
13003 
13004 #define ADD16(a, b, n) SARITH16(a, b, n, +)
13005 #define SUB16(a, b, n) SARITH16(a, b, n, -)
13006 #define ADD8(a, b, n)  SARITH8(a, b, n, +)
13007 #define SUB8(a, b, n)  SARITH8(a, b, n, -)
13008 #define PFX s
13009 #define ARITH_GE
13010 
13011 #include "op_addsub.h"
13012 
13013 /* Unsigned modulo arithmetic.  */
13014 #define ADD16(a, b, n) do { \
13015     uint32_t sum; \
13016     sum = (uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b); \
13017     RESULT(sum, n, 16); \
13018     if ((sum >> 16) == 1) \
13019         ge |= 3 << (n * 2); \
13020     } while(0)
13021 
13022 #define ADD8(a, b, n) do { \
13023     uint32_t sum; \
13024     sum = (uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b); \
13025     RESULT(sum, n, 8); \
13026     if ((sum >> 8) == 1) \
13027         ge |= 1 << n; \
13028     } while(0)
13029 
13030 #define SUB16(a, b, n) do { \
13031     uint32_t sum; \
13032     sum = (uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b); \
13033     RESULT(sum, n, 16); \
13034     if ((sum >> 16) == 0) \
13035         ge |= 3 << (n * 2); \
13036     } while(0)
13037 
13038 #define SUB8(a, b, n) do { \
13039     uint32_t sum; \
13040     sum = (uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b); \
13041     RESULT(sum, n, 8); \
13042     if ((sum >> 8) == 0) \
13043         ge |= 1 << n; \
13044     } while(0)
13045 
13046 #define PFX u
13047 #define ARITH_GE
13048 
13049 #include "op_addsub.h"
13050 
13051 /* Halved signed arithmetic.  */
13052 #define ADD16(a, b, n) \
13053   RESULT(((int32_t)(int16_t)(a) + (int32_t)(int16_t)(b)) >> 1, n, 16)
13054 #define SUB16(a, b, n) \
13055   RESULT(((int32_t)(int16_t)(a) - (int32_t)(int16_t)(b)) >> 1, n, 16)
13056 #define ADD8(a, b, n) \
13057   RESULT(((int32_t)(int8_t)(a) + (int32_t)(int8_t)(b)) >> 1, n, 8)
13058 #define SUB8(a, b, n) \
13059   RESULT(((int32_t)(int8_t)(a) - (int32_t)(int8_t)(b)) >> 1, n, 8)
13060 #define PFX sh
13061 
13062 #include "op_addsub.h"
13063 
13064 /* Halved unsigned arithmetic.  */
13065 #define ADD16(a, b, n) \
13066   RESULT(((uint32_t)(uint16_t)(a) + (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13067 #define SUB16(a, b, n) \
13068   RESULT(((uint32_t)(uint16_t)(a) - (uint32_t)(uint16_t)(b)) >> 1, n, 16)
13069 #define ADD8(a, b, n) \
13070   RESULT(((uint32_t)(uint8_t)(a) + (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13071 #define SUB8(a, b, n) \
13072   RESULT(((uint32_t)(uint8_t)(a) - (uint32_t)(uint8_t)(b)) >> 1, n, 8)
13073 #define PFX uh
13074 
13075 #include "op_addsub.h"
13076 
13077 static inline uint8_t do_usad(uint8_t a, uint8_t b)
13078 {
13079     if (a > b)
13080         return a - b;
13081     else
13082         return b - a;
13083 }
13084 
13085 /* Unsigned sum of absolute byte differences.  */
13086 uint32_t HELPER(usad8)(uint32_t a, uint32_t b)
13087 {
13088     uint32_t sum;
13089     sum = do_usad(a, b);
13090     sum += do_usad(a >> 8, b >> 8);
13091     sum += do_usad(a >> 16, b >> 16);
13092     sum += do_usad(a >> 24, b >> 24);
13093     return sum;
13094 }
13095 
13096 /* For ARMv6 SEL instruction.  */
13097 uint32_t HELPER(sel_flags)(uint32_t flags, uint32_t a, uint32_t b)
13098 {
13099     uint32_t mask;
13100 
13101     mask = 0;
13102     if (flags & 1)
13103         mask |= 0xff;
13104     if (flags & 2)
13105         mask |= 0xff00;
13106     if (flags & 4)
13107         mask |= 0xff0000;
13108     if (flags & 8)
13109         mask |= 0xff000000;
13110     return (a & mask) | (b & ~mask);
13111 }
13112 
13113 /* CRC helpers.
13114  * The upper bytes of val (above the number specified by 'bytes') must have
13115  * been zeroed out by the caller.
13116  */
13117 uint32_t HELPER(crc32)(uint32_t acc, uint32_t val, uint32_t bytes)
13118 {
13119     uint8_t buf[4];
13120 
13121     stl_le_p(buf, val);
13122 
13123     /* zlib crc32 converts the accumulator and output to one's complement.  */
13124     return crc32(acc ^ 0xffffffff, buf, bytes) ^ 0xffffffff;
13125 }
13126 
13127 uint32_t HELPER(crc32c)(uint32_t acc, uint32_t val, uint32_t bytes)
13128 {
13129     uint8_t buf[4];
13130 
13131     stl_le_p(buf, val);
13132 
13133     /* Linux crc32c converts the output to one's complement.  */
13134     return crc32c(acc, buf, bytes) ^ 0xffffffff;
13135 }
13136 
13137 /* Return the exception level to which FP-disabled exceptions should
13138  * be taken, or 0 if FP is enabled.
13139  */
13140 int fp_exception_el(CPUARMState *env, int cur_el)
13141 {
13142 #ifndef CONFIG_USER_ONLY
13143     /* CPACR and the CPTR registers don't exist before v6, so FP is
13144      * always accessible
13145      */
13146     if (!arm_feature(env, ARM_FEATURE_V6)) {
13147         return 0;
13148     }
13149 
13150     if (arm_feature(env, ARM_FEATURE_M)) {
13151         /* CPACR can cause a NOCP UsageFault taken to current security state */
13152         if (!v7m_cpacr_pass(env, env->v7m.secure, cur_el != 0)) {
13153             return 1;
13154         }
13155 
13156         if (arm_feature(env, ARM_FEATURE_M_SECURITY) && !env->v7m.secure) {
13157             if (!extract32(env->v7m.nsacr, 10, 1)) {
13158                 /* FP insns cause a NOCP UsageFault taken to Secure */
13159                 return 3;
13160             }
13161         }
13162 
13163         return 0;
13164     }
13165 
13166     /* The CPACR controls traps to EL1, or PL1 if we're 32 bit:
13167      * 0, 2 : trap EL0 and EL1/PL1 accesses
13168      * 1    : trap only EL0 accesses
13169      * 3    : trap no accesses
13170      * This register is ignored if E2H+TGE are both set.
13171      */
13172     if ((arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13173         int fpen = extract32(env->cp15.cpacr_el1, 20, 2);
13174 
13175         switch (fpen) {
13176         case 0:
13177         case 2:
13178             if (cur_el == 0 || cur_el == 1) {
13179                 /* Trap to PL1, which might be EL1 or EL3 */
13180                 if (arm_is_secure(env) && !arm_el_is_aa64(env, 3)) {
13181                     return 3;
13182                 }
13183                 return 1;
13184             }
13185             if (cur_el == 3 && !is_a64(env)) {
13186                 /* Secure PL1 running at EL3 */
13187                 return 3;
13188             }
13189             break;
13190         case 1:
13191             if (cur_el == 0) {
13192                 return 1;
13193             }
13194             break;
13195         case 3:
13196             break;
13197         }
13198     }
13199 
13200     /*
13201      * The NSACR allows A-profile AArch32 EL3 and M-profile secure mode
13202      * to control non-secure access to the FPU. It doesn't have any
13203      * effect if EL3 is AArch64 or if EL3 doesn't exist at all.
13204      */
13205     if ((arm_feature(env, ARM_FEATURE_EL3) && !arm_el_is_aa64(env, 3) &&
13206          cur_el <= 2 && !arm_is_secure_below_el3(env))) {
13207         if (!extract32(env->cp15.nsacr, 10, 1)) {
13208             /* FP insns act as UNDEF */
13209             return cur_el == 2 ? 2 : 1;
13210         }
13211     }
13212 
13213     /* For the CPTR registers we don't need to guard with an ARM_FEATURE
13214      * check because zero bits in the registers mean "don't trap".
13215      */
13216 
13217     /* CPTR_EL2 : present in v7VE or v8 */
13218     if (cur_el <= 2 && extract32(env->cp15.cptr_el[2], 10, 1)
13219         && arm_is_el2_enabled(env)) {
13220         /* Trap FP ops at EL2, NS-EL1 or NS-EL0 to EL2 */
13221         return 2;
13222     }
13223 
13224     /* CPTR_EL3 : present in v8 */
13225     if (extract32(env->cp15.cptr_el[3], 10, 1)) {
13226         /* Trap all FP ops to EL3 */
13227         return 3;
13228     }
13229 #endif
13230     return 0;
13231 }
13232 
13233 /* Return the exception level we're running at if this is our mmu_idx */
13234 int arm_mmu_idx_to_el(ARMMMUIdx mmu_idx)
13235 {
13236     if (mmu_idx & ARM_MMU_IDX_M) {
13237         return mmu_idx & ARM_MMU_IDX_M_PRIV;
13238     }
13239 
13240     switch (mmu_idx) {
13241     case ARMMMUIdx_E10_0:
13242     case ARMMMUIdx_E20_0:
13243     case ARMMMUIdx_SE10_0:
13244     case ARMMMUIdx_SE20_0:
13245         return 0;
13246     case ARMMMUIdx_E10_1:
13247     case ARMMMUIdx_E10_1_PAN:
13248     case ARMMMUIdx_SE10_1:
13249     case ARMMMUIdx_SE10_1_PAN:
13250         return 1;
13251     case ARMMMUIdx_E2:
13252     case ARMMMUIdx_E20_2:
13253     case ARMMMUIdx_E20_2_PAN:
13254     case ARMMMUIdx_SE2:
13255     case ARMMMUIdx_SE20_2:
13256     case ARMMMUIdx_SE20_2_PAN:
13257         return 2;
13258     case ARMMMUIdx_SE3:
13259         return 3;
13260     default:
13261         g_assert_not_reached();
13262     }
13263 }
13264 
13265 #ifndef CONFIG_TCG
13266 ARMMMUIdx arm_v7m_mmu_idx_for_secstate(CPUARMState *env, bool secstate)
13267 {
13268     g_assert_not_reached();
13269 }
13270 #endif
13271 
13272 ARMMMUIdx arm_mmu_idx_el(CPUARMState *env, int el)
13273 {
13274     ARMMMUIdx idx;
13275     uint64_t hcr;
13276 
13277     if (arm_feature(env, ARM_FEATURE_M)) {
13278         return arm_v7m_mmu_idx_for_secstate(env, env->v7m.secure);
13279     }
13280 
13281     /* See ARM pseudo-function ELIsInHost.  */
13282     switch (el) {
13283     case 0:
13284         hcr = arm_hcr_el2_eff(env);
13285         if ((hcr & (HCR_E2H | HCR_TGE)) == (HCR_E2H | HCR_TGE)) {
13286             idx = ARMMMUIdx_E20_0;
13287         } else {
13288             idx = ARMMMUIdx_E10_0;
13289         }
13290         break;
13291     case 1:
13292         if (env->pstate & PSTATE_PAN) {
13293             idx = ARMMMUIdx_E10_1_PAN;
13294         } else {
13295             idx = ARMMMUIdx_E10_1;
13296         }
13297         break;
13298     case 2:
13299         /* Note that TGE does not apply at EL2.  */
13300         if (arm_hcr_el2_eff(env) & HCR_E2H) {
13301             if (env->pstate & PSTATE_PAN) {
13302                 idx = ARMMMUIdx_E20_2_PAN;
13303             } else {
13304                 idx = ARMMMUIdx_E20_2;
13305             }
13306         } else {
13307             idx = ARMMMUIdx_E2;
13308         }
13309         break;
13310     case 3:
13311         return ARMMMUIdx_SE3;
13312     default:
13313         g_assert_not_reached();
13314     }
13315 
13316     if (arm_is_secure_below_el3(env)) {
13317         idx &= ~ARM_MMU_IDX_A_NS;
13318     }
13319 
13320     return idx;
13321 }
13322 
13323 ARMMMUIdx arm_mmu_idx(CPUARMState *env)
13324 {
13325     return arm_mmu_idx_el(env, arm_current_el(env));
13326 }
13327 
13328 #ifndef CONFIG_USER_ONLY
13329 ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
13330 {
13331     return stage_1_mmu_idx(arm_mmu_idx(env));
13332 }
13333 #endif
13334 
13335 static CPUARMTBFlags rebuild_hflags_common(CPUARMState *env, int fp_el,
13336                                            ARMMMUIdx mmu_idx,
13337                                            CPUARMTBFlags flags)
13338 {
13339     DP_TBFLAG_ANY(flags, FPEXC_EL, fp_el);
13340     DP_TBFLAG_ANY(flags, MMUIDX, arm_to_core_mmu_idx(mmu_idx));
13341 
13342     if (arm_singlestep_active(env)) {
13343         DP_TBFLAG_ANY(flags, SS_ACTIVE, 1);
13344     }
13345     return flags;
13346 }
13347 
13348 static CPUARMTBFlags rebuild_hflags_common_32(CPUARMState *env, int fp_el,
13349                                               ARMMMUIdx mmu_idx,
13350                                               CPUARMTBFlags flags)
13351 {
13352     bool sctlr_b = arm_sctlr_b(env);
13353 
13354     if (sctlr_b) {
13355         DP_TBFLAG_A32(flags, SCTLR__B, 1);
13356     }
13357     if (arm_cpu_data_is_big_endian_a32(env, sctlr_b)) {
13358         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13359     }
13360     DP_TBFLAG_A32(flags, NS, !access_secure_reg(env));
13361 
13362     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13363 }
13364 
13365 static CPUARMTBFlags rebuild_hflags_m32(CPUARMState *env, int fp_el,
13366                                         ARMMMUIdx mmu_idx)
13367 {
13368     CPUARMTBFlags flags = {};
13369     uint32_t ccr = env->v7m.ccr[env->v7m.secure];
13370 
13371     /* Without HaveMainExt, CCR.UNALIGN_TRP is RES1. */
13372     if (ccr & R_V7M_CCR_UNALIGN_TRP_MASK) {
13373         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13374     }
13375 
13376     if (arm_v7m_is_handler_mode(env)) {
13377         DP_TBFLAG_M32(flags, HANDLER, 1);
13378     }
13379 
13380     /*
13381      * v8M always applies stack limit checks unless CCR.STKOFHFNMIGN
13382      * is suppressing them because the requested execution priority
13383      * is less than 0.
13384      */
13385     if (arm_feature(env, ARM_FEATURE_V8) &&
13386         !((mmu_idx & ARM_MMU_IDX_M_NEGPRI) &&
13387           (ccr & R_V7M_CCR_STKOFHFNMIGN_MASK))) {
13388         DP_TBFLAG_M32(flags, STACKCHECK, 1);
13389     }
13390 
13391     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13392 }
13393 
13394 static CPUARMTBFlags rebuild_hflags_aprofile(CPUARMState *env)
13395 {
13396     CPUARMTBFlags flags = {};
13397 
13398     DP_TBFLAG_ANY(flags, DEBUG_TARGET_EL, arm_debug_target_el(env));
13399     return flags;
13400 }
13401 
13402 static CPUARMTBFlags rebuild_hflags_a32(CPUARMState *env, int fp_el,
13403                                         ARMMMUIdx mmu_idx)
13404 {
13405     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13406     int el = arm_current_el(env);
13407 
13408     if (arm_sctlr(env, el) & SCTLR_A) {
13409         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13410     }
13411 
13412     if (arm_el_is_aa64(env, 1)) {
13413         DP_TBFLAG_A32(flags, VFPEN, 1);
13414     }
13415 
13416     if (el < 2 && env->cp15.hstr_el2 &&
13417         (arm_hcr_el2_eff(env) & (HCR_E2H | HCR_TGE)) != (HCR_E2H | HCR_TGE)) {
13418         DP_TBFLAG_A32(flags, HSTR_ACTIVE, 1);
13419     }
13420 
13421     if (env->uncached_cpsr & CPSR_IL) {
13422         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13423     }
13424 
13425     return rebuild_hflags_common_32(env, fp_el, mmu_idx, flags);
13426 }
13427 
13428 static CPUARMTBFlags rebuild_hflags_a64(CPUARMState *env, int el, int fp_el,
13429                                         ARMMMUIdx mmu_idx)
13430 {
13431     CPUARMTBFlags flags = rebuild_hflags_aprofile(env);
13432     ARMMMUIdx stage1 = stage_1_mmu_idx(mmu_idx);
13433     uint64_t tcr = regime_tcr(env, mmu_idx)->raw_tcr;
13434     uint64_t sctlr;
13435     int tbii, tbid;
13436 
13437     DP_TBFLAG_ANY(flags, AARCH64_STATE, 1);
13438 
13439     /* Get control bits for tagged addresses.  */
13440     tbid = aa64_va_parameter_tbi(tcr, mmu_idx);
13441     tbii = tbid & ~aa64_va_parameter_tbid(tcr, mmu_idx);
13442 
13443     DP_TBFLAG_A64(flags, TBII, tbii);
13444     DP_TBFLAG_A64(flags, TBID, tbid);
13445 
13446     if (cpu_isar_feature(aa64_sve, env_archcpu(env))) {
13447         int sve_el = sve_exception_el(env, el);
13448         uint32_t zcr_len;
13449 
13450         /*
13451          * If SVE is disabled, but FP is enabled,
13452          * then the effective len is 0.
13453          */
13454         if (sve_el != 0 && fp_el == 0) {
13455             zcr_len = 0;
13456         } else {
13457             zcr_len = sve_zcr_len_for_el(env, el);
13458         }
13459         DP_TBFLAG_A64(flags, SVEEXC_EL, sve_el);
13460         DP_TBFLAG_A64(flags, ZCR_LEN, zcr_len);
13461     }
13462 
13463     sctlr = regime_sctlr(env, stage1);
13464 
13465     if (sctlr & SCTLR_A) {
13466         DP_TBFLAG_ANY(flags, ALIGN_MEM, 1);
13467     }
13468 
13469     if (arm_cpu_data_is_big_endian_a64(el, sctlr)) {
13470         DP_TBFLAG_ANY(flags, BE_DATA, 1);
13471     }
13472 
13473     if (cpu_isar_feature(aa64_pauth, env_archcpu(env))) {
13474         /*
13475          * In order to save space in flags, we record only whether
13476          * pauth is "inactive", meaning all insns are implemented as
13477          * a nop, or "active" when some action must be performed.
13478          * The decision of which action to take is left to a helper.
13479          */
13480         if (sctlr & (SCTLR_EnIA | SCTLR_EnIB | SCTLR_EnDA | SCTLR_EnDB)) {
13481             DP_TBFLAG_A64(flags, PAUTH_ACTIVE, 1);
13482         }
13483     }
13484 
13485     if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13486         /* Note that SCTLR_EL[23].BT == SCTLR_BT1.  */
13487         if (sctlr & (el == 0 ? SCTLR_BT0 : SCTLR_BT1)) {
13488             DP_TBFLAG_A64(flags, BT, 1);
13489         }
13490     }
13491 
13492     /* Compute the condition for using AccType_UNPRIV for LDTR et al. */
13493     if (!(env->pstate & PSTATE_UAO)) {
13494         switch (mmu_idx) {
13495         case ARMMMUIdx_E10_1:
13496         case ARMMMUIdx_E10_1_PAN:
13497         case ARMMMUIdx_SE10_1:
13498         case ARMMMUIdx_SE10_1_PAN:
13499             /* TODO: ARMv8.3-NV */
13500             DP_TBFLAG_A64(flags, UNPRIV, 1);
13501             break;
13502         case ARMMMUIdx_E20_2:
13503         case ARMMMUIdx_E20_2_PAN:
13504         case ARMMMUIdx_SE20_2:
13505         case ARMMMUIdx_SE20_2_PAN:
13506             /*
13507              * Note that EL20_2 is gated by HCR_EL2.E2H == 1, but EL20_0 is
13508              * gated by HCR_EL2.<E2H,TGE> == '11', and so is LDTR.
13509              */
13510             if (env->cp15.hcr_el2 & HCR_TGE) {
13511                 DP_TBFLAG_A64(flags, UNPRIV, 1);
13512             }
13513             break;
13514         default:
13515             break;
13516         }
13517     }
13518 
13519     if (env->pstate & PSTATE_IL) {
13520         DP_TBFLAG_ANY(flags, PSTATE__IL, 1);
13521     }
13522 
13523     if (cpu_isar_feature(aa64_mte, env_archcpu(env))) {
13524         /*
13525          * Set MTE_ACTIVE if any access may be Checked, and leave clear
13526          * if all accesses must be Unchecked:
13527          * 1) If no TBI, then there are no tags in the address to check,
13528          * 2) If Tag Check Override, then all accesses are Unchecked,
13529          * 3) If Tag Check Fail == 0, then Checked access have no effect,
13530          * 4) If no Allocation Tag Access, then all accesses are Unchecked.
13531          */
13532         if (allocation_tag_access_enabled(env, el, sctlr)) {
13533             DP_TBFLAG_A64(flags, ATA, 1);
13534             if (tbid
13535                 && !(env->pstate & PSTATE_TCO)
13536                 && (sctlr & (el == 0 ? SCTLR_TCF0 : SCTLR_TCF))) {
13537                 DP_TBFLAG_A64(flags, MTE_ACTIVE, 1);
13538             }
13539         }
13540         /* And again for unprivileged accesses, if required.  */
13541         if (EX_TBFLAG_A64(flags, UNPRIV)
13542             && tbid
13543             && !(env->pstate & PSTATE_TCO)
13544             && (sctlr & SCTLR_TCF0)
13545             && allocation_tag_access_enabled(env, 0, sctlr)) {
13546             DP_TBFLAG_A64(flags, MTE0_ACTIVE, 1);
13547         }
13548         /* Cache TCMA as well as TBI. */
13549         DP_TBFLAG_A64(flags, TCMA, aa64_va_parameter_tcma(tcr, mmu_idx));
13550     }
13551 
13552     return rebuild_hflags_common(env, fp_el, mmu_idx, flags);
13553 }
13554 
13555 static CPUARMTBFlags rebuild_hflags_internal(CPUARMState *env)
13556 {
13557     int el = arm_current_el(env);
13558     int fp_el = fp_exception_el(env, el);
13559     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13560 
13561     if (is_a64(env)) {
13562         return rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13563     } else if (arm_feature(env, ARM_FEATURE_M)) {
13564         return rebuild_hflags_m32(env, fp_el, mmu_idx);
13565     } else {
13566         return rebuild_hflags_a32(env, fp_el, mmu_idx);
13567     }
13568 }
13569 
13570 void arm_rebuild_hflags(CPUARMState *env)
13571 {
13572     env->hflags = rebuild_hflags_internal(env);
13573 }
13574 
13575 /*
13576  * If we have triggered a EL state change we can't rely on the
13577  * translator having passed it to us, we need to recompute.
13578  */
13579 void HELPER(rebuild_hflags_m32_newel)(CPUARMState *env)
13580 {
13581     int el = arm_current_el(env);
13582     int fp_el = fp_exception_el(env, el);
13583     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13584 
13585     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13586 }
13587 
13588 void HELPER(rebuild_hflags_m32)(CPUARMState *env, int el)
13589 {
13590     int fp_el = fp_exception_el(env, el);
13591     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13592 
13593     env->hflags = rebuild_hflags_m32(env, fp_el, mmu_idx);
13594 }
13595 
13596 /*
13597  * If we have triggered a EL state change we can't rely on the
13598  * translator having passed it to us, we need to recompute.
13599  */
13600 void HELPER(rebuild_hflags_a32_newel)(CPUARMState *env)
13601 {
13602     int el = arm_current_el(env);
13603     int fp_el = fp_exception_el(env, el);
13604     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13605     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13606 }
13607 
13608 void HELPER(rebuild_hflags_a32)(CPUARMState *env, int el)
13609 {
13610     int fp_el = fp_exception_el(env, el);
13611     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13612 
13613     env->hflags = rebuild_hflags_a32(env, fp_el, mmu_idx);
13614 }
13615 
13616 void HELPER(rebuild_hflags_a64)(CPUARMState *env, int el)
13617 {
13618     int fp_el = fp_exception_el(env, el);
13619     ARMMMUIdx mmu_idx = arm_mmu_idx_el(env, el);
13620 
13621     env->hflags = rebuild_hflags_a64(env, el, fp_el, mmu_idx);
13622 }
13623 
13624 static inline void assert_hflags_rebuild_correctly(CPUARMState *env)
13625 {
13626 #ifdef CONFIG_DEBUG_TCG
13627     CPUARMTBFlags c = env->hflags;
13628     CPUARMTBFlags r = rebuild_hflags_internal(env);
13629 
13630     if (unlikely(c.flags != r.flags || c.flags2 != r.flags2)) {
13631         fprintf(stderr, "TCG hflags mismatch "
13632                         "(current:(0x%08x,0x" TARGET_FMT_lx ")"
13633                         " rebuilt:(0x%08x,0x" TARGET_FMT_lx ")\n",
13634                 c.flags, c.flags2, r.flags, r.flags2);
13635         abort();
13636     }
13637 #endif
13638 }
13639 
13640 static bool mve_no_pred(CPUARMState *env)
13641 {
13642     /*
13643      * Return true if there is definitely no predication of MVE
13644      * instructions by VPR or LTPSIZE. (Returning false even if there
13645      * isn't any predication is OK; generated code will just be
13646      * a little worse.)
13647      * If the CPU does not implement MVE then this TB flag is always 0.
13648      *
13649      * NOTE: if you change this logic, the "recalculate s->mve_no_pred"
13650      * logic in gen_update_fp_context() needs to be updated to match.
13651      *
13652      * We do not include the effect of the ECI bits here -- they are
13653      * tracked in other TB flags. This simplifies the logic for
13654      * "when did we emit code that changes the MVE_NO_PRED TB flag
13655      * and thus need to end the TB?".
13656      */
13657     if (cpu_isar_feature(aa32_mve, env_archcpu(env))) {
13658         return false;
13659     }
13660     if (env->v7m.vpr) {
13661         return false;
13662     }
13663     if (env->v7m.ltpsize < 4) {
13664         return false;
13665     }
13666     return true;
13667 }
13668 
13669 void cpu_get_tb_cpu_state(CPUARMState *env, target_ulong *pc,
13670                           target_ulong *cs_base, uint32_t *pflags)
13671 {
13672     CPUARMTBFlags flags;
13673 
13674     assert_hflags_rebuild_correctly(env);
13675     flags = env->hflags;
13676 
13677     if (EX_TBFLAG_ANY(flags, AARCH64_STATE)) {
13678         *pc = env->pc;
13679         if (cpu_isar_feature(aa64_bti, env_archcpu(env))) {
13680             DP_TBFLAG_A64(flags, BTYPE, env->btype);
13681         }
13682     } else {
13683         *pc = env->regs[15];
13684 
13685         if (arm_feature(env, ARM_FEATURE_M)) {
13686             if (arm_feature(env, ARM_FEATURE_M_SECURITY) &&
13687                 FIELD_EX32(env->v7m.fpccr[M_REG_S], V7M_FPCCR, S)
13688                 != env->v7m.secure) {
13689                 DP_TBFLAG_M32(flags, FPCCR_S_WRONG, 1);
13690             }
13691 
13692             if ((env->v7m.fpccr[env->v7m.secure] & R_V7M_FPCCR_ASPEN_MASK) &&
13693                 (!(env->v7m.control[M_REG_S] & R_V7M_CONTROL_FPCA_MASK) ||
13694                  (env->v7m.secure &&
13695                   !(env->v7m.control[M_REG_S] & R_V7M_CONTROL_SFPA_MASK)))) {
13696                 /*
13697                  * ASPEN is set, but FPCA/SFPA indicate that there is no
13698                  * active FP context; we must create a new FP context before
13699                  * executing any FP insn.
13700                  */
13701                 DP_TBFLAG_M32(flags, NEW_FP_CTXT_NEEDED, 1);
13702             }
13703 
13704             bool is_secure = env->v7m.fpccr[M_REG_S] & R_V7M_FPCCR_S_MASK;
13705             if (env->v7m.fpccr[is_secure] & R_V7M_FPCCR_LSPACT_MASK) {
13706                 DP_TBFLAG_M32(flags, LSPACT, 1);
13707             }
13708 
13709             if (mve_no_pred(env)) {
13710                 DP_TBFLAG_M32(flags, MVE_NO_PRED, 1);
13711             }
13712         } else {
13713             /*
13714              * Note that XSCALE_CPAR shares bits with VECSTRIDE.
13715              * Note that VECLEN+VECSTRIDE are RES0 for M-profile.
13716              */
13717             if (arm_feature(env, ARM_FEATURE_XSCALE)) {
13718                 DP_TBFLAG_A32(flags, XSCALE_CPAR, env->cp15.c15_cpar);
13719             } else {
13720                 DP_TBFLAG_A32(flags, VECLEN, env->vfp.vec_len);
13721                 DP_TBFLAG_A32(flags, VECSTRIDE, env->vfp.vec_stride);
13722             }
13723             if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30)) {
13724                 DP_TBFLAG_A32(flags, VFPEN, 1);
13725             }
13726         }
13727 
13728         DP_TBFLAG_AM32(flags, THUMB, env->thumb);
13729         DP_TBFLAG_AM32(flags, CONDEXEC, env->condexec_bits);
13730     }
13731 
13732     /*
13733      * The SS_ACTIVE and PSTATE_SS bits correspond to the state machine
13734      * states defined in the ARM ARM for software singlestep:
13735      *  SS_ACTIVE   PSTATE.SS   State
13736      *     0            x       Inactive (the TB flag for SS is always 0)
13737      *     1            0       Active-pending
13738      *     1            1       Active-not-pending
13739      * SS_ACTIVE is set in hflags; PSTATE__SS is computed every TB.
13740      */
13741     if (EX_TBFLAG_ANY(flags, SS_ACTIVE) && (env->pstate & PSTATE_SS)) {
13742         DP_TBFLAG_ANY(flags, PSTATE__SS, 1);
13743     }
13744 
13745     *pflags = flags.flags;
13746     *cs_base = flags.flags2;
13747 }
13748 
13749 #ifdef TARGET_AARCH64
13750 /*
13751  * The manual says that when SVE is enabled and VQ is widened the
13752  * implementation is allowed to zero the previously inaccessible
13753  * portion of the registers.  The corollary to that is that when
13754  * SVE is enabled and VQ is narrowed we are also allowed to zero
13755  * the now inaccessible portion of the registers.
13756  *
13757  * The intent of this is that no predicate bit beyond VQ is ever set.
13758  * Which means that some operations on predicate registers themselves
13759  * may operate on full uint64_t or even unrolled across the maximum
13760  * uint64_t[4].  Performing 4 bits of host arithmetic unconditionally
13761  * may well be cheaper than conditionals to restrict the operation
13762  * to the relevant portion of a uint16_t[16].
13763  */
13764 void aarch64_sve_narrow_vq(CPUARMState *env, unsigned vq)
13765 {
13766     int i, j;
13767     uint64_t pmask;
13768 
13769     assert(vq >= 1 && vq <= ARM_MAX_VQ);
13770     assert(vq <= env_archcpu(env)->sve_max_vq);
13771 
13772     /* Zap the high bits of the zregs.  */
13773     for (i = 0; i < 32; i++) {
13774         memset(&env->vfp.zregs[i].d[2 * vq], 0, 16 * (ARM_MAX_VQ - vq));
13775     }
13776 
13777     /* Zap the high bits of the pregs and ffr.  */
13778     pmask = 0;
13779     if (vq & 3) {
13780         pmask = ~(-1ULL << (16 * (vq & 3)));
13781     }
13782     for (j = vq / 4; j < ARM_MAX_VQ / 4; j++) {
13783         for (i = 0; i < 17; ++i) {
13784             env->vfp.pregs[i].p[j] &= pmask;
13785         }
13786         pmask = 0;
13787     }
13788 }
13789 
13790 /*
13791  * Notice a change in SVE vector size when changing EL.
13792  */
13793 void aarch64_sve_change_el(CPUARMState *env, int old_el,
13794                            int new_el, bool el0_a64)
13795 {
13796     ARMCPU *cpu = env_archcpu(env);
13797     int old_len, new_len;
13798     bool old_a64, new_a64;
13799 
13800     /* Nothing to do if no SVE.  */
13801     if (!cpu_isar_feature(aa64_sve, cpu)) {
13802         return;
13803     }
13804 
13805     /* Nothing to do if FP is disabled in either EL.  */
13806     if (fp_exception_el(env, old_el) || fp_exception_el(env, new_el)) {
13807         return;
13808     }
13809 
13810     /*
13811      * DDI0584A.d sec 3.2: "If SVE instructions are disabled or trapped
13812      * at ELx, or not available because the EL is in AArch32 state, then
13813      * for all purposes other than a direct read, the ZCR_ELx.LEN field
13814      * has an effective value of 0".
13815      *
13816      * Consider EL2 (aa64, vq=4) -> EL0 (aa32) -> EL1 (aa64, vq=0).
13817      * If we ignore aa32 state, we would fail to see the vq4->vq0 transition
13818      * from EL2->EL1.  Thus we go ahead and narrow when entering aa32 so that
13819      * we already have the correct register contents when encountering the
13820      * vq0->vq0 transition between EL0->EL1.
13821      */
13822     old_a64 = old_el ? arm_el_is_aa64(env, old_el) : el0_a64;
13823     old_len = (old_a64 && !sve_exception_el(env, old_el)
13824                ? sve_zcr_len_for_el(env, old_el) : 0);
13825     new_a64 = new_el ? arm_el_is_aa64(env, new_el) : el0_a64;
13826     new_len = (new_a64 && !sve_exception_el(env, new_el)
13827                ? sve_zcr_len_for_el(env, new_el) : 0);
13828 
13829     /* When changing vector length, clear inaccessible state.  */
13830     if (new_len < old_len) {
13831         aarch64_sve_narrow_vq(env, new_len + 1);
13832     }
13833 }
13834 #endif
13835